问:
Log4Net Writing Exception Twice To Log with Custom Layout
I am developing an ASP.Net web application and am running into an issue with Log4Net writing out exceptions with a custom layout. I am configuring a rolling file appender in my Global.asax programmatically (not using web.config setup) in the following way:

```<code>// Create basic file logging appender for the application.
var fileAppender = new RollingFileAppender
{
     Layout = new JsonPatternLayout(),
     File = $"c:/logs/web.log",
     AppendToFile = true,
     RollingStyle = RollingFileAppender.RollingMode.Date,
     DatePattern = "yyyyMMdd'.log'",
     StaticLogFileName = true,
     Threshold = Level.Debug
};
fileAppender.ActivateOptions();
log4net.Config.BasicConfigurator.Configure(fileAppender);
</code>```

JsonPatternLayout is a custom class I wrote to take the Logging event from Log4Net and serialize it to json format for easier digestion into a logging service:

```<code>public class JsonPatternLayout : PatternLayout
{
    public override void Format(TextWriter writer, LoggingEvent e)
    {
        var dic = new Dictionary<string, string>
        {
            ["level"] = e.Level.DisplayName,
            ["session"] = e.Identity,
            ["timestamp"] = e.TimeStamp.ToString(),
            ["message"] = e.RenderedMessage,
            ["logger"] = e.LoggerName,
            ["exception"] = e.ExceptionObject == null ? string.Empty : e.ExceptionObject.ToString(),
            ["thread"] = e.ThreadName,
            ["machineName"] = Environment.MachineName
        };
            writer.Write($"{JsonConvert.SerializeObject(dic)}\n");
    }
}
</code>```

This results in a file output where an exception is written twice -- once in json from from my pattern layout, and again as a string (messages sanitized for clarity):

```<code>{"level":"INFO","session":"1","timestamp":"2/14/2020 5:07:12 PM","message":"Message","logger":"Logger","exception":"","thread":"7", "machineName":"Machine"}
{"level":"INFO","session":"1","timestamp":"2/14/2020 5:07:14 PM","message":"Message","logger":"Logger","exception":"","thread":"10","machineName":"Machine"}
{"level":"ERROR","session":"1","timestamp":"2/14/2020 5:07:14 PM","message":"Message","logger":"Logger","exception":"System.Exception: Boo!\r\n   at {CallStack}","thread":"10","machineName":"Machine"}
System.Exception: Boo!
   at {Call Stack}
</code>```

What I want is for that second time for the exception to not be written out at all. As best as I can tell, this is not going through my formatter because its not a message I am explicitly raising, but rather from the .Net framework itself. Trapping exceptions and not re-throwing them does not keep the exception from logging a second time.

How do I stop this behavior?

答:
I wound up resolving this issue by replacing Log4net with Serilog. I was able to re-use my custom formatter with a few tweaks since Serilog implements many of the same interfaces anyways:

```<code>Log.Logger = new LoggerConfiguration()
    // Configure file sink.
    .WriteTo.RollingFile(
        new JsonPatternLayout(),
        @"c:\path\logs\app-{Date}.log",
        LogEventLevel.Information,
        retainedFileCountLimit: 90)
    .CreateLogger();
</code>```

```<code>public class JsonPatternLayout : ITextFormatter
{
    public void Format(LogEvent e, TextWriter writer)
    {
        var dic = new Dictionary<string, object>
        {
            ["level"] = e.Level.ToString(),
            ["session"] = System.Threading.Thread.CurrentPrincipal.Identity.Name,
            ["timestamp"] = e.Timestamp.ToLocalTime().ToString(),
            ["message"] = e.RenderMessage(),
            ["Properties"] = e.Properties,
            ["exception"] = e.Exception == null ? string.Empty : e.Exception.ToString(),
            ["machineName"] = machineName
        };
        writer.Write($"{JsonConvert.SerializeObject(dic)}\n");
    }
}
</code>```

My logging messages are formatted the same way Log4net did them, and the exceptions are not doubly logged. Was a bit of a pain to replace Log4net entirely, but went very smoothly.

Many thanks to everyone who helped and look at this.

Body:
I am developing an ASP.Net web application and am running into an issue with Log4Net writing out exceptions with a custom layout. I am configuring a rolling file appender in my Global.asax programmatically (not using web.config setup) in the following way:

// Create basic file logging appender for the application.
var fileAppender = new RollingFileAppender
{
     Layout = new JsonPatternLayout(),
     File = $"c:/logs/web.log",
     AppendToFile = true,
     RollingStyle = RollingFileAppender.RollingMode.Date,
     DatePattern = "yyyyMMdd'.log'",
     StaticLogFileName = true,
     Threshold = Level.Debug
};
fileAppender.ActivateOptions();
log4net.Config.BasicConfigurator.Configure(fileAppender);

JsonPatternLayout is a custom class I wrote to take the Logging event from Log4Net and serialize it to json format for easier digestion into a logging service:

public class JsonPatternLayout : PatternLayout
{
    public override void Format(TextWriter writer, LoggingEvent e)
    {
        var dic = new Dictionary<string, string>
        {
            ["level"] = e.Level.DisplayName,
            ["session"] = e.Identity,
            ["timestamp"] = e.TimeStamp.ToString(),
            ["message"] = e.RenderedMessage,
            ["logger"] = e.LoggerName,
            ["exception"] = e.ExceptionObject == null ? string.Empty : e.ExceptionObject.ToString(),
            ["thread"] = e.ThreadName,
            ["machineName"] = Environment.MachineName
        };
            writer.Write($"{JsonConvert.SerializeObject(dic)}\n");
    }
}

This results in a file output where an exception is written twice -- once in json from from my pattern layout, and again as a string (messages sanitized for clarity):

{"level":"INFO","session":"1","timestamp":"2/14/2020 5:07:12 PM","message":"Message","logger":"Logger","exception":"","thread":"7", "machineName":"Machine"}
{"level":"INFO","session":"1","timestamp":"2/14/2020 5:07:14 PM","message":"Message","logger":"Logger","exception":"","thread":"10","machineName":"Machine"}
{"level":"ERROR","session":"1","timestamp":"2/14/2020 5:07:14 PM","message":"Message","logger":"Logger","exception":"System.Exception: Boo!\r\n   at {CallStack}","thread":"10","machineName":"Machine"}
System.Exception: Boo!
   at {Call Stack}

What I want is for that second time for the exception to not be written out at all. As best as I can tell, this is not going through my formatter because its not a message I am explicitly raising, but rather from the .Net framework itself. Trapping exceptions and not re-throwing them does not keep the exception from logging a second time.

How do I stop this behavior?

Body:
I wound up resolving this issue by replacing Log4net with Serilog. I was able to re-use my custom formatter with a few tweaks since Serilog implements many of the same interfaces anyways:

Log.Logger = new LoggerConfiguration()
    // Configure file sink.
    .WriteTo.RollingFile(
        new JsonPatternLayout(),
        @"c:\path\logs\app-{Date}.log",
        LogEventLevel.Information,
        retainedFileCountLimit: 90)
    .CreateLogger();

public class JsonPatternLayout : ITextFormatter
{
    public void Format(LogEvent e, TextWriter writer)
    {
        var dic = new Dictionary<string, object>
        {
            ["level"] = e.Level.ToString(),
            ["session"] = System.Threading.Thread.CurrentPrincipal.Identity.Name,
            ["timestamp"] = e.Timestamp.ToLocalTime().ToString(),
            ["message"] = e.RenderMessage(),
            ["Properties"] = e.Properties,
            ["exception"] = e.Exception == null ? string.Empty : e.Exception.ToString(),
            ["machineName"] = machineName
        };
        writer.Write($"{JsonConvert.SerializeObject(dic)}\n");
    }
}

My logging messages are formatted the same way Log4net did them, and the exceptions are not doubly logged. Was a bit of a pain to replace Log4net entirely, but went very smoothly.

Many thanks to everyone who helped and look at this.


来源: stackexchange

问:
PHP array_fill array with multiples of the same record
I have this function; I'm trying to fill the $records array with multiple entries of each $vendor. Only the first record goes in the $records array 12 times like I want it to. Now I would like to get the rest to do the same.

```<code>function vendors()
{
    $vendor = [
        "Chick-Fil-A #03971 Houston TX" => 3,
        "Uber Trip Help.Uber.Com TX" => 8,
        "Starbucks Store 05 Houston TX" => 3,
        "Shell Service S Houston TX" => 3,
        "Ralphs #0 1200 N Centr Houston TX" => 3,
        "Nails Van Nuys TX" => 3,
        "Postmates Ed3F9 to Httpspostmate CA" => 3,
        "Pico Beauty Supply and SA Houston TX" => 3,
        "Big Mamas & Papas 818-679-9976 TX" => 3,
        "CIT-GO Houston TX" => 3,
        "Dollar Tree Houston TX" => 3,
        "McDonald's M6310 O Houston TX" => 5,
        "Jamba Juice - Houston TX" => 3,
        "Cvs/Pharm 10445--125 N Glendale" => 3,
    ];
    $records = array();
    foreach ($vendor as $key => $value)
    {
        $times = $value * 4;
        $records = array_fill(0, $times, $key);
    }
    return $records;
}
</code>```

答:
you are over-writing your array variable again and again instead of assigning new data to it.

Do:

```<code>$records[] = array_fill(0, $times, $key);//assign data as child-array to your final array
</code>```

Output:-https://3v4l.org/rVdKg

Or may be you want like this:- https://3v4l.org/2Yb8B

ContentLicense: CC BY-SA 4.0

Body:
I have this function; I'm trying to fill the $records array with multiple entries of each $vendor. Only the first record goes in the $records array 12 times like I want it to. Now I would like to get the rest to do the same.

