问:
Reprocessing a message when an error occurs while processing it in the Kafka Stream
I have simple Spring application based on Kafka Streams which consumes message from incoming topic, doing map transformation and printing this message. KStream configured like this

@Bean
public KStream<?, ?> processingPipeline(StreamsBuilder builder, MyTransformer myTransformer,
         PrintAction printAction, String topicName) {
    KStream<String, JsonNode> source = builder.stream(topicName,
                Consumed.with(Serdes.String(), new JsonSerde<>(JsonNode.class)));
    // @formatter:off
    source
        .map(myTransformer)
        .foreach(printAction);
    // @formatter:on
    return source;
}
```

Inside MyTransformer I'm calling external microservice which can be down at this time. If call failed (typically throwing RuntimeException), I can't do my transformation.

The question is here any way to reprocess message in Streams application again if any error happened during previous processing?

Based on my current research here is no way to do so, the only possibility I have is to push the message into dead letters topic and try to process it in the future if it failes again I push it into DLT again and do retries this way.

答:
if any uncaught exception happens during Kafka Streams processing, your stream will change status to ERROR and stop consuming incoming messages for partition on which error occurred.
You need to catch exceptions by yourself. Retries could be achieved either: 1) using Spring RetryTemplate to invoke external microservice (but keep in mind that you will have delays of consuming messages from a specific partition), or 2) push failed message into another topic for later reprocessing (as you suggested)

Update since kafka-streams 2.8.0

since kafka-streams 2.8.0, you have the ability to automatically replace failed stream thread (that caused by uncaught exception)
using KafkaStreams method void setUncaughtExceptionHandler(StreamsUncaughtExceptionHandler eh); with StreamThreadExceptionResponse.REPLACE_THREAD. For more details please take a look at Kafka Streams Specific Uncaught Exception Handler

```<code>kafkaStreams.setUncaughtExceptionHandler(ex -> {
    log.error("Kafka-Streams uncaught exception occurred. Stream will be replaced with new thread", ex);
    return StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.REPLACE_THREAD;
});
</code>```

Body:
I have simple Spring application based on Kafka Streams which consumes message from incoming topic, doing map transformation and printing this message. KStream configured like this

@Bean
public KStream<?, ?> processingPipeline(StreamsBuilder builder, MyTransformer myTransformer,
         PrintAction printAction, String topicName) {
    KStream<String, JsonNode> source = builder.stream(topicName,
                Consumed.with(Serdes.String(), new JsonSerde<>(JsonNode.class)));
    // @formatter:off
    source
        .map(myTransformer)
        .foreach(printAction);
    // @formatter:on
    return source;
}

Inside MyTransformer I'm calling external microservice which can be down at this time. If call failed (typically throwing RuntimeException), I can't do my transformation.

The question is here any way to reprocess message in Streams application again if any error happened during previous processing?

Based on my current research here is no way to do so, the only possibility I have is to push the message into dead letters topic and try to process it in the future if it failes again I push it into DLT again and do retries this way.

Body:
if any uncaught exception happens during Kafka Streams processing, your stream will change status to ERROR and stop consuming incoming messages for partition on which error occurred.
You need to catch exceptions by yourself. Retries could be achieved either: 1) using Spring RetryTemplate to invoke external microservice (but keep in mind that you will have delays of consuming messages from a specific partition), or 2) push failed message into another topic for later reprocessing (as you suggested)

Update since kafka-streams 2.8.0

since kafka-streams 2.8.0, you have the ability to automatically replace failed stream thread (that caused by uncaught exception)
using KafkaStreams method void setUncaughtExceptionHandler(StreamsUncaughtExceptionHandler eh); with StreamThreadExceptionResponse.REPLACE_THREAD. For more details please take a look at Kafka Streams Specific Uncaught Exception Handler

kafkaStreams.setUncaughtExceptionHandler(ex -> {
    log.error("Kafka-Streams uncaught exception occurred. Stream will be replaced with new thread", ex);
    return StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.REPLACE_THREAD;
});


来源: stackexchange

问:
Sum of all odd fibonacci numbers upto n
I am stuck in summing up to number 10. Can't get it right.
What i am getting is the total sum from 10 digits (after filtering odd only 7). Where should i make <= num ?

function sumFibs(num) {
  var fib = [1, 1];
  for (var i = 2; i < num; i++) {
    var next = fib[i - 1] + fib[i - 2];
    var fibi = fib.push(next);
  }

  return fib.filter(function(a) {
      return (a % 2 != 0);
    })
    .reduce(function(a, z) {
      return a + z;
    })
}
console.log(sumFibs(10));```

Expected output 10, but getting 99

答:
If you want to retain your code for the most part, you can add an if statement that breaks the loop once your next number goes beyond your num:

function sumFibs(num) {
  var fib = [1, 1];
  for (var i = 2; i < num; i++) {
    var next = fib[i - 1] + fib[i - 2];

    if ( next > num ) { // not >= assuming you want to include your num
      break;
    }

    fib.push(next);
  }
  console.log({fib});

  return fib.filter(function(a) {
      return (a % 2 != 0);
    })
    .reduce(function(a, z) {
      return a + z;
    })
}
console.log(sumFibs(10));```

ContentLicense: CC BY-SA 4.0

Title: Sum of all odd fibonacci numbers upto n

Body:
I am stuck in summing up to number 10. Can't get it right.
What i am getting is the total sum from 10 digits (after filtering odd only 7). Where should i make <= num ?

function sumFibs(num) {
  var fib = [1, 1];
  for (var i = 2; i < num; i++) {
    var next = fib[i - 1] + fib[i - 2];
    var fibi = fib.push(next);
  }

  return fib.filter(function(a) {
      return (a % 2 != 0);
    })
    .reduce(function(a, z) {
      return a + z;
    })
}
console.log(sumFibs(10));

Expected output 10, but getting 99


问:
Is CLLocationManagerDelegate didFailError always callback error is CLError?
In swift, the method of CLLocationManagerDelegate didFailWithError error is always CLError? If yes, any reference?

Discussion: Invoked when an error has occurred. Error types are
  defined in "CLError.h".

Does it mean I can convert error to LAError anytime?

```<code>func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        guard let error = error as? CLError else {
            // Never?
            return
        }
    }
</code>```

And LAError...

答:
I found below legit reference for the error when CLLocationManager object is not able to retrieve the location. The Discussions part also have some examples also in the reference that which error will be received in different scenarios :

https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/1423786-locationmanager

Hope this helps you!!

Body:
In swift, the method of CLLocationManagerDelegate didFailWithError error is always CLError? If yes, any reference?

Discussion: Invoked when an error has occurred. Error types are
  defined in "CLError.h".

Does it mean I can convert error to LAError anytime?

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        guard let error = error as? CLError else {
            // Never?
            return
        }
    }

And LAError...


问:
Scraping a inner div's text
I'm new in python scraping. For a trial, I was scraping google page searched "cities in Ohio". I want to scrape the result i.e. the name of cities which are in boxes with the images (I just want text). Though there are many div so I'm confused that how to go for the div which is having the name of the city that is text. I just want to scrape the text written under Columbus. I want that Columbus. And other city's name is also in that div.

Can you please to learn this thing?

```<code>import bs4
import requests
import html.parser
import lxml,
res = requests.get('https://www.google.com/search?rlz=1C1CHBF_enIN818IN818&ei=KejsXJTSLdu0rQGk3aeQDw&q=cities+in+Ohio&oq=cities+in+Ohio&gs_l=psy-ab.3..0i71l8.826656.826656..826671...0.0..0.0.0.......0....2j1..gws-wiz.N2bmaS9Bitw')
soup = bs4.BeautifulSoup(res.text, 'lxml')
type(soup)
<class 'bs4.BeautifulSoup'>
soup.select('.wfg6Pb')[]
</code>```

The output is [] always.
Please use the link in code to get the result.

答:
to make this work for me I had to do 2 things:

add localization to the URL query params (hl=en&gl=en) otherwise I got the results in Hebrew (surfing from Israel...)

Identify the names themselves with a slightly more specific selector (otherwise I also got some unrelated information blocks)

all in all, my code looks like this:

import bs4
import requests
import html.parser
import lxml
res = requests.get('https://www.google.com/search?hl=en&gl=en&rlz=1C1CHBF_enIN818IN818&ei=KejsXJTSLdu0rQGk3aeQDw&q=cities+in+Ohio&oq=cities+in+Ohio&gs_l=psy-ab.3..0i71l8.826656.826656..826671...0.0..0.0.0.......0....2j1..gws-wiz.N2bmaS9Bitw')
soup = bs4.BeautifulSoup(res.content, 'lxml')
city_divs = soup.select('a.Mlb36b div.s3v9rd')
city_names = [c.text for c in city_divs]
```

<p>and output for <code>city_divs</code> is:</p>

<pre class="lang-html prettyprint-override"><code>[<div class="BNeawe s3v9rd AP7Wnd">Columbus</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Cleveland</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Cincinnati</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Dayton</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Toledo</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Akron</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Youngstown</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Findlay</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Kent</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Chillicothe</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Westerville</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Zanesville</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Wooster</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Elyria</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Hilliard</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Grove City</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Lorain</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Massillon</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Perrysburg</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Strongsville</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Cuyahoga Falls</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Maumee</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Reynoldsburg</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Stow</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Port Clinton</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Pickerington</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Steubenville</div>,
 <div class="BNeawe s3v9rd AP7Wnd">North Canton</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Gahanna</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Ashtabula</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Beachwood</div>,
 <div class="BNeawe s3v9rd AP7Wnd">New Philadelphia</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Miamisburg</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Wadsworth</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Bellefontaine</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Painesville</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Put‑in‑Bay</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Worthington</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Twinsburg</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Chagrin Falls</div>,
 <div class="BNeawe s3v9rd AP7Wnd">North Olmsted</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Barberton</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Canal Winchester</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Wright‑Patterson Air Force...</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Yellow Springs</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Shaker Heights</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Oberlin</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Upper Arlington</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Blue Ash</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Rocky River</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Pataskala</div>]
</code>```

and for city_names is:

['Columbus',
 'Cleveland',
 'Cincinnati',
 'Dayton',
 'Toledo',
 'Akron',
 'Youngstown',
 'Findlay',
 'Kent',
 'Chillicothe',
 'Westerville',
 'Zanesville',
 'Wooster',
 'Elyria',
 'Hilliard',
 'Grove City',
 'Lorain',
 'Massillon',
 'Perrysburg',
 'Strongsville',
 'Cuyahoga Falls',
 'Maumee',
 'Reynoldsburg',
 'Stow',
 'Port Clinton',
 'Pickerington',
 'Steubenville',
 'North Canton',
 'Gahanna',
 'Ashtabula',
 'Beachwood',
 'New Philadelphia',
 'Miamisburg',
 'Wadsworth',
 'Bellefontaine',
 'Painesville',
 'Put‑in‑Bay',
 'Worthington',
 'Twinsburg',
 'Chagrin Falls',
 'North Olmsted',
 'Barberton',
 'Canal Winchester',
 'Wright‑Patterson Air Force...',
 'Yellow Springs',
 'Shaker Heights',
 'Oberlin',
 'Upper Arlington',
 'Blue Ash',
 'Rocky River',
 'Pataskala']
```

Title: Scraping a inner div's text