function vendors()
{
    $vendor = [
        "Chick-Fil-A #03971 Houston TX" => 3,
        "Uber Trip Help.Uber.Com TX" => 8,
        "Starbucks Store 05 Houston TX" => 3,
        "Shell Service S Houston TX" => 3,
        "Ralphs #0 1200 N Centr Houston TX" => 3,
        "Nails Van Nuys TX" => 3,
        "Postmates Ed3F9 to Httpspostmate CA" => 3,
        "Pico Beauty Supply and SA Houston TX" => 3,
        "Big Mamas & Papas 818-679-9976 TX" => 3,
        "CIT-GO Houston TX" => 3,
        "Dollar Tree Houston TX" => 3,
        "McDonald's M6310 O Houston TX" => 5,
        "Jamba Juice - Houston TX" => 3,
        "Cvs/Pharm 10445--125 N Glendale" => 3,
    ];
    $records = array();
    foreach ($vendor as $key => $value)
    {
        $times = $value * 4;
        $records = array_fill(0, $times, $key);
    }
    return $records;
}

Body:
you are over-writing your array variable again and again instead of assigning new data to it.

Do:

$records[] = array_fill(0, $times, $key);//assign data as child-array to your final array

Output:-https://3v4l.org/rVdKg

Or may be you want like this:- https://3v4l.org/2Yb8B


问:
Values from Select option are not printed when I click on Print button
I have coded a javascript button to print all HTML from my page. When I click on the same, all prints fine except the values of option on select. Below is the code snippet.

Live demo of the issue:

https://codepen.io/T9-T9/pen/VwLKbOv

So on the demo, if you update the options from "a" to "b" or other and click on "Print Result", it will still print the default "a" and not what you select. Code snippet as below.

The HTML:

```<code><div class="container" id="printcontent">
        <div class="row">
            <div>
            <h4>Title here</h4>
                <form>
                    <fieldset>
                        <label class='life_area'>01</label>
                        <select id='01'>
                          <option value="1">a</option>
                          <option value="2">b</option>
                          <option value="3">c</option>
                          <option value="4">d</option>
                        </select>
                        <label class='life_area'>02</label>
                        <select id='02'>
                          <option value="1">a</option>
                          <option value="2">b</option>
                          <option value="3">c</option>
                          <option value="4">d</option>
                        </select>
                    </fieldset>
                </form>
            </div>
        </div>
    </div>
    <div id="print-content">
         <form>
          <input type="button" class="print-result" onClick="PrintElem('print-content')" value="print result"/>
        </form>
    </div>
</code>```

The JavaScript:

```<code>function PrintElem(elem)
        {
            var mywindow = window.open('', 'PRINT', 'height=800,width=2200');

            mywindow.document.write('<html><head>');
            mywindow.document.write('</head><body>');
            mywindow.document.write(document.getElementById('printcontent').innerHTML);
            mywindow.document.write('</body></html>');

            mywindow.document.close();
            mywindow.focus();

            setTimeout(function () {
            mywindow.print();
            mywindow.close();
            }, 1000)
            return true;
        }
</code>```

I made multiple updates, but cannot fix this part.

答:
The innerHTML of an element will only retrieve the HTML markup - it won't retrieve state of an element which may not be in the HTML. For example, when a select changes, that doesn't change the HTML markup. (similarly, neither does putting text into an input box, nor does adding an event listener).

In this case, you can iterate through the options which are selected, and give them the selected attribute, which will be reflected in the HTML markup (and therefore retrieved properly). The selected attribute will result in the option in question being selected on pageload:

```<code>for (const option of document.querySelectorAll('option:checked')) {
  option.setAttribute('selected', '')
}
mywindow.document.write(document.getElementById('printcontent').innerHTML);
</code>```

Body:
I have coded a javascript button to print all HTML from my page. When I click on the same, all prints fine except the values of option on select. Below is the code snippet.

Live demo of the issue:

https://codepen.io/T9-T9/pen/VwLKbOv

So on the demo, if you update the options from "a" to "b" or other and click on "Print Result", it will still print the default "a" and not what you select. Code snippet as below.

The HTML:

Title here

                <form>
                    <fieldset>
                        01
                        <select id='01'>
                          <option value="1">a</option>
                          <option value="2">b</option>
                          <option value="3">c</option>
                          <option value="4">d</option>
                        </select>
                        02
                        <select id='02'>
                          <option value="1">a</option>
                          <option value="2">b</option>
                          <option value="3">c</option>
                          <option value="4">d</option>
                        </select>
                    </fieldset>
                </form>

         <form>
          <input type="button" class="print-result" onClick="PrintElem('print-content')" value="print result"/>
        </form>

The JavaScript:

function PrintElem(elem)
        {
            var mywindow = window.open('', 'PRINT', 'height=800,width=2200');

            mywindow.document.write('');
            mywindow.document.write('');
            mywindow.document.write(document.getElementById('printcontent').innerHTML);
            mywindow.document.write('');

            mywindow.document.close();
            mywindow.focus();

            setTimeout(function () {
            mywindow.print();
            mywindow.close();
            }, 1000)
            return true;
        }

I made multiple updates, but cannot fix this part.

Body:
The innerHTML of an element will only retrieve the HTML markup - it won't retrieve state of an element which may not be in the HTML. For example, when a select changes, that doesn't change the HTML markup. (similarly, neither does putting text into an input box, nor does adding an event listener).

In this case, you can iterate through the options which are selected, and give them the selected attribute, which will be reflected in the HTML markup (and therefore retrieved properly). The selected attribute will result in the option in question being selected on pageload:

for (const option of document.querySelectorAll('option:checked')) {
  option.setAttribute('selected', '')
}
mywindow.document.write(document.getElementById('printcontent').innerHTML);


问:
Using React to create a form, how could I get my err message to display on Submit (when the submit button is clicked)?
I am using React to create a form with two input text and would like to display an error message every time the user enters a non-numerical value as the age and clicks the submit button. The form apparently is doing most of what I want but it is not displaying the error message.

NB: I would love not to use the alert() syntax here if possible.

Thanks for your help.

class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      age: null,
      errormessage: ''
    };
  }

 errorHandler = () => {
  let err = '';
  if (nam === "age") {
    if (val !="" && !Number(val)) {
      err = Your age must be a number;
    }
  }
  this.setState({errormessage: err});
 }

  myChangeHandler = (event) => {
    let nam = event.target.name;
    let val = event.target.value;
    this.setState({[nam]: val});
  }

  render() {
    return (
      <form onSubmit={this.errorHandler}>

Hello {this.state.username} {this.state.age}

Enter your name:

      <input
        type='text'
        name='username'
        onChange={this.myChangeHandler}
      />

Enter your age:

      <input
        type='text'
        name='age'
        onChange={this.myChangeHandler}
      />

      <input
        type='submit'
      />
      {this.state.errormessage}
      </form>
    );
  }
}
ReactDOM.render(<MyForm />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div></code>```

答:
You can show error message below Age field. It is conditional rendering. It will be rendered only when errormessage contains some value.

```<code>render() {
    return (
      <form onSubmit={this.errorHandler}>
      <h1>Hello {this.state.username} {this.state.age}</h1>
      <p>Enter your name:</p>
      <input
        type='text'
        name='username'
        onChange={this.myChangeHandler}
      />
      <p>Enter your age:</p>
      <input
        type='text'
        name='age'
        onChange={this.myChangeHandler}
      />
      <br/>
      {this.state.errormessage ?
       <div id="err">{this.state.errorMessage}</div>
       : null}
      <input
        type='submit'
      />
      {this.state.errormessage}
      </form>
    );
  }
}
</code>```

You can test it by checking if div with id=err is rendered.

Body:
You can show error message below Age field. It is conditional rendering. It will be rendered only when errormessage contains some value.

render() {
    return (
      <form onSubmit={this.errorHandler}>
      <h1>Hello {this.state.username} {this.state.age}</h1>
      <p>Enter your name:</p>
      <input
        type='text'
        name='username'
        onChange={this.myChangeHandler}
      />
      <p>Enter your age:</p>
      <input
        type='text'
        name='age'
        onChange={this.myChangeHandler}
      />
      <br/>
      {this.state.errormessage ?
       <div id="err">{this.state.errorMessage}</div>
       : null}
      <input
        type='submit'
      />
      {this.state.errormessage}
      </form>
    );
  }
}

You can test it by checking if div with id=err is rendered.


问:
Python print/display only if the sum is not zero
I have a dataframe below:

```<code>df = pd.DataFrame({'Product': ['A', 'A', 'C', 'D'], 'Volume': ['-3', '3', '1', '5']})
</code>```

I am using groupby and sum.

```<code>final = df.groupby(['Product'])['Volume'].sum().reset_index()
print(final)
</code>```

This is ok.
But I only want the print to be carry only those where sum != 0. Like Product C and D

Any idea how can I do that?
I try to use:

```<code>if final != 0:
    print (final)
</code>```

But this is throwing error and usually when I get this error, the syntax is definitely wrong...

```<code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

答:
Your data frame has Volume as strings, is that intended? if you want to sum it like numbers you have to convert it to numbers then you can apply the filter.

df = pd.DataFrame({'Product': ['A', 'A', 'C', 'D'], 'Volume': ['-3', '3', '1', '5']})
# convert from string to integers
df.Volume = df.Volume.map(lambda x: int(x))
final = df.groupby(['Product'])['Volume'].sum().reset_index()
#choose ones with sum none zero
print(final[final.Volume != 0])
```

it will print only the C & D

Body:
I have a dataframe below:

df = pd.DataFrame({'Product': ['A', 'A', 'C', 'D'], 'Volume': ['-3', '3', '1', '5']})

I am using groupby and sum.

final = df.groupby(['Product'])['Volume'].sum().reset_index()
print(final)

This is ok.
But I only want the print to be carry only those where sum != 0. Like Product C and D

Any idea how can I do that?
I try to use:

if final != 0:
    print (final)

But this is throwing error and usually when I get this error, the syntax is definitely wrong...

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Body:
Your data frame has Volume as strings, is that intended? if you want to sum it like numbers you have to convert it to numbers then you can apply the filter.

df = pd.DataFrame({'Product': ['A', 'A', 'C', 'D'], 'Volume': ['-3', '3', '1', '5']})
# convert from string to integers
df.Volume = df.Volume.map(lambda x: int(x))
final = df.groupby(['Product'])['Volume'].sum().reset_index()
#choose ones with sum none zero
print(final[final.Volume != 0])

it will print only the C & D


问:
Kafka connect size based rollover with time based rollover on individual partitions
I am using Kafka connect to sink files to HDFS , Kafka connect has TopicPartitionWriter which does rollover on time to all partitions  and there is no size based rollover .

I want to do size based and time based rollover but for each partitions because as data passing though each partition is not uniform, also similar size files.

2 questions:
1. If I try to do this by changing a lot of code in Kafka connect that will loose original design ?
2. Is there any thing done for my use case ?

答:
TopicPartitionWriter which does rollover on time to all partitions and there is no size based rollover

flush.size is still (and always) used.

If I try to do this by changing a lot of code in Kafka connect that will loose original design

No? As long as data goes from Kafka to some external system, that's the only contract that Connect Sink API provides

Is there any thing done for my use case ?

Scan the issues and PRs of the Github repo


问:
Exponential moving averages in pandas
I have the following dataframe:

I'm trying to perform the calculation of an exponential moving average of 13 periods but the results don't match at all, I'm using the following code to try to get the result:

```<code>stockdata['sma'] = stockdata['close'].rolling(window = 13, min_periods=13).mean()
stockdata['ema'] = stockdata['close'].ewm(span=13, adjust=False).mean()
</code>```

simple media is working perfectly, only exponential moving media is not giving the correct values

the calculation of moving averages is done in the column 'close'

```<code>    ativo  close        sma        ema
0   PETR4  28.18        NaN  28.180000
1   PETR4  28.63        NaN  28.244286
2   PETR4  28.39        NaN  28.265102
3   PETR4  29.18        NaN  28.395802
4   PETR4  28.93        NaN  28.472116
5   PETR4  29.13        NaN  28.566099
6   PETR4  29.48        NaN  28.696656
7   PETR4  30.13        NaN  28.901420
8   PETR4  29.72        NaN  29.018360
9   PETR4  29.42        NaN  29.075737
10  PETR4  29.36        NaN  29.116346
11  PETR4  29.75        NaN  29.206868
12  PETR4  30.55  29.296154  29.398744
</code>```

on the dataframe the oldest data is on top, and the most recent below

the correct value of the exponential moving average of 13 should be 29.53,
what would be the correct way to use the function?

for the verification that I did on the investment platform, these values that the function is giving me are values of an arithmetic moving average

答:
The issue is that you're assuming that an EMA with span 13 is only looking at the last 13 data points... But that's not really the case, it will look past that date, simply use smaller weights for the data points further in the past...

If you take the last month of closing stock prices for PETR4 and take the 13-day EMA for them, you'll get at the expected result:

```<code>closing_price = pd.Series([
    30.00, 29.62, 29.29, 29.65, 29.30,
    28.03, 28.80, 28.85, 28.94, 28.45,
    28.18, 28.63, 28.39, 29.18, 28.93,
    29.13, 29.48, 30.13, 29.72, 29.42,
    29.36, 29.75, 30.55,
])
</code>```

And:

```<code>In []: closing_price.ewm(span=13, adjust=False).mean().iloc[-1]
Out[]: 29.52974644568118
</code>```

Which after rounding seems to match your expected answer.

Title: Exponential moving averages in pandas

Body:
I have the following dataframe:

I'm trying to perform the calculation of an exponential moving average of 13 periods but the results don't match at all, I'm using the following code to try to get the result:

stockdata['sma'] = stockdata['close'].rolling(window = 13, min_periods=13).mean()
stockdata['ema'] = stockdata['close'].ewm(span=13, adjust=False).mean()

simple media is working perfectly, only exponential moving media is not giving the correct values

the calculation of moving averages is done in the column 'close'

    ativo  close        sma        ema
0   PETR4  28.18        NaN  28.180000
1   PETR4  28.63        NaN  28.244286
2   PETR4  28.39        NaN  28.265102
3   PETR4  29.18        NaN  28.395802
4   PETR4  28.93        NaN  28.472116
5   PETR4  29.13        NaN  28.566099
6   PETR4  29.48        NaN  28.696656
7   PETR4  30.13        NaN  28.901420
8   PETR4  29.72        NaN  29.018360
9   PETR4  29.42        NaN  29.075737
10  PETR4  29.36        NaN  29.116346
11  PETR4  29.75        NaN  29.206868
12  PETR4  30.55  29.296154  29.398744

on the dataframe the oldest data is on top, and the most recent below

the correct value of the exponential moving average of 13 should be 29.53,
what would be the correct way to use the function?

for the verification that I did on the investment platform, these values that the function is giving me are values of an arithmetic moving average

Body:
The issue is that you're assuming that an EMA with span 13 is only looking at the last 13 data points... But that's not really the case, it will look past that date, simply use smaller weights for the data points further in the past...

If you take the last month of closing stock prices for PETR4 and take the 13-day EMA for them, you'll get at the expected result:

closing_price = pd.Series([
    30.00, 29.62, 29.29, 29.65, 29.30,
    28.03, 28.80, 28.85, 28.94, 28.45,
    28.18, 28.63, 28.39, 29.18, 28.93,
    29.13, 29.48, 30.13, 29.72, 29.42,
    29.36, 29.75, 30.55,
])

And:

In []: closing_price.ewm(span=13, adjust=False).mean().iloc[-1]
Out[]: 29.52974644568118

Which after rounding seems to match your expected answer.


问:
panic: Error initializing ledger provider: unable to connect to CouchDB, check the hostname and port: Get http://couchdb1:5984/: EOF
I am trying to start a hyperledger fabric network in Linux (RHEL 7) machine with docker-compose. But the peer containers are exiting after some time. In the peer container logs I can see below error.

```<code>2020-02-20 02:25:29.963 UTC [nodeCmd] serve -> INFO 001 Starting peer:
 Version: 1.4.4
 Commit SHA: 7917a40
 Go version: go1.12.12
 OS/Arch: linux/amd64
 Chaincode:
  Base Image Version: 0.4.18
  Base Docker Namespace: hyperledger
  Base Docker Label: org.hyperledger.fabric
  Docker Namespace: hyperledger
2020-02-20 02:25:29.964 UTC [ledgermgmt] initialize -> INFO 002 Initializing ledger mgmt
2020-02-20 02:25:29.964 UTC [kvledger] NewProvider -> INFO 003 Initializing ledger provider
2020-02-20 02:25:30.032 UTC [kvledger] NewProvider -> INFO 004 ledger provider Initialized
2020-02-20 02:25:30.200 UTC [couchdb] handleRequest -> WARN 005 Retrying couchdb request in 125ms. Attempt:1  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:25:30.386 UTC [couchdb] handleRequest -> WARN 006 Retrying couchdb request in 250ms. Attempt:2  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:25:30.689 UTC [couchdb] handleRequest -> WARN 007 Retrying couchdb request in 500ms. Attempt:3  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:25:31.241 UTC [couchdb] handleRequest -> WARN 008 Retrying couchdb request in 1s. Attempt:4  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:25:32.294 UTC [couchdb] handleRequest -> WARN 009 Retrying couchdb request in 2s. Attempt:5  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:25:34.347 UTC [couchdb] handleRequest -> WARN 00a Retrying couchdb request in 4s. Attempt:6  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:25:38.401 UTC [couchdb] handleRequest -> WARN 00b Retrying couchdb request in 8s. Attempt:7  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:25:46.455 UTC [couchdb] handleRequest -> WARN 00c Retrying couchdb request in 16s. Attempt:8  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:26:02.510 UTC [couchdb] handleRequest -> WARN 00d Retrying couchdb request in 32s. Attempt:9  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:26:34.565 UTC [couchdb] handleRequest -> WARN 00e Retrying couchdb request in 1m4s. Attempt:10  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:27:38.620 UTC [couchdb] handleRequest -> WARN 00f Retrying couchdb request in 2m8s. Attempt:11  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:29:46.675 UTC [couchdb] handleRequest -> WARN 010 Retrying couchdb request in 4m16s. Attempt:12  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:34:02.731 UTC [couchdb] handleRequest -> WARN 011 Retrying couchdb request in 8m32s. Attempt:13  Error:Get http://couchdb1:5984/: EOF
panic: Error initializing ledger provider: unable to connect to CouchDB, check the hostname and port: Get http://couchdb1:5984/: EOF

goroutine 1 [running]:
github.com/hyperledger/fabric/core/ledger/ledgermgmt.initialize(0xc0003728c0)
        /opt/gopath/src/github.com/hyperledger/fabric/core/ledger/ledgermgmt/ledger_mgmt.go:81 +0x78a
github.com/hyperledger/fabric/core/ledger/ledgermgmt.Initialize.func1()
        /opt/gopath/src/github.com/hyperledger/fabric/core/ledger/ledgermgmt/ledger_mgmt.go:53 +0x2a
sync.(*Once).Do(0x26d0748, 0xc0001ff458)
        /opt/go/src/sync/once.go:44 +0xb3
github.com/hyperledger/fabric/core/ledger/ledgermgmt.Initialize(0xc0003728c0)
        /opt/gopath/src/github.com/hyperledger/fabric/core/ledger/ledgermgmt/ledger_mgmt.go:52 +0x55
github.com/hyperledger/fabric/peer/node.serve(0x26d0668, 0x0, 0x0, 0x0, 0x0)
        /opt/gopath/src/github.com/hyperledger/fabric/peer/node/start.go:181 +0x568
github.com/hyperledger/fabric/peer/node.glob..func3(0x25c7240, 0x26d0668, 0x0, 0x0, 0x0, 0x0)
        /opt/gopath/src/github.com/hyperledger/fabric/peer/node/start.go:126 +0xf1