Body:
I'm new in python scraping. For a trial, I was scraping google page searched "cities in Ohio". I want to scrape the result i.e. the name of cities which are in boxes with the images (I just want text). Though there are many div so I'm confused that how to go for the div which is having the name of the city that is text. I just want to scrape the text written under Columbus. I want that Columbus. And other city's name is also in that div.

Can you please to learn this thing?

import bs4
import requests
import html.parser
import lxml,
res = requests.get('https://www.google.com/search?rlz=1C1CHBF_enIN818IN818&ei=KejsXJTSLdu0rQGk3aeQDw&q=cities+in+Ohio&oq=cities+in+Ohio&gs_l=psy-ab.3..0i71l8.826656.826656..826671...0.0..0.0.0.......0....2j1..gws-wiz.N2bmaS9Bitw')
soup = bs4.BeautifulSoup(res.text, 'lxml')
type(soup)
<class 'bs4.BeautifulSoup'>
soup.select('.wfg6Pb')[]

The output is [] always.
Please use the link in code to get the result.

Body:
to make this work for me I had to do 2 things:

add localization to the URL query params (hl=en&gl=en) otherwise I got the results in Hebrew (surfing from Israel...)

Identify the names themselves with a slightly more specific selector (otherwise I also got some unrelated information blocks)

all in all, my code looks like this:

import bs4
import requests
import html.parser
import lxml
res = requests.get('https://www.google.com/search?hl=en&gl=en&rlz=1C1CHBF_enIN818IN818&ei=KejsXJTSLdu0rQGk3aeQDw&q=cities+in+Ohio&oq=cities+in+Ohio&gs_l=psy-ab.3..0i71l8.826656.826656..826671...0.0..0.0.0.......0....2j1..gws-wiz.N2bmaS9Bitw')
soup = bs4.BeautifulSoup(res.content, 'lxml')
city_divs = soup.select('a.Mlb36b div.s3v9rd')
city_names = [c.text for c in city_divs]

and output for city_divs is:

[<div class="BNeawe s3v9rd AP7Wnd">Columbus</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Cleveland</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Cincinnati</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Dayton</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Toledo</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Akron</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Youngstown</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Findlay</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Kent</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Chillicothe</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Westerville</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Zanesville</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Wooster</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Elyria</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Hilliard</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Grove City</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Lorain</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Massillon</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Perrysburg</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Strongsville</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Cuyahoga Falls</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Maumee</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Reynoldsburg</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Stow</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Port Clinton</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Pickerington</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Steubenville</div>,
 <div class="BNeawe s3v9rd AP7Wnd">North Canton</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Gahanna</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Ashtabula</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Beachwood</div>,
 <div class="BNeawe s3v9rd AP7Wnd">New Philadelphia</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Miamisburg</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Wadsworth</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Bellefontaine</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Painesville</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Put‑in‑Bay</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Worthington</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Twinsburg</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Chagrin Falls</div>,
 <div class="BNeawe s3v9rd AP7Wnd">North Olmsted</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Barberton</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Canal Winchester</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Wright‑Patterson Air Force...</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Yellow Springs</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Shaker Heights</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Oberlin</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Upper Arlington</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Blue Ash</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Rocky River</div>,
 <div class="BNeawe s3v9rd AP7Wnd">Pataskala</div>]

and for city_names is:

['Columbus',
 'Cleveland',
 'Cincinnati',
 'Dayton',
 'Toledo',
 'Akron',
 'Youngstown',
 'Findlay',
 'Kent',
 'Chillicothe',
 'Westerville',
 'Zanesville',
 'Wooster',
 'Elyria',
 'Hilliard',
 'Grove City',
 'Lorain',
 'Massillon',
 'Perrysburg',
 'Strongsville',
 'Cuyahoga Falls',
 'Maumee',
 'Reynoldsburg',
 'Stow',
 'Port Clinton',
 'Pickerington',
 'Steubenville',
 'North Canton',
 'Gahanna',
 'Ashtabula',
 'Beachwood',
 'New Philadelphia',
 'Miamisburg',
 'Wadsworth',
 'Bellefontaine',
 'Painesville',
 'Put‑in‑Bay',
 'Worthington',
 'Twinsburg',
 'Chagrin Falls',
 'North Olmsted',
 'Barberton',
 'Canal Winchester',
 'Wright‑Patterson Air Force...',
 'Yellow Springs',
 'Shaker Heights',
 'Oberlin',
 'Upper Arlington',
 'Blue Ash',
 'Rocky River',
 'Pataskala']


问:
How to remove " " from text using regex-Python 3
So, I have a text string that I want to remove the "" from.

Here is my text string:

```<code>string= 'Sample this is a string text with "ut" '
</code>```

Here is the output I want once using a regex expression:

```<code>string= 'Sample this is a string text with ut'
</code>```

Here is my overall code:

```<code>import re
string= 'Sample this is a string text with "ut" '
re.sub('" "', '', string)
</code>```

And the output just show the exact text in the string without any changes. Any suggestions?

答:
If you want just remove all " symbols, you can use str.replace instead:

string = string.replace('"', '')

Body:
So, I have a text string that I want to remove the "" from.

Here is my text string:

string= 'Sample this is a string text with "ut" '

Here is the output I want once using a regex expression:

string= 'Sample this is a string text with ut'

Here is my overall code:

import re
string= 'Sample this is a string text with "ut" '
re.sub('" "', '', string)

And the output just show the exact text in the string without any changes. Any suggestions?


答: You can simply use string.replace('"','')

Title: How to remove " " from text using regex-Python 3


问:
Calculated timedelta column in pandas
I have some data in a pandas df like:

```<code>time                            delay
2017/06/14 10:02:10.144927 PM   15
</code>```

The time is obviously a timestamp and in the delay is in seconds. df.dtypes are datetime64[ns] and int respectively. I want to add a column that has the timestamp of the original time plus the seconds passed, e.g.:

```<code>time                            delay   end_time
2017/06/14 10:02:10.144927 PM   15      2017/06/14 10:02:25.144927 PM
</code>```

I'm trying to do

```<code>df["end_time"] = df.time.add(datetime.timedelta(seconds = df.time))
</code>```

However I get an error TypeError: unsupported type for timedelta seconds component: Series. How would I do this? Do I need a lambda?

答:
Use to_timedelta for convert integer column to timedeltas:

```<code>df["end_time"] = pd.to_datetime(df['time']).add(pd.to_timedelta(df.delay, unit='s'))
print (df)
                            time  delay                   end_time
0  2017/06/14 10:02:10.144927 PM     15 2017-06-14 22:02:25.144927
</code>```

If need same format in output add Series.dt.strftime:

```<code>df["end_time"] = (pd.to_datetime(df['time'])
                   .add(pd.to_timedelta(df.delay, unit='s'))
                   .dt.strftime('%Y/%m/%d %H:%M:%S.%f %p'))
print (df)
                            time  delay                       end_time
0  2017/06/14 10:02:10.144927 PM     15  2017/06/14 22:02:25.144927 PM
</code>```

Title: Calculated timedelta column in pandas

Body:
I have some data in a pandas df like:

time                            delay
2017/06/14 10:02:10.144927 PM   15

The time is obviously a timestamp and in the delay is in seconds. df.dtypes are datetime64[ns] and int respectively. I want to add a column that has the timestamp of the original time plus the seconds passed, e.g.:

time                            delay   end_time
2017/06/14 10:02:10.144927 PM   15      2017/06/14 10:02:25.144927 PM

I'm trying to do

df["end_time"] = df.time.add(datetime.timedelta(seconds = df.time))

However I get an error TypeError: unsupported type for timedelta seconds component: Series. How would I do this? Do I need a lambda?

Body:
Use to_timedelta for convert integer column to timedeltas:

df["end_time"] = pd.to_datetime(df['time']).add(pd.to_timedelta(df.delay, unit='s'))
print (df)
                            time  delay                   end_time
0  2017/06/14 10:02:10.144927 PM     15 2017-06-14 22:02:25.144927

If need same format in output add Series.dt.strftime:

df["end_time"] = (pd.to_datetime(df['time'])
                   .add(pd.to_timedelta(df.delay, unit='s'))
                   .dt.strftime('%Y/%m/%d %H:%M:%S.%f %p'))
print (df)
                            time  delay                       end_time
0  2017/06/14 10:02:10.144927 PM     15  2017/06/14 22:02:25.144927 PM


问:
Reactotron core client causing Jenkins build fail?
I do not have a lot of experience with Jenkins, could someone assist me in what to look for inside this error message regarding what failed about this build?