github.com/hyperledger/fabric/vendor/github.com/spf13/cobra.(*Command).execute(0x25c7240, 0x26d0668, 0x0, 0x0, 0x25c7240, 0x26d0668)
        /opt/gopath/src/github.com/hyperledger/fabric/vendor/github.com/spf13/cobra/command.go:762 +0x465
github.com/hyperledger/fabric/vendor/github.com/spf13/cobra.(*Command).ExecuteC(0x25c7960, 0xc0001fff60, 0x1, 0x1)
        /opt/gopath/src/github.com/hyperledger/fabric/vendor/github.com/spf13/cobra/command.go:852 +0x2ec
github.com/hyperledger/fabric/vendor/github.com/spf13/cobra.(*Command).Execute(...)
        /opt/gopath/src/github.com/hyperledger/fabric/vendor/github.com/spf13/cobra/command.go:800
main.main()
        /opt/gopath/src/github.com/hyperledger/fabric/peer/main.go:53 +0x41f
</code>```

I suspected there could be some dns issue in the docker container. So I have also tried
adding dns_search: . and - GODEBUG=netdns=go in the docker-compose.yaml file.

```<code>  peer0.org1.example.com:
    container_name: peer0.org1.example.com
    image: hyperledger/fabric-peer:1.4.4
    dns_search: .
    environment:
      - GODEBUG=netdns=go
      - CORE_PEER_ID=peer0.org1.example.com
      - CORE_PEER_ADDRESS=peer0.org1.example.com:7051
      - CORE_PEER_GOSSIP_BOOTSTRAP=peer1.org1.example.com:7051
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org1.example.com:7051
      - CORE_PEER_LOCALMSPID=Org1MSP
      - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
      - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${COMPOSE_PROJECT_NAME}_example
      - FABRIC_LOGGING_SPEC=INFO
      - CORE_PEER_TLS_ENABLED=true
      - CORE_PEER_GOSSIP_USELEADERELECTION=true
      - CORE_PEER_GOSSIP_ORGLEADER=false
      - CORE_PEER_PROFILE_ENABLED=true
      - CORE_PEER_TLS_CERT_FILE=/etc/hyperledger/fabric/tls/server.crt
      - CORE_PEER_TLS_KEY_FILE=/etc/hyperledger/fabric/tls/server.key
      - CORE_PEER_TLS_ROOTCERT_FILE=/etc/hyperledger/fabric/tls/ca.crt
      - CORE_LEDGER_STATE_STATEDATABASE=CouchDB
      - CORE_LEDGER_STATE_COUCHDBCONFIG_COUCHDBADDRESS=couchdb0:5984
      - CORE_LEDGER_STATE_COUCHDBCONFIG_USERNAME=admin
      - CORE_LEDGER_STATE_COUCHDBCONFIG_PASSWORD=admin

</code>```

It is still the same error.

答:
Check if you defined couchdb container in docker-compose.yaml.

If you have defined give the couchdb dependence on peer container.
something like

```<code>   - CORE_LEDGER_STATE_COUCHDBCONFIG_USERNAME=admin
   - CORE_LEDGER_STATE_COUCHDBCONFIG_PASSWORD=admin
depends_on:
   - couchdb1