```<code>08:47:43 Started by upstream project "Build/Build Mac Component" build number 3703
08:47:43 originally caused by:
08:47:43  Started by upstream project "Build/Build Component" build number 8094
08:47:43  originally caused by:
08:47:43   Started by upstream project "ENGA/ENGAL" build number 1831
08:47:43   originally caused by:
08:47:43    Started by remote host 172.16.6.8
08:47:43 Running as buildbot, svc
08:47:43 Setting version to: ENGAL 3.6.2-bug.1+127 from upstream version
08:47:43 [EnvInject] - Loading node environment variables.
08:47:43 Building remotely on Michelle (mac) in workspace /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL
08:47:43 Running Prebuild steps
08:47:43 [EnvInject] - Injecting environment variables from a build step.
08:47:43 [EnvInject] - Injecting as environment variables the properties file path '/Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/gitversion.properties'
08:47:43 [EnvInject] - Variables injected successfully.
08:47:43 Success build fororg.jenkinsci.plugins.envinject.EnvInjectBuilder@5f11578e
08:47:43 [EnvInject] - Executing scripts and injecting environment variables after the SCM step.
08:47:44 [EnvInject] - Injecting as environment variables the properties content
08:47:44 JUNIT_REPORT_PATH=testResults/
08:47:44 CI=true
08:47:44
08:47:44 [EnvInject] - Variables injected successfully.
08:47:44 Set build name.
08:47:44 New build name is 'JS! ENGAL 3.6.2-bug.1+127'
08:47:44 [description-setter] Description set: #3155: JS! Engage Application - Mobile
08:47:44 Recording fingerprints
08:47:44 [ENGAL] $ /bin/sh -xe /var/folders/8m/t1fsdc0d1szd7b4tsxt9b0z40000gn/T/jenkins4398796249639990897.sh
08:47:44 + npm install
08:48:10
08:48:10 > NFIBEngage@3.6.2-ci.1 postinstall /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL
08:48:10 > rm -f ./node_modules/react-native/local-cli/core/__fixtures__/files/package.json
08:48:10
08:48:12 npm WARN reactotron-redux@3.1.0 requires a peer of reactotron-core-client@^2.5.0 but none is installed. You must install peer dependencies yourself.
08:48:12 npm WARN reactotron-redux@3.1.0 requires a peer of redux@^4.0.1 but none is installed. You must install peer dependencies yourself.
08:48:12
08:48:12 moved 2 packages in 26.06s
08:48:12 + npm version --allow-same-version 3.6.2-bug.1 --git-tag-version false
08:48:12 v3.6.2-bug.1
08:48:12 + npm run build
08:48:13
08:48:13 > NFIBEngage@3.6.2-bug.1 build /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL
08:48:13 > nps build
08:48:13
08:48:13 nps is executing `build` : nps android.build && nps ios.build && nps finish
08:48:14 nps is executing `android.build` : node node_modules/rimraf/bin.js dist/*.apk && babel-node scripts/android/build.js
08:48:16 ########################### Starting Android Builds ###########################
08:48:16 starting gradle assembleDevRelease with flag - versionName=3.6.2-1831 -PversionCode=1831
08:49:19 ############################ Android Builds Failed! ############################
08:49:19 { Error: Command failed: ENGAGE_ENDPOINT=dv APPCENTER_KEY=f743d50f-82fa-4b23-b602-2a318b875480 ENGAGE_VERSION=3.6.2-1831 APPCENTER_PLATFORM=android npm run setup && cd android && ./gradlew assembleDevRelease -PversionName=3.6.2-1831 -PversionCode=1831 && cd ..
08:49:19
08:49:19 Unable to resolve module `reactotron-core-client` from `/Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/node_modules/reactotron-redux/dist/index.js`: Module does not exist in the module map
08:49:19
08:49:19 This might be related to https://github.com/facebook/react-native/issues/4968
08:49:19 To resolve try the following:
08:49:19   1. Clear watchman watches: `watchman watch-del-all`.
08:49:19   2. Delete the `node_modules` folder: `rm -rf node_modules && npm install`.
08:49:19   3. Reset Metro Bundler cache: `rm -rf $TMPDIR/react-*` or `npm start -- --reset-cache`.  4. Remove haste cache: `rm -rf $TMPDIR/haste-map-react-native-packager-*`.
08:49:19
08:49:19
08:49:19 FAILURE: Build failed with an exception.
08:49:19
08:49:19 * What went wrong:
08:49:19 Execution failed for task ':app:bundleDevReleaseJsAndAssets'.
08:49:19 > Process 'command 'node'' finished with non-zero exit value 1
08:49:19
08:49:19 * Try:
08:49:19 Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
08:49:19
08:49:19 * Get more help at https://help.gradle.org
08:49:19
08:49:19 BUILD FAILED in 52s
08:49:19
08:49:19     at ChildProcess.exithandler (child_process.js:206:12)
08:49:19     at emitTwo (events.js:106:13)
08:49:19     at ChildProcess.emit (events.js:191:7)
08:49:19     at maybeClose (internal/child_process.js:877:16)
08:49:19     at Socket.<anonymous> (internal/child_process.js:334:11)
08:49:19     at emitOne (events.js:96:13)
08:49:19     at Socket.emit (events.js:188:7)
08:49:19     at Pipe._handle.close [as _onclose] (net.js:498:12)
08:49:19   killed: false,
08:49:19   code: 1,
08:49:19   signal: null,
08:49:19   cmd: 'ENGAGE_ENDPOINT=dv APPCENTER_KEY=f743d50f-82fa-4b23-b602-2a318b875480 ENGAGE_VERSION=3.6.2-1831 APPCENTER_PLATFORM=android npm run setup && cd android && ./gradlew assembleDevRelease -PversionName=3.6.2-1831 -PversionCode=1831 && cd ..' }
08:49:19 ============================= Copying APK to Dist =============================
08:49:20 nps is executing `ios.build` : node node_modules/rimraf/bin.js dist/*.ipa && babel-node scripts/ios/build.js
08:49:23 ############################# DEV Build IOS Start #############################
08:49:23 ENGAGE_ENDPOINT=dv APPCENTER_KEY=e53bdbfb-dbdd-4ab9-8b4c-9d391e602cfa ENGAGE_VERSION=3.6.2-1831 APPCENTER_PLATFORM=ios npm run setup && xcodebuild -workspace ios/NFIBEngage.xcworkspace -configuration Release -scheme DEV -derivedDataPath /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/ios/build -archivePath /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/ios/build/Archive/DEV.xcarchive archive -UseModernBuildSystem=NO && xcodebuild -archivePath /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/ios/build/Archive/DEV.xcarchive -exportPath /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/dist -exportOptionsPlist /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/scripts/ios/dev.plist -exportArchive
08:54:39 ** ARCHIVE FAILED **
08:54:39
08:54:39
08:54:39 The following build commands failed:
08:54:39    PhaseScriptExecution Bundle\ React\ Native\ code\ and\ images build/Build/Intermediates.noindex/ArchiveIntermediates/DEV/IntermediateBuildFilesPath/NFIBEngage.build/Release-iphoneos/DEV.build/Script-6BE83F58202A54D500662052.sh
08:54:39 (1 failure)
08:54:39 child_process.js:526
08:54:39     throw err;
08:54:39     ^
08:54:39
08:54:39 Error: Command failed: ENGAGE_ENDPOINT=dv APPCENTER_KEY=e53bdbfb-dbdd-4ab9-8b4c-9d391e602cfa ENGAGE_VERSION=3.6.2-1831 APPCENTER_PLATFORM=ios npm run setup && xcodebuild -workspace ios/NFIBEngage.xcworkspace -configuration Release -scheme DEV -derivedDataPath /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/ios/build -archivePath /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/ios/build/Archive/DEV.xcarchive archive -UseModernBuildSystem=NO && xcodebuild -archivePath /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/ios/build/Archive/DEV.xcarchive -exportPath /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/dist -exportOptionsPlist /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/scripts/ios/dev.plist -exportArchive
08:54:39 ** ARCHIVE FAILED **
08:54:39
08:54:39
08:54:39 The following build commands failed:
08:54:39    PhaseScriptExecution Bundle\ React\ Native\ code\ and\ images build/Build/Intermediates.noindex/ArchiveIntermediates/DEV/IntermediateBuildFilesPath/NFIBEngage.build/Release-iphoneos/DEV.build/Script-6BE83F58202A54D500662052.sh
08:54:39 (1 failure)
08:54:39
08:54:39     at checkExecSyncError (child_process.js:483:13)
08:54:39     at execSync (child_process.js:523:13)
08:54:39     at /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/scripts/ios/build.js:155:5
08:54:39     at Array.forEach (native)
08:54:39     at run (/Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/scripts/ios/build.js:117:16)
08:54:39     at Object.<anonymous> (/Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/scripts/ios/build.js:166:1)
08:54:39     at Module._compile (module.js:570:32)
08:54:39     at loader (/Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/node_modules/babel-register/lib/node.js:144:5)
08:54:39     at Object.require.extensions.(anonymous function) [as .js] (/Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/node_modules/babel-register/lib/node.js:154:7)
08:54:39     at Module.load (module.js:487:32)
08:54:39 The script called "ios.build" which runs "node node_modules/rimraf/bin.js dist/*.ipa && babel-node scripts/ios/build.js" failed with exit code 1 https://github.com/kentcdodds/nps/blob/v5.7.1/other/ERRORS_AND_WARNINGS.md#failed-with-exit-code
08:54:39 The script called "build" which runs "nps android.build && nps ios.build && nps finish" failed with exit code 1 https://github.com/kentcdodds/nps/blob/v5.7.1/other/ERRORS_AND_WARNINGS.md#failed-with-exit-code
08:54:39 npm ERR! code ELIFECYCLE
08:54:39 npm ERR! errno 1
08:54:39 npm ERR! NFIBEngage@3.6.2-bug.1 build: `nps build`
08:54:39 npm ERR! Exit status 1
08:54:39 npm ERR!
08:54:39 npm ERR! Failed at the NFIBEngage@3.6.2-bug.1 build script.
08:54:39 npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
08:54:39
08:54:39 npm ERR! A complete log of this run can be found in:
08:54:39 npm ERR!     /Users/nfib/.npm/_logs/2019-05-24T13_54_39_789Z-debug.log
08:54:39 Build step 'Execute shell' marked build as failure
08:54:39 Set build name.
08:54:39 New build name is 'JS! ENGAL 3.6.2-bug.1+127'
08:54:39 Variable with name 'BUILD_DISPLAY_NAME' already exists, current value: 'JS! ENGAL 3.6.2-bug.1+127', new value: 'JS! ENGAL 3.6.2-bug.1+127'
08:54:45 Archiving artifacts
08:54:48 Finished: FAILURE
</code>```

It seems Jenkins is having a problem locating the reactotron-core-client

答:
This is the line you're looking for.

```<code>Unable to resolve module `reactotron-core-client` from `/Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/node_modules/reactotron-redux/dist/index.js`: Module does not exist in the module map
</code>```

Looks like it's probably a dependency issue.  It also tells you it happens during this step:

```<code>Execution failed for task ':app:bundleDevReleaseJsAndAssets'.
</code>```

If you need to see exactly what the workspace looks like and you're running pipeline builds, you can use the following line right before the step that fails:

```<code>archiveArtifacts '**\\*.*'
</code>```

If you're not using pipeline builds, you can find the step as "Archive the Artifacts" in the Post Build Actions.

Body:
I do not have a lot of experience with Jenkins, could someone assist me in what to look for inside this error message regarding what failed about this build?