</code>```

Check your couchdb  container is up. If not, up the container using docker-compose

Body:
I am trying to start a hyperledger fabric network in Linux (RHEL 7) machine with docker-compose. But the peer containers are exiting after some time. In the peer container logs I can see below error.

2020-02-20 02:25:29.963 UTC [nodeCmd] serve -> INFO 001 Starting peer:
 Version: 1.4.4
 Commit SHA: 7917a40
 Go version: go1.12.12
 OS/Arch: linux/amd64
 Chaincode:
  Base Image Version: 0.4.18
  Base Docker Namespace: hyperledger
  Base Docker Label: org.hyperledger.fabric
  Docker Namespace: hyperledger
2020-02-20 02:25:29.964 UTC [ledgermgmt] initialize -> INFO 002 Initializing ledger mgmt
2020-02-20 02:25:29.964 UTC [kvledger] NewProvider -> INFO 003 Initializing ledger provider
2020-02-20 02:25:30.032 UTC [kvledger] NewProvider -> INFO 004 ledger provider Initialized
2020-02-20 02:25:30.200 UTC [couchdb] handleRequest -> WARN 005 Retrying couchdb request in 125ms. Attempt:1  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:25:30.386 UTC [couchdb] handleRequest -> WARN 006 Retrying couchdb request in 250ms. Attempt:2  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:25:30.689 UTC [couchdb] handleRequest -> WARN 007 Retrying couchdb request in 500ms. Attempt:3  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:25:31.241 UTC [couchdb] handleRequest -> WARN 008 Retrying couchdb request in 1s. Attempt:4  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:25:32.294 UTC [couchdb] handleRequest -> WARN 009 Retrying couchdb request in 2s. Attempt:5  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:25:34.347 UTC [couchdb] handleRequest -> WARN 00a Retrying couchdb request in 4s. Attempt:6  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:25:38.401 UTC [couchdb] handleRequest -> WARN 00b Retrying couchdb request in 8s. Attempt:7  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:25:46.455 UTC [couchdb] handleRequest -> WARN 00c Retrying couchdb request in 16s. Attempt:8  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:26:02.510 UTC [couchdb] handleRequest -> WARN 00d Retrying couchdb request in 32s. Attempt:9  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:26:34.565 UTC [couchdb] handleRequest -> WARN 00e Retrying couchdb request in 1m4s. Attempt:10  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:27:38.620 UTC [couchdb] handleRequest -> WARN 00f Retrying couchdb request in 2m8s. Attempt:11  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:29:46.675 UTC [couchdb] handleRequest -> WARN 010 Retrying couchdb request in 4m16s. Attempt:12  Error:Get http://couchdb1:5984/: EOF
2020-02-20 02:34:02.731 UTC [couchdb] handleRequest -> WARN 011 Retrying couchdb request in 8m32s. Attempt:13  Error:Get http://couchdb1:5984/: EOF
panic: Error initializing ledger provider: unable to connect to CouchDB, check the hostname and port: Get http://couchdb1:5984/: EOF

goroutine 1 [running]:
github.com/hyperledger/fabric/core/ledger/ledgermgmt.initialize(0xc0003728c0)
        /opt/gopath/src/github.com/hyperledger/fabric/core/ledger/ledgermgmt/ledger_mgmt.go:81 +0x78a
github.com/hyperledger/fabric/core/ledger/ledgermgmt.Initialize.func1()
        /opt/gopath/src/github.com/hyperledger/fabric/core/ledger/ledgermgmt/ledger_mgmt.go:53 +0x2a
sync.(*Once).Do(0x26d0748, 0xc0001ff458)
        /opt/go/src/sync/once.go:44 +0xb3
github.com/hyperledger/fabric/core/ledger/ledgermgmt.Initialize(0xc0003728c0)
        /opt/gopath/src/github.com/hyperledger/fabric/core/ledger/ledgermgmt/ledger_mgmt.go:52 +0x55
github.com/hyperledger/fabric/peer/node.serve(0x26d0668, 0x0, 0x0, 0x0, 0x0)
        /opt/gopath/src/github.com/hyperledger/fabric/peer/node/start.go:181 +0x568
github.com/hyperledger/fabric/peer/node.glob..func3(0x25c7240, 0x26d0668, 0x0, 0x0, 0x0, 0x0)
        /opt/gopath/src/github.com/hyperledger/fabric/peer/node/start.go:126 +0xf1
github.com/hyperledger/fabric/vendor/github.com/spf13/cobra.(*Command).execute(0x25c7240, 0x26d0668, 0x0, 0x0, 0x25c7240, 0x26d0668)
        /opt/gopath/src/github.com/hyperledger/fabric/vendor/github.com/spf13/cobra/command.go:762 +0x465
github.com/hyperledger/fabric/vendor/github.com/spf13/cobra.(*Command).ExecuteC(0x25c7960, 0xc0001fff60, 0x1, 0x1)
        /opt/gopath/src/github.com/hyperledger/fabric/vendor/github.com/spf13/cobra/command.go:852 +0x2ec
github.com/hyperledger/fabric/vendor/github.com/spf13/cobra.(*Command).Execute(...)
        /opt/gopath/src/github.com/hyperledger/fabric/vendor/github.com/spf13/cobra/command.go:800
main.main()
        /opt/gopath/src/github.com/hyperledger/fabric/peer/main.go:53 +0x41f

I suspected there could be some dns issue in the docker container. So I have also tried
adding dns_search: . and - GODEBUG=netdns=go in the docker-compose.yaml file.

  peer0.org1.example.com:
    container_name: peer0.org1.example.com
    image: hyperledger/fabric-peer:1.4.4
    dns_search: .
    environment:
      - GODEBUG=netdns=go
      - CORE_PEER_ID=peer0.org1.example.com
      - CORE_PEER_ADDRESS=peer0.org1.example.com:7051
      - CORE_PEER_GOSSIP_BOOTSTRAP=peer1.org1.example.com:7051
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org1.example.com:7051
      - CORE_PEER_LOCALMSPID=Org1MSP
      - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
      - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=${COMPOSE_PROJECT_NAME}_example
      - FABRIC_LOGGING_SPEC=INFO
      - CORE_PEER_TLS_ENABLED=true
      - CORE_PEER_GOSSIP_USELEADERELECTION=true
      - CORE_PEER_GOSSIP_ORGLEADER=false
      - CORE_PEER_PROFILE_ENABLED=true
      - CORE_PEER_TLS_CERT_FILE=/etc/hyperledger/fabric/tls/server.crt
      - CORE_PEER_TLS_KEY_FILE=/etc/hyperledger/fabric/tls/server.key
      - CORE_PEER_TLS_ROOTCERT_FILE=/etc/hyperledger/fabric/tls/ca.crt
      - CORE_LEDGER_STATE_STATEDATABASE=CouchDB
      - CORE_LEDGER_STATE_COUCHDBCONFIG_COUCHDBADDRESS=couchdb0:5984
      - CORE_LEDGER_STATE_COUCHDBCONFIG_USERNAME=admin
      - CORE_LEDGER_STATE_COUCHDBCONFIG_PASSWORD=admin

It is still the same error.

Body:
Check if you defined couchdb container in docker-compose.yaml.

If you have defined give the couchdb dependence on peer container.
something like

   - CORE_LEDGER_STATE_COUCHDBCONFIG_USERNAME=admin
   - CORE_LEDGER_STATE_COUCHDBCONFIG_PASSWORD=admin
depends_on:
   - couchdb1

Check your couchdb  container is up. If not, up the container using docker-compose


问:
The type or namespace EventProcessorClient could not be found
I am starting off with Event Hubs with .Net Core and am facing a very peculiar issue when trying to write the same code as in the official MS documentation(https://learn.microsoft.com/en-us/azure/event-hubs/get-started-dotnet-standard-send-v2). The event receiver code throws an error although I'm using it's containing namespace i.e. Azure.Messaging.EventHubs. Where am I going wrong here?

答: You need to install  Azure.Messaging.EventHubs.Processor as a dependency to the project. Even though the answer above is correct, I just attached the link.


问:
How to send progress success message after every bulk operation in asp.net Core
I have an excel sheet that contains 50,000 rows, Now I have to update these using EF.
but Without full-cycle complete, I can't send any success message to the user, and the web page shows "Processing....." and every other operation is stopped, when the operation is done after 10-15 min later, then the user can see the success message.
Now I want to do: User can see progress, such as "1000/ 50000 data updated", "2000/ 50000 data updated", "50000/ 50000 data updated". and user can do other operation between the current operation.

I tried using Async, But I can't find out the exact result.

Technology:
Asp.Net Core MVC 3.1
EF Core 3.1
SQL server 2017

答:
Based on yoour description and scenario, if possible, you can try following approach to achieve it:

1) For long-running bulk update operation, you can create and use a background task to handle it.

For exampel, using a queue triggered task, user can create a queue message for each new bulk update operation, then task would be triggered and process data from excel file.

2) For displaying progress of bulk update operation to web client user, you can integrate ASP.NET Core SignalR real-time web functionality into web client application.

In background task, call hub method to push progress message to the connected SignalR web client user(s).


问:
Positioning in Slimbox
Slimbox is working perfectly for me with one exception... my slideshows often open way to low. The positioning is effected by any scrolling already done on the page. Every time the page is scrolled a bit, the slideshow opens lower than it had previously for the same page. Scroll down the page much and the show can be completely out of sight.

lbCenter and lbBottomContainer in the CSS control the positioning, but I can't find how to adjust them accurately. The default is:

```<code>#lbCenter,
#lbBottomContainer {
 position: absolute;
 z-index: 9999;
 overflow: hidden;
 background-color: #fff;
}
</code>```

In an old thread here, I found suggestion for adding:

```<code>       top: 30px !important;
</code>```

As long as !important is included, this does work but with a significant caveat; the caption is moved from below to above the image and covers some of it. ( And !Important doesn't seem like an ideal solution )

How can I adjust the positioning of both while keeping the caption below the image?

答:
This one was on me. My links included href="#" as some others required. The # caused the page to scroll to the top even as the slide show opened where the link was located.

```<code><a href="#" onclick="show('homes')">
</code>```

Eliminating the hash tag resolved it.

Title: Positioning in Slimbox

Body:
Slimbox is working perfectly for me with one exception... my slideshows often open way to low. The positioning is effected by any scrolling already done on the page. Every time the page is scrolled a bit, the slideshow opens lower than it had previously for the same page. Scroll down the page much and the show can be completely out of sight.

lbCenter and lbBottomContainer in the CSS control the positioning, but I can't find how to adjust them accurately. The default is:

#lbCenter,
#lbBottomContainer {
 position: absolute;
 z-index: 9999;
 overflow: hidden;
 background-color: #fff;
}

In an old thread here, I found suggestion for adding:

       top: 30px !important;

As long as !important is included, this does work but with a significant caveat; the caption is moved from below to above the image and covers some of it. ( And !Important doesn't seem like an ideal solution )

How can I adjust the positioning of both while keeping the caption below the image?

Body:
This one was on me. My links included href="#" as some others required. The # caused the page to scroll to the top even as the slide show opened where the link was located.

<a href="#" onclick="show('homes')">

Eliminating the hash tag resolved it.


问:
upper casing all values within quotes " " except those coming after certain words
I am trying to replace every word within quotes " " to upper case word except those coming after the word "then" in a pandas column:
for example:

```<code>0 There was a "quick" "brown" fox who "jumped" over the wall then "fell" and broke its "tooth"
</code>```

the output should be:

```<code>0 There was a "QUICK" "BROWN" fox who "JUMPED" over the wall then "fell" and broke its "TOOTH"
</code>```

although I am able to find the words in quotes but I am not able to exclude the word coming right after "then".

```<code>df.str.replace({r'"(.*?)"':r'\U$1') #this will select and replace all values in quotes to uppercase also values after then
</code>```

please help.

答:
String= He "ate" a "penguin" then "played with a hamburger.
 Turn the string into a list splitting at the word then. Convert the list[0] into a string, and use an if '"' is in clause to isolate the quoted words. Capitalize. Then split by spaces, use join to get the whole string back together again and there ya go</p>

Body:
I am trying to replace every word within quotes " " to upper case word except those coming after the word "then" in a pandas column:
for example:

0 There was a "quick" "brown" fox who "jumped" over the wall then "fell" and broke its "tooth"

the output should be:

0 There was a "QUICK" "BROWN" fox who "JUMPED" over the wall then "fell" and broke its "TOOTH"

although I am able to find the words in quotes but I am not able to exclude the word coming right after "then".

df.str.replace({r'"(.*?)"':r'\U$1') #this will select and replace all values in quotes to uppercase also values after then

please help.


问:
How do we get the count of a list in my SQL?
The query I wrote works perfectly the only problem is that I need to get the count of the rows instead of the full list.

For example: here is my output and my query:

答:
You can change your query like following.</p>

```<code>select count(*) totalcount from
(
    select count(employeeid) ct
    from eventmanagment
    group by employeeid
    having count(*) > 5
)t
</code>```

Body:
You can change your query like following.

select count(*) totalcount from
(
    select count(employeeid) ct
    from eventmanagment
    group by employeeid
    having count(*) > 5
)t


问:
Can I avoid using BuildServiceProvider in startup?
Can I avoid using BuildServiceProvider in ExpireToken function below? In other words...

Is there a way of avoiding BuildServiceProvider() in Startup.cs when using JWTBearer OnAuthenticationFailed event?

(Using Web API aspnet Core 3.0)

Startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
    {
        //some code removed..

        //Authentication
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.Events = new JwtBearerEvents()
            {
                OnAuthenticationFailed = context =>
                {

                    if (context.Exception.Message.Contains("The token is expired"))
                    {
                        Microsoft.Extensions.Primitives.StringValues token = string.Empty;

                        var logger = new LoggerManager();
                        logger.LogError("Token expired"); //confirming that the token expired so authentication failed

                        var header = context.Request.Headers;

                        if (!header.TryGetValue("Authorization", out token))
                            logger.LogError("no token found");
                        else
                            token = token.ToString().Substring("Bearer ".Length).Trim();

                        ExpireToken(services, token);
                    }
                    return Task.CompletedTask;
                }
            };
         });
     }

public void ExpireToken(IServiceCollection services, string tokenId)
    {
        var sp = services.BuildServiceProvider();

        var jwtManager = sp.GetService<IJWTAuthenticationManager>();
        jwtManager.ExpireToken(tokenId);
    }
</code>```

jwtAuthentication Manager will publish this event so that subscribers are notified (c#:event + delegates)

```<code>public delegate void TokenExpiredEventHandler(object source, TokenExpiredEventArgs args);
</code>```

JWTAuthenticationManager.cs

```<code>public class JWTAuthenticationManager : IJWTAuthenticationManager
{
    private readonly string _tokenKey;
    public event TokenExpiredEventHandler TokenExpired;

    //some code removed for brevity
    public void ExpireToken(string tokenId)
    {
        OnTokenExpired(tokenId); //notify all subscribers
    }
    protected virtual void OnTokenExpired(string token) {
        TokenExpired?.Invoke(this, new TokenExpiredEventArgs(token));
    }
}

public class TokenExpiredEventArgs : EventArgs
{
    public string token;

    public TokenExpiredEventArgs(string tokenId)
    {
        token = tokenId;
    }
}
</code>```

Program.cs

```<code>public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();

        var jwtMgr = host.Services.GetRequiredService<IJWTAuthenticationManager>();
        var cacheMgr = host.Services.GetRequiredService<ICacheManager>();
        jwtMgr.TokenExpired += cacheMgr.OnTokenExpired;

        host.Run();
    }
</code>```

答:
Why not resolve services from context? Simply change your ExpireToken method to take an IServiceProvider:

```<code>public void ExpireToken(IServiceProvider services, string tokenId)
{
    var jwtManager = services.GetService<IJWTAuthenticationManager>();
    jwtManager.ExpireToken(tokenId);
}
</code>```

And then pass context.HttpContext.RequestServices:

```<code>ExpireToken(context.HttpContext.RequestServices, token);
</code>```

Body:
Can I avoid using BuildServiceProvider in ExpireToken function below? In other words...

Is there a way of avoiding BuildServiceProvider() in Startup.cs when using JWTBearer OnAuthenticationFailed event?

(Using Web API aspnet Core 3.0)

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        //some code removed..

        //Authentication
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.Events = new JwtBearerEvents()
            {
                OnAuthenticationFailed = context =>
                {

                    if (context.Exception.Message.Contains("The token is expired"))
                    {
                        Microsoft.Extensions.Primitives.StringValues token = string.Empty;

                        var logger = new LoggerManager();
                        logger.LogError("Token expired"); //confirming that the token expired so authentication failed

                        var header = context.Request.Headers;

                        if (!header.TryGetValue("Authorization", out token))
                            logger.LogError("no token found");
                        else
                            token = token.ToString().Substring("Bearer ".Length).Trim();

                        ExpireToken(services, token);
                    }
                    return Task.CompletedTask;
                }
            };
         });
     }