08:47:43 Started by upstream project "Build/Build Mac Component" build number 3703
08:47:43 originally caused by:
08:47:43  Started by upstream project "Build/Build Component" build number 8094
08:47:43  originally caused by:
08:47:43   Started by upstream project "ENGA/ENGAL" build number 1831
08:47:43   originally caused by:
08:47:43    Started by remote host 172.16.6.8
08:47:43 Running as buildbot, svc
08:47:43 Setting version to: ENGAL 3.6.2-bug.1+127 from upstream version
08:47:43 [EnvInject] - Loading node environment variables.
08:47:43 Building remotely on Michelle (mac) in workspace /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL
08:47:43 Running Prebuild steps
08:47:43 [EnvInject] - Injecting environment variables from a build step.
08:47:43 [EnvInject] - Injecting as environment variables the properties file path '/Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/gitversion.properties'
08:47:43 [EnvInject] - Variables injected successfully.
08:47:43 Success build fororg.jenkinsci.plugins.envinject.EnvInjectBuilder@5f11578e
08:47:43 [EnvInject] - Executing scripts and injecting environment variables after the SCM step.
08:47:44 [EnvInject] - Injecting as environment variables the properties content
08:47:44 JUNIT_REPORT_PATH=testResults/
08:47:44 CI=true
08:47:44
08:47:44 [EnvInject] - Variables injected successfully.
08:47:44 Set build name.
08:47:44 New build name is 'JS! ENGAL 3.6.2-bug.1+127'
08:47:44 [description-setter] Description set: #3155: JS! Engage Application - Mobile
08:47:44 Recording fingerprints
08:47:44 [ENGAL] $ /bin/sh -xe /var/folders/8m/t1fsdc0d1szd7b4tsxt9b0z40000gn/T/jenkins4398796249639990897.sh
08:47:44 + npm install
08:48:10
08:48:10 > NFIBEngage@3.6.2-ci.1 postinstall /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL
08:48:10 > rm -f ./node_modules/react-native/local-cli/core/__fixtures__/files/package.json
08:48:10
08:48:12 npm WARN reactotron-redux@3.1.0 requires a peer of reactotron-core-client@^2.5.0 but none is installed. You must install peer dependencies yourself.
08:48:12 npm WARN reactotron-redux@3.1.0 requires a peer of redux@^4.0.1 but none is installed. You must install peer dependencies yourself.
08:48:12
08:48:12 moved 2 packages in 26.06s
08:48:12 + npm version --allow-same-version 3.6.2-bug.1 --git-tag-version false
08:48:12 v3.6.2-bug.1
08:48:12 + npm run build
08:48:13
08:48:13 > NFIBEngage@3.6.2-bug.1 build /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL
08:48:13 > nps build
08:48:13
08:48:13 nps is executing `build` : nps android.build && nps ios.build && nps finish
08:48:14 nps is executing `android.build` : node node_modules/rimraf/bin.js dist/*.apk && babel-node scripts/android/build.js
08:48:16 ########################### Starting Android Builds ###########################
08:48:16 starting gradle assembleDevRelease with flag - versionName=3.6.2-1831 -PversionCode=1831
08:49:19 ############################ Android Builds Failed! ############################
08:49:19 { Error: Command failed: ENGAGE_ENDPOINT=dv APPCENTER_KEY=f743d50f-82fa-4b23-b602-2a318b875480 ENGAGE_VERSION=3.6.2-1831 APPCENTER_PLATFORM=android npm run setup && cd android && ./gradlew assembleDevRelease -PversionName=3.6.2-1831 -PversionCode=1831 && cd ..
08:49:19
08:49:19 Unable to resolve module `reactotron-core-client` from `/Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/node_modules/reactotron-redux/dist/index.js`: Module does not exist in the module map
08:49:19
08:49:19 This might be related to https://github.com/facebook/react-native/issues/4968
08:49:19 To resolve try the following:
08:49:19   1. Clear watchman watches: `watchman watch-del-all`.
08:49:19   2. Delete the `node_modules` folder: `rm -rf node_modules && npm install`.
08:49:19   3. Reset Metro Bundler cache: `rm -rf $TMPDIR/react-*` or `npm start -- --reset-cache`.  4. Remove haste cache: `rm -rf $TMPDIR/haste-map-react-native-packager-*`.
08:49:19
08:49:19
08:49:19 FAILURE: Build failed with an exception.
08:49:19
08:49:19 * What went wrong:
08:49:19 Execution failed for task ':app:bundleDevReleaseJsAndAssets'.
08:49:19 > Process 'command 'node'' finished with non-zero exit value 1
08:49:19
08:49:19 * Try:
08:49:19 Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
08:49:19
08:49:19 * Get more help at https://help.gradle.org
08:49:19
08:49:19 BUILD FAILED in 52s
08:49:19
08:49:19     at ChildProcess.exithandler (child_process.js:206:12)
08:49:19     at emitTwo (events.js:106:13)
08:49:19     at ChildProcess.emit (events.js:191:7)
08:49:19     at maybeClose (internal/child_process.js:877:16)
08:49:19     at Socket.<anonymous> (internal/child_process.js:334:11)
08:49:19     at emitOne (events.js:96:13)
08:49:19     at Socket.emit (events.js:188:7)
08:49:19     at Pipe._handle.close [as _onclose] (net.js:498:12)
08:49:19   killed: false,
08:49:19   code: 1,
08:49:19   signal: null,
08:49:19   cmd: 'ENGAGE_ENDPOINT=dv APPCENTER_KEY=f743d50f-82fa-4b23-b602-2a318b875480 ENGAGE_VERSION=3.6.2-1831 APPCENTER_PLATFORM=android npm run setup && cd android && ./gradlew assembleDevRelease -PversionName=3.6.2-1831 -PversionCode=1831 && cd ..' }
08:49:19 ============================= Copying APK to Dist =============================
08:49:20 nps is executing `ios.build` : node node_modules/rimraf/bin.js dist/*.ipa && babel-node scripts/ios/build.js
08:49:23 ############################# DEV Build IOS Start #############################
08:49:23 ENGAGE_ENDPOINT=dv APPCENTER_KEY=e53bdbfb-dbdd-4ab9-8b4c-9d391e602cfa ENGAGE_VERSION=3.6.2-1831 APPCENTER_PLATFORM=ios npm run setup && xcodebuild -workspace ios/NFIBEngage.xcworkspace -configuration Release -scheme DEV -derivedDataPath /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/ios/build -archivePath /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/ios/build/Archive/DEV.xcarchive archive -UseModernBuildSystem=NO && xcodebuild -archivePath /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/ios/build/Archive/DEV.xcarchive -exportPath /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/dist -exportOptionsPlist /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/scripts/ios/dev.plist -exportArchive
08:54:39 ** ARCHIVE FAILED **
08:54:39
08:54:39
08:54:39 The following build commands failed:
08:54:39    PhaseScriptExecution Bundle\ React\ Native\ code\ and\ images build/Build/Intermediates.noindex/ArchiveIntermediates/DEV/IntermediateBuildFilesPath/NFIBEngage.build/Release-iphoneos/DEV.build/Script-6BE83F58202A54D500662052.sh
08:54:39 (1 failure)
08:54:39 child_process.js:526
08:54:39     throw err;
08:54:39     ^
08:54:39
08:54:39 Error: Command failed: ENGAGE_ENDPOINT=dv APPCENTER_KEY=e53bdbfb-dbdd-4ab9-8b4c-9d391e602cfa ENGAGE_VERSION=3.6.2-1831 APPCENTER_PLATFORM=ios npm run setup && xcodebuild -workspace ios/NFIBEngage.xcworkspace -configuration Release -scheme DEV -derivedDataPath /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/ios/build -archivePath /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/ios/build/Archive/DEV.xcarchive archive -UseModernBuildSystem=NO && xcodebuild -archivePath /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/ios/build/Archive/DEV.xcarchive -exportPath /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/dist -exportOptionsPlist /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/scripts/ios/dev.plist -exportArchive
08:54:39 ** ARCHIVE FAILED **
08:54:39
08:54:39
08:54:39 The following build commands failed:
08:54:39    PhaseScriptExecution Bundle\ React\ Native\ code\ and\ images build/Build/Intermediates.noindex/ArchiveIntermediates/DEV/IntermediateBuildFilesPath/NFIBEngage.build/Release-iphoneos/DEV.build/Script-6BE83F58202A54D500662052.sh
08:54:39 (1 failure)
08:54:39
08:54:39     at checkExecSyncError (child_process.js:483:13)
08:54:39     at execSync (child_process.js:523:13)
08:54:39     at /Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/scripts/ios/build.js:155:5
08:54:39     at Array.forEach (native)
08:54:39     at run (/Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/scripts/ios/build.js:117:16)
08:54:39     at Object.<anonymous> (/Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/scripts/ios/build.js:166:1)
08:54:39     at Module._compile (module.js:570:32)
08:54:39     at loader (/Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/node_modules/babel-register/lib/node.js:144:5)
08:54:39     at Object.require.extensions.(anonymous function) [as .js] (/Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/node_modules/babel-register/lib/node.js:154:7)
08:54:39     at Module.load (module.js:487:32)
08:54:39 The script called "ios.build" which runs "node node_modules/rimraf/bin.js dist/*.ipa && babel-node scripts/ios/build.js" failed with exit code 1 https://github.com/kentcdodds/nps/blob/v5.7.1/other/ERRORS_AND_WARNINGS.md#failed-with-exit-code
08:54:39 The script called "build" which runs "nps android.build && nps ios.build && nps finish" failed with exit code 1 https://github.com/kentcdodds/nps/blob/v5.7.1/other/ERRORS_AND_WARNINGS.md#failed-with-exit-code
08:54:39 npm ERR! code ELIFECYCLE
08:54:39 npm ERR! errno 1
08:54:39 npm ERR! NFIBEngage@3.6.2-bug.1 build: `nps build`
08:54:39 npm ERR! Exit status 1
08:54:39 npm ERR!
08:54:39 npm ERR! Failed at the NFIBEngage@3.6.2-bug.1 build script.
08:54:39 npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
08:54:39
08:54:39 npm ERR! A complete log of this run can be found in:
08:54:39 npm ERR!     /Users/nfib/.npm/_logs/2019-05-24T13_54_39_789Z-debug.log
08:54:39 Build step 'Execute shell' marked build as failure
08:54:39 Set build name.
08:54:39 New build name is 'JS! ENGAL 3.6.2-bug.1+127'
08:54:39 Variable with name 'BUILD_DISPLAY_NAME' already exists, current value: 'JS! ENGAL 3.6.2-bug.1+127', new value: 'JS! ENGAL 3.6.2-bug.1+127'
08:54:45 Archiving artifacts
08:54:48 Finished: FAILURE

It seems Jenkins is having a problem locating the reactotron-core-client

Body:
This is the line you're looking for.

Unable to resolve module `reactotron-core-client` from `/Users/nfib/Jenkins/Jenkins-Workspaces/ENGA/ENGAL/node_modules/reactotron-redux/dist/index.js`: Module does not exist in the module map

Looks like it's probably a dependency issue.  It also tells you it happens during this step:

Execution failed for task ':app:bundleDevReleaseJsAndAssets'.

If you need to see exactly what the workspace looks like and you're running pipeline builds, you can use the following line right before the step that fails:

archiveArtifacts '**\\*.*'

If you're not using pipeline builds, you can find the step as "Archive the Artifacts" in the Post Build Actions.


问:
Is there a better way to write my item/weapon unlock system?
I'm really struggling with creating a weapon/item unlock system via an in-game shop. The player should only be able to select weapons at indexes that have been unlocked or bought.

I've wasted two days on the best way to achieve this and I'm still not anywhere near a solution.

Currently this is what I have:

I have a WeaponUnlock script that handles a dictionary of weapons and another WeaponSwitcher script that access vales from that script to check if it is unlocked or not.

```<code>public class WeaponUnlockSystem : MonoBehaviour
{

    private Dictionary<string, bool> weaponUnlockState;

    void Start()
    {
        // Seeding with some data for example purposes
        weaponUnlockState = new Dictionary<string, bool>();
        weaponUnlockState.Add("Shotgun", true);
        weaponUnlockState.Add("Rifle", true);
        weaponUnlockState.Add("FireballGun", false);
        weaponUnlockState.Add("LaserGun", false);
        weaponUnlockState.Add("FlamethrowerGun", false);
        weaponUnlockState.Add("SuperGun", false);
    }

    public bool IsWeaponUnlocked(string weapon_)
    {
        if (weaponUnlockState.ContainsKey(weapon_))
            return weaponUnlockState[weapon_];              // this will return either true or false if the weapon is unlocked or not
        else
            return false;
    }

    public void UnlockWeapon(string weapon_)            //this will be called by the button..
    {
        if (weaponUnlockState.ContainsKey(weapon_))
            weaponUnlockState[weapon_] = true;
    }
}
</code>```

The WeaponSwitchergets the name of the weapon from the nested children every time the nextWeapon button is pressed:

```<code>weaponName = this.gameObject.transform.GetChild(weaponIdx).name.ToString();     //get the name of the child at current index

        if (weaponUnlock.IsWeaponUnlocked(weaponName))      //ask weaponUnlockSystem if this name weapon is unlocked or not, only enable the transform if true is returned
            selectedWeapon = weaponIdx;
</code>```

This...... works..... but I know is not practical. As the script sits on a game object and at every time it is called the Start() is called that will reset all the unlocked values. Also will I have to make it persistent via DontDestroyOnLOad() through scenes?

I can get use PlayerPrefs and set a value for every weapon, but that is also not ideal and also to avoid it being reset every time someone opens my game I would have to perform a checks of PlayerPrefs.HasKey() for every weapon. Also not practical.

There must be a better way of doing this. Its funny that I cannot find much help online for this and dont know how everyone is getting around this.

Thanks

答:
You create a class that is not a GameObject, just a normal class. There you can initialize the dictionary and have methods to unlock or check if a weapon is unlocked.

As I don't know what your architecture of the rest of the code looks like, I will go ahead and assume that you have some kind of a persistent player model.

You could just add the WeaponUnlockSystem to your player GameObject and manage the unlocks from there.
To me this would make the most sense as the player is probably the one unlocking the weapons so the WeaponUnlockSystem should be attached to him.

Here is a really basic code example:

```<code>public class WeaponUnlockSystem {

    private Dictionary<string, bool> weaponUnlockState;

    public WeaponUnlockSystem()
    {
        weaponUnlockState = new Dictionary<string, bool>();
        weaponUnlockState.Add("Shotgun", true);
        weaponUnlockState.Add("Rifle", true);
        weaponUnlockState.Add("FireballGun", false);
        weaponUnlockState.Add("LaserGun", false);
        weaponUnlockState.Add("FlamethrowerGun", false);
        weaponUnlockState.Add("SuperGun", false);
    }

    public bool IsWeaponUnlocked(string weapon)
    {
        if (weaponUnlockState.ContainsKey(weapon))
            return weaponUnlockState[weapon];
        else
            return false;
    }

    public void UnlockWeapon(string weapon)
    {
        if (weaponUnlockState.ContainsKey(weapon))
            weaponUnlockState[weapon] = true;
    }
}

public class Player : MonoBehaviour {

    private WeaponUnlockSystem weaponUnlockSystem;

    void Start()
    {
        weaponUnlockSystem = new WeaponUnlockSystem();
        ...
    }

    public void NextWeapon(string weapon)
    {
        ...
    }
}
</code>```

I would also advice against using a static class for convenience here. Static should only be used, if you don't want to change the state of an object or don't need to create an instance of an object.

Body:
I'm really struggling with creating a weapon/item unlock system via an in-game shop. The player should only be able to select weapons at indexes that have been unlocked or bought.

I've wasted two days on the best way to achieve this and I'm still not anywhere near a solution.

Currently this is what I have:

I have a WeaponUnlock script that handles a dictionary of weapons and another WeaponSwitcher script that access vales from that script to check if it is unlocked or not.

public class WeaponUnlockSystem : MonoBehaviour
{

    private Dictionary<string, bool> weaponUnlockState;

    void Start()
    {
        // Seeding with some data for example purposes
        weaponUnlockState = new Dictionary<string, bool>();
        weaponUnlockState.Add("Shotgun", true);
        weaponUnlockState.Add("Rifle", true);
        weaponUnlockState.Add("FireballGun", false);
        weaponUnlockState.Add("LaserGun", false);
        weaponUnlockState.Add("FlamethrowerGun", false);
        weaponUnlockState.Add("SuperGun", false);
    }

    public bool IsWeaponUnlocked(string weapon_)
    {
        if (weaponUnlockState.ContainsKey(weapon_))
            return weaponUnlockState[weapon_];              // this will return either true or false if the weapon is unlocked or not
        else
            return false;
    }

    public void UnlockWeapon(string weapon_)            //this will be called by the button..
    {
        if (weaponUnlockState.ContainsKey(weapon_))
            weaponUnlockState[weapon_] = true;
    }
}

The WeaponSwitchergets the name of the weapon from the nested children every time the nextWeapon button is pressed:

weaponName = this.gameObject.transform.GetChild(weaponIdx).name.ToString();     //get the name of the child at current index

        if (weaponUnlock.IsWeaponUnlocked(weaponName))      //ask weaponUnlockSystem if this name weapon is unlocked or not, only enable the transform if true is returned
            selectedWeapon = weaponIdx;

This...... works..... but I know is not practical. As the script sits on a game object and at every time it is called the Start() is called that will reset all the unlocked values. Also will I have to make it persistent via DontDestroyOnLOad() through scenes?

I can get use PlayerPrefs and set a value for every weapon, but that is also not ideal and also to avoid it being reset every time someone opens my game I would have to perform a checks of PlayerPrefs.HasKey() for every weapon. Also not practical.

There must be a better way of doing this. Its funny that I cannot find much help online for this and dont know how everyone is getting around this.

Thanks

Body:
You create a class that is not a GameObject, just a normal class. There you can initialize the dictionary and have methods to unlock or check if a weapon is unlocked.

As I don't know what your architecture of the rest of the code looks like, I will go ahead and assume that you have some kind of a persistent player model.

You could just add the WeaponUnlockSystem to your player GameObject and manage the unlocks from there.
To me this would make the most sense as the player is probably the one unlocking the weapons so the WeaponUnlockSystem should be attached to him.

Here is a really basic code example:

public class WeaponUnlockSystem {

    private Dictionary<string, bool> weaponUnlockState;

    public WeaponUnlockSystem()
    {
        weaponUnlockState = new Dictionary<string, bool>();
        weaponUnlockState.Add("Shotgun", true);
        weaponUnlockState.Add("Rifle", true);
        weaponUnlockState.Add("FireballGun", false);
        weaponUnlockState.Add("LaserGun", false);
        weaponUnlockState.Add("FlamethrowerGun", false);
        weaponUnlockState.Add("SuperGun", false);
    }

    public bool IsWeaponUnlocked(string weapon)
    {
        if (weaponUnlockState.ContainsKey(weapon))
            return weaponUnlockState[weapon];
        else
            return false;
    }

    public void UnlockWeapon(string weapon)
    {
        if (weaponUnlockState.ContainsKey(weapon))
            weaponUnlockState[weapon] = true;
    }
}

public class Player : MonoBehaviour {

    private WeaponUnlockSystem weaponUnlockSystem;

    void Start()
    {
        weaponUnlockSystem = new WeaponUnlockSystem();
        ...
    }

    public void NextWeapon(string weapon)
    {
        ...
    }
}

I would also advice against using a static class for convenience here. Static should only be used, if you don't want to change the state of an object or don't need to create an instance of an object.


问:
Deployed Applet Suddenly Not Working
I put together an applet that uploads images via as3httpclientlib to a servlet. The applet works fine in debug mode (through flash builder) and until today it worked when deployed.

From the servlet logs, it appears the servlet never receives the image(s) byte stream, therefore my hunch is the applet is not posting the multipart data.

Can anyone suggest what I should do next to find the cause of the problem?

答:
I suppose you ran into problem described here:

In Flash Player 10 and later, if you
  use a multipart Content-Type (for
  example "multipart/form-data") that
  contains an upload (indicated by a
  "filename" parameter in a
  "content-disposition" header within
  the POST body), the POST operation is
  subject to the security rules applied
  to uploads:

The POST operation must be performed
  in response to a user-initiated
  action, such as a mouse click or key
  press.

If the POST operation is
  cross-domain (the POST target is not
  on the same server as the SWF file
  that is sending the POST request), the
  target server must provide a URL
  policy file that permits cross-domain
  access.

So I think you should run your application using debugger and check Flex client logs for exceptions described above.

ContentLicense: CC BY-SA 3.0

Title: Deployed Applet Suddenly Not Working


问:
Most elegant way to convert string array into a dictionary of strings
Is there a built-in function for converting a string array into a dictionary of strings or do you need to do a loop here?</p>

答:
The Question is not very clear, but Yes you can convert a string to Dictionary provided the string is delimited with some characters to support Dictionary<Key,Value> pair

So if a string is like  a=first;b=second;c=third;d=fourth you can split it first based on ; then on = to create a Dictionary<string,string> the below extension method does the same

public static Dictionary<string, string> ToDictionary(this string stringData, char propertyDelimiter = ';', char keyValueDelimiter = '=')
{
    Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
    Array.ForEach<string>(stringData.Split(propertyDelimiter), s =>
        {
            if(s != null && s.Length != 0)
                keyValuePairs.Add(s.Split(keyValueDelimiter)[0], s.Split(keyValueDelimiter)[1]);
        });

    return keyValuePairs;
}
```
<p>and can use it like</p>
<pre class="lang-cs prettyprint-override"><code>var myDictionary = "a=first;b=second;c=third;d=fourth".ToDictionary();
</code>```

since the default parameter is ; & = for the extension method.

Body:
The Question is not very clear, but Yes you can convert a string to Dictionary provided the string is delimited with some characters to support Dictionary<Key,Value> pair

So if a string is like  a=first;b=second;c=third;d=fourth you can split it first based on ; then on = to create a Dictionary<string,string> the below extension method does the same

public static Dictionary<string, string> ToDictionary(this string stringData, char propertyDelimiter = ';', char keyValueDelimiter = '=')
{
    Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
    Array.ForEach<string>(stringData.Split(propertyDelimiter), s =>
        {
            if(s != null && s.Length != 0)
                keyValuePairs.Add(s.Split(keyValueDelimiter)[0], s.Split(keyValueDelimiter)[1]);
        });

    return keyValuePairs;
}

and can use it like

var myDictionary = "a=first;b=second;c=third;d=fourth".ToDictionary();

since the default parameter is ; & = for the extension method.


问:
How to sort the data while searching according to the ratings they get and also for not those are not rated

I have a project of human resource management where I want to
  display the ratings and non ratings jobseekers while searching as a
  employer.

```<code>I have tried this but this only gives jobseekers whose ratings has been set.
</code>```

```<code>public function search(Request $request)
    {
        $query = $request->get('query');
        if (isset($query)) {
            $queryParam = explode(' ', $query);
        } else {
            $queryParam = null;
        }
        $jobseekers = JobSeekers::where(function ($que) use ($queryParam) {
            if (isset($queryParam)) {
                foreach ($queryParam as $queries) {
                    $que->orWhere('job_seekers.category', 'like', '%' . $queries . '%');
                    $que->orWhere('job_seekers.keywords', 'like', '%' . $queries . '%');
                    $que->orWhere('job_seekers.experience', 'like', '%' . $queries . '%');
                }
            }
        })->join('ratings', 'job_seekers.id', '=', 'ratings.js_id')
            ->groupBy('job_seekers.id')
            ->select('job_seekers.id', DB::raw('AVG( ratings.rating )  AS average_rating'))
            ->orderBy('average_rating', 'desc')
            ->get();
        return view('search.search_all', compact('jobseekers'));
    }
</code>```

```<code>    I have a rating table .
</code>```

```<code>    Schema::create('ratings', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('emp_id')->unsigned();
        $table->integer('js_id')->unsigned();
        $table->integer('rating')->unsigned();
        $table->longText('description')->nullable();
        $table->foreign('emp_id')->references('id')->on('employers');
        $table->foreign('js_id')->references('id')->on('job_seekers');
        $table->timestamps();
    });
</code>```

I get data of only objects whose ratings is given but not for the
  datas that exists but has no rating.

答:
Try leftJoin() instead of join().

JOIN selects only results having data in joined table.

LEFT JOIN selects all results and attach data from the joined table.

```<code>public function search(Request $request)
{
    $jobseekers = JobSeekers
        ::when($request->get('query'), function($query) use ($request) {
            $words = explode(' ', $request->get('query'));
            foreach($words as $word){
                $query->orWhere('job_seekers.category', 'like', '%' . $word . '%');
                $query->orWhere('job_seekers.keywords', 'like', '%' . $word . '%');
                $query->orWhere('job_seekers.experience', 'like', '%' . $word . '%');
            }
        })
        ->leftJoin('ratings', 'job_seekers.id', '=', 'ratings.js_id')
        ->groupBy('job_seekers.id')
        ->select('job_seekers.id', DB::raw('AVG( ratings.rating )  AS average_rating'))
        ->orderBy('average_rating', 'desc')
        ->get();

    return view('search.search_all', compact('jobseekers'));
}
</code>```

Body:
I have a project of human resource management where I want to
  display the ratings and non ratings jobseekers while searching as a
  employer.

I have tried this but this only gives jobseekers whose ratings has been set.

public function search(Request $request)
    {
        $query = $request->get('query');
        if (isset($query)) {
            $queryParam = explode(' ', $query);
        } else {
            $queryParam = null;
        }
        $jobseekers = JobSeekers::where(function ($que) use ($queryParam) {
            if (isset($queryParam)) {
                foreach ($queryParam as $queries) {
                    $que->orWhere('job_seekers.category', 'like', '%' . $queries . '%');
                    $que->orWhere('job_seekers.keywords', 'like', '%' . $queries . '%');
                    $que->orWhere('job_seekers.experience', 'like', '%' . $queries . '%');
                }
            }
        })->join('ratings', 'job_seekers.id', '=', 'ratings.js_id')
            ->groupBy('job_seekers.id')
            ->select('job_seekers.id', DB::raw('AVG( ratings.rating )  AS average_rating'))
            ->orderBy('average_rating', 'desc')
            ->get();
        return view('search.search_all', compact('jobseekers'));
    }

    I have a rating table .

    Schema::create('ratings', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('emp_id')->unsigned();
        $table->integer('js_id')->unsigned();
        $table->integer('rating')->unsigned();
        $table->longText('description')->nullable();
        $table->foreign('emp_id')->references('id')->on('employers');
        $table->foreign('js_id')->references('id')->on('job_seekers');
        $table->timestamps();
    });

I get data of only objects whose ratings is given but not for the
  datas that exists but has no rating.

Body:
Try leftJoin() instead of join().

JOIN selects only results having data in joined table.

LEFT JOIN selects all results and attach data from the joined table.

public function search(Request $request)
{
    $jobseekers = JobSeekers
        ::when($request->get('query'), function($query) use ($request) {
            $words = explode(' ', $request->get('query'));
            foreach($words as $word){
                $query->orWhere('job_seekers.category', 'like', '%' . $word . '%');
                $query->orWhere('job_seekers.keywords', 'like', '%' . $word . '%');
                $query->orWhere('job_seekers.experience', 'like', '%' . $word . '%');
            }
        })
        ->leftJoin('ratings', 'job_seekers.id', '=', 'ratings.js_id')
        ->groupBy('job_seekers.id')
        ->select('job_seekers.id', DB::raw('AVG( ratings.rating )  AS average_rating'))
        ->orderBy('average_rating', 'desc')
        ->get();

    return view('search.search_all', compact('jobseekers'));
}


问:
Does getting a synchronized collection from collections class synchronize a class?
I am trying to understand what does synchronizedCollection, synchronizedList, synchronizedMap, synchronizedSet and other such methods do. From what I understand synchronization can be done on blocks and methods and not on classes so let's say if I have a hashmap.

```<code>HashMap<Integer,String> hashMap = new HashMap<Integer,String>();
HashMap<Integer,String> syncHashMap = Collections.synchronizedMap(hashMap);
</code>```

Questions

So did the above code just synchronized whole syncHashMap class or
every method inside it?

If we can simply use a threadsafe collection such as
ConcurrentHashMap or SynchronizedMap in multithreading scenario then what's the need of
Collections.synchronizedMap(hashMap) and other similar methods in
Collections class

Will deeply appreciate some direction on this, thanks in advance.

答:
Before answering your question, lets reiterate some basics of synchronization

The synchronization is always on an object/instance. Every synchronized instance is guarded by a lock (called mutex).

Any thread invoking a synchronized method on the object, has to acquire that lock first and then invoke that method.

This lock acquisition is not needed why an unsychronized method is called.

To answer your questions:

So did the above code just synchronized whole syncHashMap class or every method inside it?

Yes it does. Just look at the source code of Collections.SynchronizedMap here. Notice almost every method has synchronized (mutex) block.

If we can simply use a threadsafe collection such as ConcurrentHashMap or SynchronizedMap in multithreading scenario then what's the need of Collections.synchronizedMap(hashMap) and other similar methods in Collections class?

Well there are disadvantages of synchronizing every method (including read-only type methods). It slows down the read operation unnecessarily and hence your observation is right i.e. to use the implementations such as ConcurrentHashMap which lock only the method which is modifying the collection. The read-only methods are not synchronized and hence its faster in multithread scenario with concurrent read/write operations.

The only advantage Collections.synchronizedMap offers is to preserve the order of the keys entered. So when you need that you use Collections.synchronizedMap.

Body:
I am trying to understand what does synchronizedCollection, synchronizedList, synchronizedMap, synchronizedSet and other such methods do. From what I understand synchronization can be done on blocks and methods and not on classes so let's say if I have a hashmap.

HashMap<Integer,String> hashMap = new HashMap<Integer,String>();
HashMap<Integer,String> syncHashMap = Collections.synchronizedMap(hashMap);

Questions

So did the above code just synchronized whole syncHashMap class or
every method inside it?

If we can simply use a threadsafe collection such as
ConcurrentHashMap or SynchronizedMap in multithreading scenario then what's the need of
Collections.synchronizedMap(hashMap) and other similar methods in
Collections class

Will deeply appreciate some direction on this, thanks in advance.


问:
System.Diagnostics.Activity is null in aspnet core 2.1
We've just updated an aspnet core 2.0 application to 2.1 and have run into a problem with our usage/reliance on System.Diagnostics.Activity.

Background

We want a consistent 'correlation id' passed across our service boundaries, so that we can correlate log entries per request.

The approach we took was:

Add a diagnostic listener to the middleware pipeline for Microsoft.AspNetCore.Hosting.HttpRequestIn.Start

When this listener was invoked, check if there was a header in the context.request called "Request-Id", and if there wasn't then add one with a value of Activity.Current.Id

Another piece of middleware took care of pushing the "Request-Id" header value into the logging context

This worked just fine in 2.0 and the hierarchical nature of Activity.Current.Id meant we could correlate log entries across different services and layers. In 2.1 we are now getting exceptions because Activity.Current appears to always be null on the point-of-entry for a request (i.e. the first service that is hit, in this case an API).

I've not managed to find any information that suggests that an activity is no longer automatically started whenever an HttpRequest comes in, but that's what it seems like is happening. Is anyone able to shed any light on what has changed and/or what we're doing wrong?

Some code

The startup configure method ...

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, DiagnosticListener diagnosticListener)
        {
           diagnosticListener.SubscribeWithAdapter(new HttpRequestInDiagnosticListener());
           app.UseMiddleware<SetRequestIdHeaderForHttpRequestInMiddleware>();

            if (env.IsDevelopment())
                app.UseDeveloperExceptionPage();
            else
                app.UseStatusCodePages();

            app.UseSecurityHeaders(Headers.AddSecurityHeaders());

            app.UseMvc();
        }
</code>```

... and the custom classes involved

```<code>    public class HttpRequestInDiagnosticListener
    {
        [DiagnosticName("Microsoft.AspNetCore.Hosting.HttpRequestIn.Start")]
        public virtual void OnMiddlewareStarting(HttpContext httpContext)
        {
            Console.WriteLine($"Middleware Starting, path: {httpContext.Request.Path}");
        }
    }

    public class SetRequestIdHeaderForHttpRequestInMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly DiagnosticSource _diagnostics;

        public SetRequestIdHeaderForHttpRequestInMiddleware(RequestDelegate next, DiagnosticSource diagnosticSource)
        {
            _next = next;
            _diagnostics = diagnosticSource;
        }

        public async Task Invoke(HttpContext context)
        {

            if (_diagnostics.IsEnabled("Microsoft.AspNetCore.Hosting.HttpRequestIn.Start"))
            {
                if (!context.Request.Headers.Keys.Contains("Request-Id"))
                {
                    context.Request.Headers.Add("Request-Id", Activity.Current.Id);
                }
            }

            await _next.Invoke(context);
        }
    }
</code>```

答: You can use HttpContext.TraceIdentifier instead of Activity.Current.Id. I have similar use case and use HttpContext.TraceIdentifier to identify requests inside logs. For more info look at this answer: https://stackoverflow.com/a/50694180/5632590

Body:
We've just updated an aspnet core 2.0 application to 2.1 and have run into a problem with our usage/reliance on System.Diagnostics.Activity.

Background

We want a consistent 'correlation id' passed across our service boundaries, so that we can correlate log entries per request.

The approach we took was:

Add a diagnostic listener to the middleware pipeline for Microsoft.AspNetCore.Hosting.HttpRequestIn.Start

When this listener was invoked, check if there was a header in the context.request called "Request-Id", and if there wasn't then add one with a value of Activity.Current.Id

Another piece of middleware took care of pushing the "Request-Id" header value into the logging context

This worked just fine in 2.0 and the hierarchical nature of Activity.Current.Id meant we could correlate log entries across different services and layers. In 2.1 we are now getting exceptions because Activity.Current appears to always be null on the point-of-entry for a request (i.e. the first service that is hit, in this case an API).

I've not managed to find any information that suggests that an activity is no longer automatically started whenever an HttpRequest comes in, but that's what it seems like is happening. Is anyone able to shed any light on what has changed and/or what we're doing wrong?

Some code

The startup configure method ...

public void Configure(IApplicationBuilder app, IHostingEnvironment env, DiagnosticListener diagnosticListener)
        {
           diagnosticListener.SubscribeWithAdapter(new HttpRequestInDiagnosticListener());
           app.UseMiddleware<SetRequestIdHeaderForHttpRequestInMiddleware>();

            if (env.IsDevelopment())
                app.UseDeveloperExceptionPage();
            else
                app.UseStatusCodePages();

            app.UseSecurityHeaders(Headers.AddSecurityHeaders());

            app.UseMvc();
        }

... and the custom classes involved

    public class HttpRequestInDiagnosticListener
    {
        [DiagnosticName("Microsoft.AspNetCore.Hosting.HttpRequestIn.Start")]
        public virtual void OnMiddlewareStarting(HttpContext httpContext)
        {
            Console.WriteLine($"Middleware Starting, path: {httpContext.Request.Path}");
        }
    }

    public class SetRequestIdHeaderForHttpRequestInMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly DiagnosticSource _diagnostics;

        public SetRequestIdHeaderForHttpRequestInMiddleware(RequestDelegate next, DiagnosticSource diagnosticSource)
        {
            _next = next;
            _diagnostics = diagnosticSource;
        }

        public async Task Invoke(HttpContext context)
        {

            if (_diagnostics.IsEnabled("Microsoft.AspNetCore.Hosting.HttpRequestIn.Start"))
            {
                if (!context.Request.Headers.Keys.Contains("Request-Id"))
                {
                    context.Request.Headers.Add("Request-Id", Activity.Current.Id);
                }
            }

            await _next.Invoke(context);
        }
    }


问:
What browsers does AngularJS work with?
This can be a most common question. But no any clue about browser versions. More over, Angular site itself says as following.

What browsers does Angular work with?

We run our extensive test suite against the following browsers: the latest versions of Chrome, Firefox, Safari, and Safari for iOS, as well as Internet Explorer versions 9-11. See Internet Explorer Compatibility for more details on supporting legacy IE browsers.

If a browser is untested, it doesn't mean it won't work. You can also expect browsers to work that share a large part of their codebase with a browser we test, such as Opera 15 or newer (uses the Blink engine), or the various Firefox derivatives.

— AngularJS FAQ - What browsers does AngularJS work with?

However, there is no any note which versions are supported. I googled, but couldn't find. Any one let me know what browsers and their versions do support which version of angular ?

答:
According to AngularJS document：Internet Explorer Compatibility, the answer should be IE 9。

AngularJS 1.3 has dropped support for IE8. Read more about it on our blog. AngularJS 1.2 will continue to support IE8, but the core team does not plan to spend time addressing issues specific to IE8 or earlier.

The project currently supports and will attempt to fix bugs for IE9 and above. The continuous integration server runs all the tests against IE9, IE10, and IE11.

Title: What browsers does AngularJS work with?


问:
Use same entity field multiple times with different admin code in sonata form
I'm using Sonata admin in my Symfony project. I have 2 entities like Parent and Child. Parent entity is connected to child by one-to-many relationship.

I have created 2 admin classes for child entity with different baseRoutName. I need to use Child entity fields in Parent entity sonata form for 2 times.

```<code>//ParentAdmin.php
    $formMapper
            ->with('Child 1', ['class' => 'col-md-4'])
            ->add('child', CollectionType::class, [], [
                'edit' => 'inline',
                'inline' => 'table',
                'sortable' => 'position',
                'admin_code' => 'admin.child1'
            ])
            ->end()
            ->with('Child 2', ['class' => 'col-md-4'])
            ->add('child', CollectionType::class, [], [
                'edit' => 'inline',
                'inline' => 'table',
                'sortable' => 'position',
                'admin_code' => 'admin.child2'
            ])
            ->end();
</code>```

The problem here is that I need to use child field for multiple times. But the child field within Child 2 is overriding the child field in Child 1. As you can see I have used different admin_code for these 2 fields.

My expected output is,

But the actual output I'm getting is,

I know the problem here is duplicate entity fields. Is it possible to display same field for multiple times?

Does anyone have solution/suggestion? Thanks in advance!!

答:
maybe it's late but i had the same problem, found this post with no answer, and finally found a solution, so here it is for future purpose.

i have a Request class with generated document, get an eye on get and add functions:

```<code>class Request
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\OneToMany(targetEntity="GeneratedDocument", mappedBy="request", cascade={"all"}, orphanRemoval=true)
     */
    protected $generatedDocuments;

    /**
     * @var ArrayCollection
     * each of this attributes will get one type of $generatedDocuments
     */
    protected $generatedAttestationDocuments;
    protected $generatedCertificationDocuments;

    public function __construct()
    {
        $this->generatedDocuments = new ArrayCollection();
    }

    /**
     * Set the value of id.
     *
     * @param integer $id
     * @return \App\Entity\Request
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Get the value of id.
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return Collection|GeneratedDocument[]
     */
    public function getGeneratedDocuments(): Collection
    {
        return $this->generatedDocuments;
    }

    public function addGeneratedDocument(GeneratedDocument $generatedDocument): self
    {
        if (!$this->generatedDocuments->contains($generatedDocument)) {
            $this->generatedDocuments[] = $generatedDocument;
            $generatedDocument->setRequest($this);
        }

        return $this;
    }

    public function removeGeneratedDocument(GeneratedDocument $generatedDocument): self
    {
        if ($this->generatedDocuments->contains($generatedDocument)) {
            $this->generatedDocuments->removeElement($generatedDocument);
            // set the owning side to null (unless already changed)
            if ($generatedDocument->getRequest() === $this) {
                $generatedDocument->setRequest(null);
            }
        }

        return $this;
    }

    /**
     * @return Collection|GeneratedDocument[]
     *
     * @param int $type
     */
    protected function getTypedGeneratedDocuments(int $type): Collection
    {
        return $this->getGeneratedDocuments()->filter(function (GeneratedDocument $gd) use ($type) {
            if ($gd->getGeneratedDocumentModel()) {
                return $type === $gd->getGeneratedDocumentModel()->getType();
            }
            return false;
        });
    }

    /**
     * @return Collection|GeneratedDocument[]
     */
    public function getGeneratedAttestationDocuments(): Collection
    {
        if (empty($this->generatedAttestationDocuments)) {
            $this->generatedAttestationDocuments =
                $this->getTypedGeneratedDocuments(GeneratedDocumentModel::TYPE_ATTESTATION);
        }

        return $this->generatedAttestationDocuments;
    }

    public function addGeneratedAttestationDocument(GeneratedDocument $generatedDocument): self
    {
        $this->generatedAttestationDocuments[] = $generatedDocument;
        return $this->addGeneratedDocument($generatedDocument);
    }

    public function removeGeneratedAttestationDocument(GeneratedDocument $generatedDocument): self
    {
        return $this->removeGeneratedDocument($generatedDocument);
    }

    /**
     * @return Collection|GeneratedDocument[]
     */
    public function getGeneratedCertificationDocuments(): Collection
    {
        if (empty($this->generatedCertificationDocuments)) {
            $this->generatedCertificationDocuments =
                $this->getTypedGeneratedDocuments(GeneratedDocumentModel::TYPE_CERTIFICATE);
        }

        return $this->generatedCertificationDocuments;
    }

    public function addGeneratedCertificationDocument(GeneratedDocument $generatedDocument): self
    {
        $this->generatedCertificationDocuments[] = $generatedDocument;
        return $this->addGeneratedDocument($generatedDocument);
    }

    public function removeGeneratedCertificationDocument(GeneratedDocument $generatedDocument): self
    {
        return $this->removeGeneratedDocument($generatedDocument);
    }
}
</code>```

Then in admin you have to give a different name in each add, here I use my typed generated documents so there's no duplication problem, but they are not mapped and symfony complain about it.

Trying to use 'mapped' => false resolved nothing, the simplest way I found was a 'virtual mapping', based on the original mapped attribute 'generatedDocuments, just the time to fool symfony when building the form.

```<code>class RequestAdmin extends AbstractAdmin
{
    protected function configureFormFields(FormMapper $formMapper): void
    {
        /** @var Request $createdRequest */
        $createdRequest = $this->getSubject();

        $metaData = $this->getModelManager()->getMetadata($this->getClass());
        //We need many CollectionType based on 'generatedDocuments', and we need an ArrayCollection for each of them
        //so here is a virtual mapping to make symfony accept the persistence of our CollectionType
        //then setter should fill 'generatedDocuments'
        $mapping = $metaData->getAssociationMappings()['generatedDocuments'];
        $mapping['fieldName'] = 'generatedAttestationDocuments';
        $metaData->mapOneToMany($mapping);
        $mapping['fieldName'] = 'generatedCertificationDocuments';
        $metaData->mapOneToMany($mapping);

        $formMapper
            ->with(('Attestation Deposit'))
                ->add('generatedAttestationDocuments', CollectionType::class, [
                    'label' => false,
                    'by_reference' => false,
                    'btn_add' => 'Add Attestation',
                    'data' => $createdRequest->getGeneratedAttestationDocuments(),
                ], [
                    'edit' => 'inline',
                    'inline' => 'table',
                    'admin_code' => 'admin.generated_document_attestation',
                ])
            ->end()
            ->with(('Certificate'))
                ->add('generatedCertificationDocuments', CollectionType::class, [
                    'label' => false,
                    'by_reference' => false,
                    'btn_add' => 'Add Certification',
                    'data' => $createdRequest->getGeneratedCertificationDocuments(),
                ], [
                    'edit' => 'inline',
                    'inline' => 'table',
                    'admin_code' => 'admin.generated_document_certification',
                ])
            ->end()

        //delete virtual mapping to avoid it to get handle like a real mapping
        unset($metaData->associationMappings['generatedAttestationDocuments']);
        unset($metaData->associationMappings['generatedCertificationDocuments']);
    }
}
</code>```

I would like to know a simplest way, but It really work like individual CollectionType for me.

Hope it will help!

Body:
I'm using Sonata admin in my Symfony project. I have 2 entities like Parent and Child. Parent entity is connected to child by one-to-many relationship.

I have created 2 admin classes for child entity with different baseRoutName. I need to use Child entity fields in Parent entity sonata form for 2 times.

//ParentAdmin.php
    $formMapper
            ->with('Child 1', ['class' => 'col-md-4'])
            ->add('child', CollectionType::class, [], [
                'edit' => 'inline',
                'inline' => 'table',
                'sortable' => 'position',
                'admin_code' => 'admin.child1'
            ])
            ->end()
            ->with('Child 2', ['class' => 'col-md-4'])
            ->add('child', CollectionType::class, [], [
                'edit' => 'inline',
                'inline' => 'table',
                'sortable' => 'position',
                'admin_code' => 'admin.child2'
            ])
            ->end();

The problem here is that I need to use child field for multiple times. But the child field within Child 2 is overriding the child field in Child 1. As you can see I have used different admin_code for these 2 fields.

My expected output is,

But the actual output I'm getting is,

I know the problem here is duplicate entity fields. Is it possible to display same field for multiple times?

Does anyone have solution/suggestion? Thanks in advance!!

Body:
maybe it's late but i had the same problem, found this post with no answer, and finally found a solution, so here it is for future purpose.

i have a Request class with generated document, get an eye on get and add functions:

class Request
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\OneToMany(targetEntity="GeneratedDocument", mappedBy="request", cascade={"all"}, orphanRemoval=true)
     */
    protected $generatedDocuments;

    /**
     * @var ArrayCollection
     * each of this attributes will get one type of $generatedDocuments
     */
    protected $generatedAttestationDocuments;
    protected $generatedCertificationDocuments;

    public function __construct()
    {
        $this->generatedDocuments = new ArrayCollection();
    }

    /**
     * Set the value of id.
     *
     * @param integer $id
     * @return \App\Entity\Request
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Get the value of id.
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return Collection|GeneratedDocument[]
     */
    public function getGeneratedDocuments(): Collection
    {
        return $this->generatedDocuments;
    }

    public function addGeneratedDocument(GeneratedDocument $generatedDocument): self
    {
        if (!$this->generatedDocuments->contains($generatedDocument)) {
            $this->generatedDocuments[] = $generatedDocument;
            $generatedDocument->setRequest($this);
        }

        return $this;
    }

    public function removeGeneratedDocument(GeneratedDocument $generatedDocument): self
    {
        if ($this->generatedDocuments->contains($generatedDocument)) {
            $this->generatedDocuments->removeElement($generatedDocument);
            // set the owning side to null (unless already changed)
            if ($generatedDocument->getRequest() === $this) {
                $generatedDocument->setRequest(null);
            }
        }

        return $this;
    }

    /**
     * @return Collection|GeneratedDocument[]
     *
     * @param int $type
     */
    protected function getTypedGeneratedDocuments(int $type): Collection
    {
        return $this->getGeneratedDocuments()->filter(function (GeneratedDocument $gd) use ($type) {
            if ($gd->getGeneratedDocumentModel()) {
                return $type === $gd->getGeneratedDocumentModel()->getType();
            }
            return false;
        });
    }

    /**
     * @return Collection|GeneratedDocument[]
     */
    public function getGeneratedAttestationDocuments(): Collection
    {
        if (empty($this->generatedAttestationDocuments)) {
            $this->generatedAttestationDocuments =
                $this->getTypedGeneratedDocuments(GeneratedDocumentModel::TYPE_ATTESTATION);
        }

        return $this->generatedAttestationDocuments;
    }

    public function addGeneratedAttestationDocument(GeneratedDocument $generatedDocument): self
    {
        $this->generatedAttestationDocuments[] = $generatedDocument;
        return $this->addGeneratedDocument($generatedDocument);
    }

    public function removeGeneratedAttestationDocument(GeneratedDocument $generatedDocument): self
    {
        return $this->removeGeneratedDocument($generatedDocument);
    }

    /**
     * @return Collection|GeneratedDocument[]
     */
    public function getGeneratedCertificationDocuments(): Collection
    {
        if (empty($this->generatedCertificationDocuments)) {
            $this->generatedCertificationDocuments =
                $this->getTypedGeneratedDocuments(GeneratedDocumentModel::TYPE_CERTIFICATE);
        }

        return $this->generatedCertificationDocuments;
    }

    public function addGeneratedCertificationDocument(GeneratedDocument $generatedDocument): self
    {
        $this->generatedCertificationDocuments[] = $generatedDocument;
        return $this->addGeneratedDocument($generatedDocument);
    }

    public function removeGeneratedCertificationDocument(GeneratedDocument $generatedDocument): self
    {
        return $this->removeGeneratedDocument($generatedDocument);
    }
}

Then in admin you have to give a different name in each add, here I use my typed generated documents so there's no duplication problem, but they are not mapped and symfony complain about it.

Trying to use 'mapped' => false resolved nothing, the simplest way I found was a 'virtual mapping', based on the original mapped attribute 'generatedDocuments, just the time to fool symfony when building the form.

class RequestAdmin extends AbstractAdmin
{
    protected function configureFormFields(FormMapper $formMapper): void
    {
        /** @var Request $createdRequest */
        $createdRequest = $this->getSubject();

        $metaData = $this->getModelManager()->getMetadata($this->getClass());
        //We need many CollectionType based on 'generatedDocuments', and we need an ArrayCollection for each of them
        //so here is a virtual mapping to make symfony accept the persistence of our CollectionType
        //then setter should fill 'generatedDocuments'
        $mapping = $metaData->getAssociationMappings()['generatedDocuments'];
        $mapping['fieldName'] = 'generatedAttestationDocuments';
        $metaData->mapOneToMany($mapping);
        $mapping['fieldName'] = 'generatedCertificationDocuments';
        $metaData->mapOneToMany($mapping);

        $formMapper
            ->with(('Attestation Deposit'))
                ->add('generatedAttestationDocuments', CollectionType::class, [
                    'label' => false,
                    'by_reference' => false,
                    'btn_add' => 'Add Attestation',
                    'data' => $createdRequest->getGeneratedAttestationDocuments(),
                ], [
                    'edit' => 'inline',
                    'inline' => 'table',
                    'admin_code' => 'admin.generated_document_attestation',
                ])
            ->end()
            ->with(('Certificate'))
                ->add('generatedCertificationDocuments', CollectionType::class, [
                    'label' => false,
                    'by_reference' => false,
                    'btn_add' => 'Add Certification',
                    'data' => $createdRequest->getGeneratedCertificationDocuments(),
                ], [
                    'edit' => 'inline',
                    'inline' => 'table',
                    'admin_code' => 'admin.generated_document_certification',
                ])
            ->end()

        //delete virtual mapping to avoid it to get handle like a real mapping
        unset($metaData->associationMappings['generatedAttestationDocuments']);
        unset($metaData->associationMappings['generatedCertificationDocuments']);
    }
}

I would like to know a simplest way, but It really work like individual CollectionType for me.

Hope it will help!


答:
Your code is summing the first N Fibonacci numbers that are odd. You seem to be looking for the first odd Fibonacci numbers that sum to N:

function oddFibsThatAddTo(target)
{
  let currentFib = 1;
  let lastFib = 1;
  let sum = 2;
  const outs = [1,1];
  while(sum < target)
  {
    let nextFib = currentFib + lastFib;
    if(nextFib % 2 == 1)
    {
      sum += nextFib;
      outs.push(nextFib);
    }
    lastFib = currentFib;
    currentFib = nextFib;
  }
  if(sum > target)
  {
    throw 'can\'t find perfect sequence';
  }
  return outs;
}

console.log(oddFibsThatAddTo(10))```

Title: Sum of all odd fibonacci numbers upto n

Body:
I am stuck in summing up to number 10. Can't get it right.
What i am getting is the total sum from 10 digits (after filtering odd only 7). Where should i make <= num ?

function sumFibs(num) {
  var fib = [1, 1];
  for (var i = 2; i < num; i++) {
    var next = fib[i - 1] + fib[i - 2];
    var fibi = fib.push(next);
  }

  return fib.filter(function(a) {
      return (a % 2 != 0);
    })
    .reduce(function(a, z) {
      return a + z;
    })
}
console.log(sumFibs(10));

Expected output 10, but getting 99


问:
How do I display a different website logo to mobile users in WordPress?
I'm working on E-Commerce theme and I've been trying to make the site display a different logo if the device is a mobile, is this possible?

NOTE: I'm using a WordPress theme called storefront.

答:
Try this

```<code><style>
  .sitelogo .mobilelogo {
    display: none;
  }

  @media (max-width: 600px) {
    .sitelogo .mobilelogo {
      display: block;
    }
    .sitelogo .desktoplogo {
      display: none;
    }
  }
</style>

<div class="sitelogo">
  <img src="/images/logo_desktop.png" class="desktoplogo" />
  <img src="/images/logo_mobile.png" class="mobilelogo" />
</div>
</code>```