public void ExpireToken(IServiceCollection services, string tokenId)
    {
        var sp = services.BuildServiceProvider();

        var jwtManager = sp.GetService<IJWTAuthenticationManager>();
        jwtManager.ExpireToken(tokenId);
    }

jwtAuthentication Manager will publish this event so that subscribers are notified (c#:event + delegates)

public delegate void TokenExpiredEventHandler(object source, TokenExpiredEventArgs args);

JWTAuthenticationManager.cs

public class JWTAuthenticationManager : IJWTAuthenticationManager
{
    private readonly string _tokenKey;
    public event TokenExpiredEventHandler TokenExpired;

    //some code removed for brevity
    public void ExpireToken(string tokenId)
    {
        OnTokenExpired(tokenId); //notify all subscribers
    }
    protected virtual void OnTokenExpired(string token) {
        TokenExpired?.Invoke(this, new TokenExpiredEventArgs(token));
    }
}

public class TokenExpiredEventArgs : EventArgs
{
    public string token;

    public TokenExpiredEventArgs(string tokenId)
    {
        token = tokenId;
    }
}

Program.cs

public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();

        var jwtMgr = host.Services.GetRequiredService<IJWTAuthenticationManager>();
        var cacheMgr = host.Services.GetRequiredService<ICacheManager>();
        jwtMgr.TokenExpired += cacheMgr.OnTokenExpired;

        host.Run();
    }

Body:
Why not resolve services from context? Simply change your ExpireToken method to take an IServiceProvider:

public void ExpireToken(IServiceProvider services, string tokenId)
{
    var jwtManager = services.GetService<IJWTAuthenticationManager>();
    jwtManager.ExpireToken(tokenId);
}

And then pass context.HttpContext.RequestServices:

ExpireToken(context.HttpContext.RequestServices, token);


问:
Scan this from a text file into 2 arrays using C
Im having trouble parsing someething like this into an array.

So my text file test.txt has this line:
(1231212A, 1231212B)    (1231212C, 321128D)

im trying to scan this into an array but it needs to be divided up into parts

part1 of type int should be : 123

part2 : 12

part3 : 12

part4 (char): A

and I need to do this 4 times within the line

Here is the code i have but it is not working properly

```<code>{
int nums[1][12];
char chars[1][4];
FILE *file;

file = fopen("test.txt", "r");
if (file != NULL){

fscanf(file , "%*s%3d %2d %2d %s %*s %2d %2d %2d %s%*s        %*s%3d %2d %2d %s%*s %2d %2d %2d %s%*s"
, &nums[0][0],&nums[0][1],&nums[0][2],&chars[0][0],&nums[0][3],&nums[0][4],&nums[0][5],&chars[0]
[1],&nums[0][6],&nums[0][7],&nums[0][8],&chars[0][2],&nums[0][9],&chars[0][10],&nums[0][11],&chars[0]
[3]);
}
</code>```

when I print these arrays they do not print the right numbers and characters.
I need help with the fscanf part
Thank You