And also try following code, Check this link for better reference

```<code>if ( wp_is_mobile() ) {
    /* Include/display resources targeted to phones/tablets here */
} else {
    /* Include/display resources targeted to laptops/desktops here */
}
</code>```

Body:
Try this

<style>
  .sitelogo .mobilelogo {
    display: none;
  }

  @media (max-width: 600px) {
    .sitelogo .mobilelogo {
      display: block;
    }
    .sitelogo .desktoplogo {
      display: none;
    }
  }
</style>

<div class="sitelogo">
  <img src="/images/logo_desktop.png" class="desktoplogo" />
  <img src="/images/logo_mobile.png" class="mobilelogo" />
</div>

And also try following code, Check this link for better reference

if ( wp_is_mobile() ) {
    /* Include/display resources targeted to phones/tablets here */
} else {
    /* Include/display resources targeted to laptops/desktops here */
}


问:
How to fix delayed data on prepare segue?
My data got delayed 1 time when I want to pass the data in my tableview and pass it to another viewcontroller

i'm using prepare for segue.

now, in order to get the right data i need go back to the table view and press the same row

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toRequestCorrection"{
            let destinationVC = segue.destination as! RequestCorrectionViewController
            if let indexPath = tableView.indexPathForSelectedRow{
                destinationVC.Shift = self.correction["Shift"].stringValue
                destinationVC.LogDate = self.correction["LogDate"].stringValue
                destinationVC.logIn = self.correction["ActualLogIn"].stringValue
                destinationVC.logOut = self.correction["ActualLogOut"].stringValue
                destinationVC.breakEnd = self.correction["ActualBreakEnd"].stringValue
                destinationVC.breakStart = self.correction["ActualBreakStart"].stringValue
                destinationVC.overTimeIn = self.correction["ActualOverTimeIn"].stringValue
                destinationVC.overTimeOut = self.correction["ActualOverTimeOut"].stringValue
                destinationVC.transactionStatusID = self.correction["TransactionStatusID"].intValue
            }
        }
    }