答:
As @chux provided in his answer, the key is properly matching the format string with the data to be parsed, and then critically validating the return against the number of conversions anticipated. The primary errors in  your format string are your unnecessary inclusion of %*s (to try and skip "(") and %s %*s (to try and skip the comma) and %s%*s %*s (to try and skip ") " in several locations which has the effect of reading the reading and discarding the entire first number, e.g. "(1231212A," as a string, beginning the read of values in the second group of numbers and so on.

A closer match is as shown in @chux's answer or simply:

```<code>"(%3d%2d%2d%c, %3d%2d%2d%c) (%3d%2d%2d%c, %3d%2d%2d%c"
</code>```

(that differs only in not providing for additional whitespace and doesn't read the number of characters consumed -- also note the closing ")" isn't necessary in the format-string as your read of the final character, e.g. 'D' ends the conversion)

While you are using a 2D array of 1-row, the following simplified example uses a 1D array for chars and nums, and could be written as follows to read with fgets() passing the buffer to sscanf() validating the return and either outputting the collected values or displaying an error if parsing fails:

```<code>#include <stdio.h>

#define MAXC 1024   /* if you need a constant, #define one (or more) */

int main (int argc, char **argv) {

    char buf[MAXC], chars[4];
    int nums[12];
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    while (fgets (buf, MAXC, fp)) { /* read line into buf with fgets() */
        /* parse with sscanf -- validate 16 conversions take place */
        if (sscanf (buf, "(%3d%2d%2d%c, %3d%2d%2d%c) (%3d%2d%2d%c, %3d%2d%2d%c",
            &nums[0], &nums[1], &nums[2], &chars[0],
            &nums[3], &nums[4], &nums[5], &chars[1],
            &nums[6], &nums[7], &nums[8], &chars[2],
            &nums[9], &nums[10], &nums[11], &chars[3]) == 16) {
            /* output result */
            printf ("%d %d %2d %c\n%d %d %2d %c\n%d %d %2d %c\n%d %d %2d %c\n",
                    nums[0], nums[1], nums[2], chars[0],
                    nums[3], nums[4], nums[5], chars[1],
                    nums[6], nums[7], nums[8], chars[2],
                    nums[9], nums[10], nums[11], chars[3]);
        }   /* or handle error */
        else
            fprintf (stderr, "error parsing data from: %s\n", buf);
    }

    if (fp != stdin)   /* close file if not stdin */
        fclose (fp);
}
</code>```

Example Input File

```<code>$ cat dat/splitintoarr.txt
(1231212A, 1231212B) (1231212C, 321128D)
</code>```

Example Use/Output

```<code>$ ./bin/splitintoarr <dat/splitintoarr.txt
123 12 12 A
123 12 12 B
123 12 12 C
321 12  8 D
</code>```

(the output of the final number has been output using the field-width modifier to ensure the columns remain aligned for your data)

Look things over in all answers and let us know if you have further questions.

Body:
Im having trouble parsing someething like this into an array.

So my text file test.txt has this line:
(1231212A, 1231212B)    (1231212C, 321128D)

im trying to scan this into an array but it needs to be divided up into parts

part1 of type int should be : 123

part2 : 12

part3 : 12

part4 (char): A

and I need to do this 4 times within the line

Here is the code i have but it is not working properly

{
int nums[1][12];
char chars[1][4];
FILE *file;

file = fopen("test.txt", "r");
if (file != NULL){

fscanf(file , "%*s%3d %2d %2d %s %*s %2d %2d %2d %s%*s        %*s%3d %2d %2d %s%*s %2d %2d %2d %s%*s"
, &nums[0][0],&nums[0][1],&nums[0][2],&chars[0][0],&nums[0][3],&nums[0][4],&nums[0][5],&chars[0]
[1],&nums[0][6],&nums[0][7],&nums[0][8],&chars[0][2],&nums[0][9],&chars[0][10],&nums[0][11],&chars[0]
[3]);
}

when I print these arrays they do not print the right numbers and characters.
I need help with the fscanf part
Thank You

Body:
As @chux provided in his answer, the key is properly matching the format string with the data to be parsed, and then critically validating the return against the number of conversions anticipated. The primary errors in  your format string are your unnecessary inclusion of %*s (to try and skip "(") and %s %*s (to try and skip the comma) and %s%*s %*s (to try and skip ") " in several locations which has the effect of reading the reading and discarding the entire first number, e.g. "(1231212A," as a string, beginning the read of values in the second group of numbers and so on.

A closer match is as shown in @chux's answer or simply:

"(%3d%2d%2d%c, %3d%2d%2d%c) (%3d%2d%2d%c, %3d%2d%2d%c"

(that differs only in not providing for additional whitespace and doesn't read the number of characters consumed -- also note the closing ")" isn't necessary in the format-string as your read of the final character, e.g. 'D' ends the conversion)

While you are using a 2D array of 1-row, the following simplified example uses a 1D array for chars and nums, and could be written as follows to read with fgets() passing the buffer to sscanf() validating the return and either outputting the collected values or displaying an error if parsing fails:

#include <stdio.h>

#define MAXC 1024   /* if you need a constant, #define one (or more) */

int main (int argc, char **argv) {

    char buf[MAXC], chars[4];
    int nums[12];
    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    while (fgets (buf, MAXC, fp)) { /* read line into buf with fgets() */
        /* parse with sscanf -- validate 16 conversions take place */
        if (sscanf (buf, "(%3d%2d%2d%c, %3d%2d%2d%c) (%3d%2d%2d%c, %3d%2d%2d%c",
            &nums[0], &nums[1], &nums[2], &chars[0],
            &nums[3], &nums[4], &nums[5], &chars[1],
            &nums[6], &nums[7], &nums[8], &chars[2],
            &nums[9], &nums[10], &nums[11], &chars[3]) == 16) {
            /* output result */
            printf ("%d %d %2d %c\n%d %d %2d %c\n%d %d %2d %c\n%d %d %2d %c\n",
                    nums[0], nums[1], nums[2], chars[0],
                    nums[3], nums[4], nums[5], chars[1],
                    nums[6], nums[7], nums[8], chars[2],
                    nums[9], nums[10], nums[11], chars[3]);
        }   /* or handle error */
        else
            fprintf (stderr, "error parsing data from: %s\n", buf);
    }

    if (fp != stdin)   /* close file if not stdin */
        fclose (fp);
}

Example Input File

$ cat dat/splitintoarr.txt
(1231212A, 1231212B) (1231212C, 321128D)

Example Use/Output

$ ./bin/splitintoarr <dat/splitintoarr.txt
123 12 12 A
123 12 12 B
123 12 12 C
321 12  8 D

(the output of the final number has been output using the field-width modifier to ensure the columns remain aligned for your data)

Look things over in all answers and let us know if you have further questions.


问:
React : Uncaught TypeError: Cannot read property 'i' of undefined
I have a problem with my code:

```<code>class Albs extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      i: 0,
      anh: this.props.hinhanh[this.state.i]
    };
    var hinhanh = ["1.png", "2.png", "3.png"];
    this.state.i = this.state.i.bind(this);
  }
  nextPic(){
    this.setState({i: this.state.i++});
  }
  backPic(){
    this.setState({i: this.state.i--});
  }
  render(){
    return(
      <div>
        <img src={this.state.anh}/>
        <br/>
        <button onClick={nextPic}>Next</button>
        <button onClick={backPic}>Back</button>
      </div>
    )
  }
}

ReactDOM.render(
  <Albs/>,
  document.getElementById('root')
);
</code>```

In console it shows: Uncaught TypeError: Cannot read property 'i' of undefined. Reason please?

答:
You need to bind the class this to your methods nextPic and backPic as you do with this.state.i (I don't see how it's necessary)

Or you could use this syntax

nextPic = () => {
    this.setState({i: this.state.i++});
  }
  backPic = () => {
    this.setState({i: this.state.i--});
  }
```

Body:
I have a problem with my code:

class Albs extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      i: 0,
      anh: this.props.hinhanh[this.state.i]
    };
    var hinhanh = ["1.png", "2.png", "3.png"];
    this.state.i = this.state.i.bind(this);
  }
  nextPic(){
    this.setState({i: this.state.i++});
  }
  backPic(){
    this.setState({i: this.state.i--});
  }
  render(){
    return(

        <button onClick={nextPic}>Next</button>
        <button onClick={backPic}>Back</button>

    )
  }
}

ReactDOM.render(
  <Albs/>,
  document.getElementById('root')
);

In console it shows: Uncaught TypeError: Cannot read property 'i' of undefined. Reason please?


问:
Merging in R without duplicating columns with same names between datasets
I have 2 dataframes

```<code>x <- data.frame(ID=c("A","B","C","D"),y=c(1,2,3,4),animal=c("squid","shark", NA, NA))
</code>```

which looks like

```<code>  ID y animal
1  A 1  squid
2  B 2  shark
3  C 3   <NA>
4  D 4   <NA>
</code>```

and

```<code>y <- data.frame(ID=c("A","B","C","D"),y=c(1,2,3,4),animal=c(NA,NA, "dog", "cat"))
</code>```

which looks like

```<code>  ID y animal
1  A 1   <NA>
2  B 2   <NA>
3  C 3    dog
4  D 4    cat
</code>```

I want to merge these datasets by their ID so that the animal columns complete each other. However, when I try to do this using merge or the joins offered by dplyr I get these results

```<code>#example code
merge(x, y, by = "ID")

#output
  ID y.x animal.x y.y animal.y
1  A   1    squid   1     <NA>
2  B   2    shark   2     <NA>
3  C   3     <NA>   3      dog
4  D   4     <NA>   4      cat
</code>```

What I'd like is for the output to just be

```<code>  ID y animal
1  A 1  squid
2  B 2  shark
3  C 3   dog
4  D 4   cat
</code>```

There are ways to go about combining that with something like a loop that creates a final column where the incomplete data is tossed and only complete data is kept, but I'm curious if there are handy functions out there that can fix this with a one-liner

It seems like people have asked similar questions to this, but most of the posts I found were more interested in just renaming the shared column names between the 2 datasets to avoid the .x and .y results merge produces

答:
```<code>library(dplyr)
x %>%
   left_join(y,by=c("ID","y")) %>%
   mutate(animal = coalesce(animal.x,animal.y))
  ID y animal.x animal.y animal
1  A 1    squid     <NA>  squid
2  B 2    shark     <NA>  shark
3  C 3     <NA>      dog    dog
4  D 4     <NA>      cat    cat

y <- data.frame(ID=c("A","B","C","D"),y=c(1,2,3,4),animal=c(NA,NA, "dog", "cat"),stringsAsFactors = F)

y <- data.frame(ID=c("A","B","C","D"),y=c(1,2,3,4),animal=c(NA,NA, "dog", "cat"),stringsAsFactors = F)
</code>```

Body:
I have 2 dataframes

x <- data.frame(ID=c("A","B","C","D"),y=c(1,2,3,4),animal=c("squid","shark", NA, NA))

which looks like

  ID y animal
1  A 1  squid
2  B 2  shark
3  C 3   <NA>
4  D 4   <NA>

and

y <- data.frame(ID=c("A","B","C","D"),y=c(1,2,3,4),animal=c(NA,NA, "dog", "cat"))

which looks like

  ID y animal
1  A 1   <NA>
2  B 2   <NA>
3  C 3    dog
4  D 4    cat

I want to merge these datasets by their ID so that the animal columns complete each other. However, when I try to do this using merge or the joins offered by dplyr I get these results

#example code
merge(x, y, by = "ID")

#output
  ID y.x animal.x y.y animal.y
1  A   1    squid   1     <NA>
2  B   2    shark   2     <NA>
3  C   3     <NA>   3      dog
4  D   4     <NA>   4      cat

What I'd like is for the output to just be

  ID y animal
1  A 1  squid
2  B 2  shark
3  C 3   dog
4  D 4   cat

There are ways to go about combining that with something like a loop that creates a final column where the incomplete data is tossed and only complete data is kept, but I'm curious if there are handy functions out there that can fix this with a one-liner

It seems like people have asked similar questions to this, but most of the posts I found were more interested in just renaming the shared column names between the 2 datasets to avoid the .x and .y results merge produces


问:
Firebase analytics android apps
When implementing fire base analytics in android apps do i need to add any codes in the app side or is it enough to enable it in firebase console only. Does it same in ios</p>

答:
You should add Firebase SDK to your app. see this link:
Firebase android setup page

For ios you should add Firebase configuration file to your project, then add Firebase SDK to the app and then you should initialize it. detailed instructions can be found here:
Firebase ios setup page

Title: Firebase analytics android apps


问:
Error: A JNI error has occurred, please check your installation and try again Exception in thread "main"
I'm creating a java web-scraping project. I want to package the application using maven but struggling with this error.

My pom.xml file:

```<code><project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>AppName</groupId>
    <artifactId>AppName</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SwellMapApp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.12.2</version>
        </dependency>
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.30.1</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <!-- Build an executable JAR -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>Hello/App</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

</code>```

I am trying to run my .jar after mvn package but i get the following error:

```<code>Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/json/simple/parser/ParseException
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
        at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
        at java.lang.Class.getMethod0(Class.java:3018)
        at java.lang.Class.getMethod(Class.java:1784)
        at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
        at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: org.json.simple.parser.ParseException
        at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:419)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:352)
        ... 7 more
</code>```

Can any maven experts give me some tips on how to package a jar successfully and how to resolve this error? :)

答:
use maven-dependency-plugin to copy the depenedencies to libs directory as metioned below. Insert this plugin before maven jar plugin under the build section</p>

```<code><build>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>2.1</version>
          <executions>
            <execution>
              <id>copy-dependencies</id>
              <phase>package</phase>
              <goals>
                <goal>copy-dependencies</goal>
              </goals>
              <configuration>
                <outputDirectory>${project.build.directory}/lib</outputDirectory>
                <overWriteReleases>false</overWriteReleases>
                <overWriteSnapshots>false</overWriteSnapshots>
                <overWriteIfNewer>true</overWriteIfNewer>
              </configuration>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </build>
</code>```

Body:
I'm creating a java web-scraping project. I want to package the application using maven but struggling with this error.

My pom.xml file:

<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>AppName</groupId>
    <artifactId>AppName</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SwellMapApp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.12.2</version>
        </dependency>
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.30.1</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>

                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>Hello/App</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

I am trying to run my .jar after mvn package but i get the following error:

Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/json/simple/parser/ParseException
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
        at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
        at java.lang.Class.getMethod0(Class.java:3018)
        at java.lang.Class.getMethod(Class.java:1784)
        at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
        at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: org.json.simple.parser.ParseException
        at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:419)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:352)
        ... 7 more

Can any maven experts give me some tips on how to package a jar successfully and how to resolve this error? :)

Body:
use maven-dependency-plugin to copy the depenedencies to libs directory as metioned below. Insert this plugin before maven jar plugin under the build section

<build>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>2.1</version>
          <executions>
            <execution>
              <id>copy-dependencies</id>
              <phase>package</phase>
              <goals>
                <goal>copy-dependencies</goal>
              </goals>
              <configuration>
                <outputDirectory>${project.build.directory}/lib</outputDirectory>
                <overWriteReleases>false</overWriteReleases>
                <overWriteSnapshots>false</overWriteSnapshots>
                <overWriteIfNewer>true</overWriteIfNewer>
              </configuration>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </build>


问:
Mongodb : Check if a point is inside a stored polygon
I'm new to the mongodb geolocation features.

I stored some polygons that represent the country borders in a database along with the country name.
Now what i would like to do is checking which country a point is in.
For example if i give my own geolocation i would like to get the country where i am.

Is there a way to do it with mongodb? Maybe with geoWithin?

Thank you

答:
Your scenario seems to be identical with the MongoDB Geo-spatial
  Tutorial example which uses $geoIntersects instead of
  $geoWithin.

As in the example shown in the MongoDB documentation you can use $geoIntersects Geo-spatial query feature of MongoDB assuming that you have a polygon representing countries stored in your database and a point is your current location, you can use following query.

```<code>db.neighborhoods.findOne({
     geometry: {
        $geoIntersects: {
             $geometry: {
                type: "Point",
                coordinates: [ -73.93414657, 40.82302903 ]
            }
        }
    }
})
</code>```

where, neighborhood is your collection which stores in your case country's polygon. geometry in second line of query is your actual polygon stored in DB (which is Geo-Json format). And "Point" inside $geometry is your current location that you want to fine country of.

ContentLicense: CC BY-SA 3.0

Body:
Your scenario seems to be identical with the MongoDB Geo-spatial
  Tutorial example which uses $geoIntersects instead of
  $geoWithin.

As in the example shown in the MongoDB documentation you can use $geoIntersects Geo-spatial query feature of MongoDB assuming that you have a polygon representing countries stored in your database and a point is your current location, you can use following query.

db.neighborhoods.findOne({
     geometry: {
        $geoIntersects: {
             $geometry: {
                type: "Point",
                coordinates: [ -73.93414657, 40.82302903 ]
            }
        }
    }
})

where, neighborhood is your collection which stores in your case country's polygon. geometry in second line of query is your actual polygon stored in DB (which is Geo-Json format). And "Point" inside $geometry is your current location that you want to fine country of.


问:
Setting state along with AsyncStorage in useEffect hook causes infinite loop?
I'm new to hooks and recently started using hooks in my React Native projects.

I'm building a simple todo app using the AsyncStorage. First I initialize initial data and setData state using useState hook:

```<code>const [data, setData] = useState([]);
</code>```

There are two textInput and submit button that I use to save data to AsyncStorage. Here is the saveData function:

```<code>const saveData = async () => {
  const arrData = [{ name: 'vikrant', phone: 123456 }]; // [{ name, phone}] from the textInput

  const storedData = await AsyncStorage.getItem('user');
  const storedDataParsed = JSON.parse(storedData);

  let newData = [];

  if (storedData === null) {
    // save
    await AsyncStorage.setItem('user', JSON.stringify(arrData));
  } else {
    newData = [...storedDataParsed, user];
    await AsyncStorage.setItem('user', JSON.stringify(newData));
  }
  setName('');
  setPhone('');
  Keyboard.dismiss();
};
</code>```

Now, I'm using useEffect to get data from the AsyncStorage and setting it to the data state. I'm using data to render the text in the screen.

```<code>useEffect(() => {
  retrieveData();
}, [data]);

const retrieveData = async () => {
  try {
    const valueString = await AsyncStorage.getItem('user');
    const value = JSON.parse(valueString);
    setData(value);
  } catch (error) {
    console.log(error);
  }
};
</code>```

I'm using [data] in useEffect since I want to re-render my component each time  data changes i.e. each time I save data in AsyncStorage. But this is causing infinite loop as setData causes useEffect to run infinitely.

If I remove data from the [] it doesn't loop but my data in render is one step behind. So whenever I save data it doesn't show the current data but the previous one.

Any explanation of what I am doing wrong here and how can i fix this?

Thanks.

答:
Just add a conditional flag, retrieve to wrap async storage, retrieveData(), calls.

Also in the context of "saving data" I would probably just separate async storage-ish logic with state logic. Current saveData is polluted with both state and async storage logic.

Something like:

```<code>const [retrieve, setRetrieve] = useState(false);

// Pure AsyncStorage context
const saveData = async () => {
  ...
  if (storedData === null) {
    await AsyncStorage.setItem('user', JSON.stringify(arrData));
  } else {
    newData = [...storedDataParsed, user];
    await AsyncStorage.setItem('user', JSON.stringify(newData));
  }
  // XXX: Removed state logic, call it somewhere else.
};

const someHandler = async () => {
  await saveData();
  setRetrieve(true); // to signal effect to call retrieveData()
}
</code>```

Then the goal of the effect is just to run retrieveData() once saving is done.

```<code>const [data, setData] = useState([]);

useEffect(() => {
  const retrieveData = async () => {
    try {
      const valueString = await AsyncStorage.getItem('user');
      const value = JSON.parse(valueString);
      // Other set states
      setData(value);
    } catch (error) {
      console.log(error);
    }
  };
  // Retrieve if has new data
  if (retrieve)
    retrieveData();
    setRetrieve(false);
  }
}, [retrieve]);
</code>```

Body:
I'm new to hooks and recently started using hooks in my React Native projects.

I'm building a simple todo app using the AsyncStorage. First I initialize initial data and setData state using useState hook:

const [data, setData] = useState([]);

There are two textInput and submit button that I use to save data to AsyncStorage. Here is the saveData function:

const saveData = async () => {
  const arrData = [{ name: 'vikrant', phone: 123456 }]; // [{ name, phone}] from the textInput

  const storedData = await AsyncStorage.getItem('user');
  const storedDataParsed = JSON.parse(storedData);

  let newData = [];

  if (storedData === null) {
    // save
    await AsyncStorage.setItem('user', JSON.stringify(arrData));
  } else {
    newData = [...storedDataParsed, user];
    await AsyncStorage.setItem('user', JSON.stringify(newData));
  }
  setName('');
  setPhone('');
  Keyboard.dismiss();
};

Now, I'm using useEffect to get data from the AsyncStorage and setting it to the data state. I'm using data to render the text in the screen.

useEffect(() => {
  retrieveData();
}, [data]);

const retrieveData = async () => {
  try {
    const valueString = await AsyncStorage.getItem('user');
    const value = JSON.parse(valueString);
    setData(value);
  } catch (error) {
    console.log(error);
  }
};

I'm using [data] in useEffect since I want to re-render my component each time  data changes i.e. each time I save data in AsyncStorage. But this is causing infinite loop as setData causes useEffect to run infinitely.

If I remove data from the [] it doesn't loop but my data in render is one step behind. So whenever I save data it doesn't show the current data but the previous one.

Any explanation of what I am doing wrong here and how can i fix this?

Thanks.

Body:
Just add a conditional flag, retrieve to wrap async storage, retrieveData(), calls.

Also in the context of "saving data" I would probably just separate async storage-ish logic with state logic. Current saveData is polluted with both state and async storage logic.

Something like:

const [retrieve, setRetrieve] = useState(false);

// Pure AsyncStorage context
const saveData = async () => {
  ...
  if (storedData === null) {
    await AsyncStorage.setItem('user', JSON.stringify(arrData));
  } else {
    newData = [...storedDataParsed, user];
    await AsyncStorage.setItem('user', JSON.stringify(newData));
  }
  // XXX: Removed state logic, call it somewhere else.
};

const someHandler = async () => {
  await saveData();
  setRetrieve(true); // to signal effect to call retrieveData()
}

Then the goal of the effect is just to run retrieveData() once saving is done.

const [data, setData] = useState([]);

useEffect(() => {
  const retrieveData = async () => {
    try {
      const valueString = await AsyncStorage.getItem('user');
      const value = JSON.parse(valueString);
      // Other set states
      setData(value);
    } catch (error) {
      console.log(error);
    }
  };
  // Retrieve if has new data
  if (retrieve)
    retrieveData();
    setRetrieve(false);
  }
}, [retrieve]);


问:
How to subset the data frame based on selected variable with limited column?
i would like to subset limited column and selected variable as i have multiple column in my data frame.

my sample data:

df <- data.frame('ID'=c('A','B','C'),'YEAR'=c('2020','2020','2020'),'MONTH'=c('1','1','1'),'DAY'=c('16','16','16'),'HOUR'=c('15','15','15'),'VALUE1'=c(1,2,3))

i would like to subset ID'='C' and column name 'VALUE1'
Expected output:-

```<code>  ID VALUE1
1  C      3
</code>```

Appreciate any help...!

What i have tried so far is.

```<code>df1 <- subset(df,df$ID=='C')
df2 <- subset(df1,select=c('ID','VALUE1')

</code>```

Is there any efficient way to do that as creating multiple data frame when we have multiple is not good.

答:
you can use dplyr chaining function too,</p>

```<code>df %>% select(ID,VALUE1) %>% filter(ID=="C")
</code>```

Body:
i would like to subset limited column and selected variable as i have multiple column in my data frame.

my sample data:

df <- data.frame('ID'=c('A','B','C'),'YEAR'=c('2020','2020','2020'),'MONTH'=c('1','1','1'),'DAY'=c('16','16','16'),'HOUR'=c('15','15','15'),'VALUE1'=c(1,2,3))

i would like to subset ID'='C' and column name 'VALUE1'
Expected output:-

  ID VALUE1
1  C      3

Appreciate any help...!

What i have tried so far is.

df1 <- subset(df,df$ID=='C')
df2 <- subset(df1,select=c('ID','VALUE1')

Is there any efficient way to do that as creating multiple data frame when we have multiple is not good.

Body:
you can use dplyr chaining function too,

df %>% select(ID,VALUE1) %>% filter(ID=="C")


问:
How do I make a string bold in a console window?
So I'm trying to find a simple code that makes my code get printed in bold. When I searched the internet all of them were so complicated that it wasn't even worth it. Is there any easier way to make a string or just a Console.WriteLine(" "); bold? </p>

```<code>Console.Write("Type in the number of people to create: ");
int time = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nGenerating " + time + " people please stand by...");
System.Threading.Thread.Sleep(3000);
Console.Clear();
</code>```

答:
Fonts and Styles are not available on a per-word basis. To get bold, italics, underline or size, you would have to change all text in the Console.

But you can set the Console.ForegroundColor, Console.BackgroundColor

Body:
So I'm trying to find a simple code that makes my code get printed in bold. When I searched the internet all of them were so complicated that it wasn't even worth it. Is there any easier way to make a string or just a Console.WriteLine(" "); bold?

Console.Write("Type in the number of people to create: ");
int time = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nGenerating " + time + " people please stand by...");
System.Threading.Thread.Sleep(3000);
Console.Clear();


问:
Accessing Android/iPhone volume buttons with HTML5 app
Does anyone know if there is a way to access to the volume button events in an HTML5 application run on the phone's browser?</p>

答:
I came to the conclusion that it's impossible to have access to the volume buttons with HTML5 on the phone's browser.

One's has to use the native APIs (either Android or iOS).