```

it's should pass the data on the row right after i pressed the row

答:
You should implement tableVew(_:willSelectRowAt:) method of UITableViewDelegate in your viewController and set your correction property to selected row's value.

```<code>class YourSourceViewController: UITableViewDelegate{
    var correction: Correction!

    func tableView(_ tabelView: UITableView, willSelecRowAt indexPath: IndexPath) -> IndexPath?{
        correction = correctionList[indexPath.row]
        return indexPath
    }

    func prepare(for segue: UIStoryBoardSegue, sender: Any?){
        //passing data to RequestCorrectionViewController.
        //And also you don't need to check if indexPath is nil.
        //Because this block will called only any row of tableView is selected.
    }
}
</code>```

Also note that you could do same thing in tableView(_:didSelectRowAt:) method but this method works after performing segues and cause the problem you are encountered too.

Edit

If you think using willSelectRowAt: method is a misusing, you can set your segue's source your viewController (instead of template cell) and set identifier on Storyboard and call it programmatically. like @vadian's said

```<code>func tableView(_ tabelView: UITableView, didSelecRowAt indexPath: IndexPath){
        correction = correctionList[indexPath.row]
        performSegue(withIdentifier "mySegueIdentifier", sender: self)
    }
</code>```

Body:
My data got delayed 1 time when I want to pass the data in my tableview and pass it to another viewcontroller

i'm using prepare for segue.

now, in order to get the right data i need go back to the table view and press the same row

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toRequestCorrection"{
            let destinationVC = segue.destination as! RequestCorrectionViewController
            if let indexPath = tableView.indexPathForSelectedRow{
                destinationVC.Shift = self.correction["Shift"].stringValue
                destinationVC.LogDate = self.correction["LogDate"].stringValue
                destinationVC.logIn = self.correction["ActualLogIn"].stringValue
                destinationVC.logOut = self.correction["ActualLogOut"].stringValue
                destinationVC.breakEnd = self.correction["ActualBreakEnd"].stringValue
                destinationVC.breakStart = self.correction["ActualBreakStart"].stringValue
                destinationVC.overTimeIn = self.correction["ActualOverTimeIn"].stringValue
                destinationVC.overTimeOut = self.correction["ActualOverTimeOut"].stringValue
                destinationVC.transactionStatusID = self.correction["TransactionStatusID"].intValue
            }
        }
    }

it's should pass the data on the row right after i pressed the row

Body:
You should implement tableVew(_:willSelectRowAt:) method of UITableViewDelegate in your viewController and set your correction property to selected row's value.

class YourSourceViewController: UITableViewDelegate{
    var correction: Correction!

    func tableView(_ tabelView: UITableView, willSelecRowAt indexPath: IndexPath) -> IndexPath?{
        correction = correctionList[indexPath.row]
        return indexPath
    }

    func prepare(for segue: UIStoryBoardSegue, sender: Any?){
        //passing data to RequestCorrectionViewController.
        //And also you don't need to check if indexPath is nil.
        //Because this block will called only any row of tableView is selected.
    }
}

Also note that you could do same thing in tableView(_:didSelectRowAt:) method but this method works after performing segues and cause the problem you are encountered too.

Edit

If you think using willSelectRowAt: method is a misusing, you can set your segue's source your viewController (instead of template cell) and set identifier on Storyboard and call it programmatically. like @vadian's said

func tableView(_ tabelView: UITableView, didSelecRowAt indexPath: IndexPath){
        correction = correctionList[indexPath.row]
        performSegue(withIdentifier "mySegueIdentifier", sender: self)
    }