问:
Redirect to /en for one specific url in IIS
I have 2 urls for my website

1: domain1.com
2: domain2.com

I want to redirect "domain2.com" to "domain2.com/en" and if domain1.com is requested, I don't want it to be redirected.

been googling for hours, but cannot find a workaround.

here's what I have written so far, and returns:
domain2.com redirected you too many times.

```<code><rule name="NAME" patternSyntax="Wildcard" stopProcessing="true">
            <match url="*" />
            <conditions logicalGrouping="MatchAny">
                        <add input="{HTTP_HOST}" pattern="*domain2.com*" />
            </conditions>
            <action type="Redirect" appendQueryString="false" url="http://domain2.com/en/{C:2}" redirectType="Permanent" />
        </rule>
</code>```

答:
Here's what I did to solve the problem:</p>

```<code>         <rewrite>
            <rules>
                <clear />
                <rule name="redirect to en" patternSyntax="ECMAScript" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                        <add input="{URL}" pattern="(.*)/en/(.*)" negate="true" />
                        <add input="{URL}" pattern="(.*)/Scripts/(.*)" negate="true" />
                        <add input="{URL}" pattern="(.*)/Content/(.*)" negate="true" />
                        <add input="{URL}" pattern="(.*)/fonts/(.*)" negate="true" />
                        <add input="{HTTP_HOST}" pattern="(.*)domain1.com(.*)" negate="true" />
                    </conditions>
                    <action type="Redirect" url="/en/{R:1}" appendQueryString="false" />
                </rule>
            </rules>
        </rewrite>
</code>```

Body:
I have 2 urls for my website

1: domain1.com
2: domain2.com

I want to redirect "domain2.com" to "domain2.com/en" and if domain1.com is requested, I don't want it to be redirected.

been googling for hours, but cannot find a workaround.

here's what I have written so far, and returns:
domain2.com redirected you too many times.

<rule name="NAME" patternSyntax="Wildcard" stopProcessing="true">
            <match url="*" />
            <conditions logicalGrouping="MatchAny">
                        <add input="{HTTP_HOST}" pattern="*domain2.com*" />
            </conditions>
            <action type="Redirect" appendQueryString="false" url="http://domain2.com/en/{C:2}" redirectType="Permanent" />
        </rule>

Body:
Here's what I did to solve the problem:

         <rewrite>
            <rules>
                <clear />
                <rule name="redirect to en" patternSyntax="ECMAScript" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                        <add input="{URL}" pattern="(.*)/en/(.*)" negate="true" />
                        <add input="{URL}" pattern="(.*)/Scripts/(.*)" negate="true" />
                        <add input="{URL}" pattern="(.*)/Content/(.*)" negate="true" />
                        <add input="{URL}" pattern="(.*)/fonts/(.*)" negate="true" />
                        <add input="{HTTP_HOST}" pattern="(.*)domain1.com(.*)" negate="true" />
                    </conditions>
                    <action type="Redirect" url="/en/{R:1}" appendQueryString="false" />
                </rule>
            </rules>
        </rewrite>


来源: stackexchange

问:
TYPO3 - Howto restrict all pages by frontend user login but the login page itself
I would like to restrict all pages of a website by the frontend user login. Therefor I would like to add "Show at any login" in the page settings of the root page and tick the checkbox "Extend to Subpages". So all pages are only accessible, if the user is logged in.

But:
How can I show the login form now? Are there beste practices?

First idea for the page tree:

```<code>- root page (with login form)
  - Home page <-- Password protection starts here and cascades down to all subpages
    - Subpage
    - more pages...
</code>```

But how can I redirect to the homepage, if the user is already logged in?

答:
you might put the pages side by side:

```<code>- root (login) (visible only, without login)
- homepage (visible only with login)
  - subpage1
  - subpage2
  :
</code>```

but you probably need another page on top

```<code>- top (Shortcut: redirects to first subpage)
  - root (login) (visible only without login)
  - homepage (visible only with login)
    - subpage1
    - subpage2
    :
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to restrict all pages of a website by the frontend user login. Therefor I would like to add "Show at any login" in the page settings of the root page and tick the checkbox "Extend to Subpages". So all pages are only accessible, if the user is logged in.

But:
How can I show the login form now? Are there beste practices?

First idea for the page tree:

- root page (with login form)
  - Home page <-- Password protection starts here and cascades down to all subpages
    - Subpage
    - more pages...

But how can I redirect to the homepage, if the user is already logged in?

Body:
you might put the pages side by side:

- root (login) (visible only, without login)
- homepage (visible only with login)
  - subpage1
  - subpage2
  :

but you probably need another page on top

- top (Shortcut: redirects to first subpage)
  - root (login) (visible only without login)
  - homepage (visible only with login)
    - subpage1
    - subpage2
    :


问:
MySQL: Updating data from one column to another using two matching columns
I'm trying to update columns based on two matching columns: firms.id = investors.firm and investors.firm_role = "ceo", but the server keeps rejecting my syntax. I have tried inner joins, without inner joins, it's all really too complex for me, so I'm not sure what to do next.

```<code>UPDATE firms
JOIN investors USING (firms.id = investors.firm)
SET firms.ceo = investors.name
WHERE investors.firm_role = "ceo"
</code>```

Error:

SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '.id = investors.firm) SET firms.ceo = investors.name WHERE investors.firm_role =' at line 1

答:
Try this Syntax

update patients set column_name="value" where (condition)

for example im using c# and it goes

```<code>update patients set " + dgv.Columns[c].HeaderText + "='" + dgv.Rows[dgv.CurrentCell.RowIndex].Cells[c].Value.ToString() + "' where idno='" + dgv.Rows[dgv.CurrentCell.RowIndex].Cells[0].Value.ToString() + "'"
</code>```

Body:
I'm trying to update columns based on two matching columns: firms.id = investors.firm and investors.firm_role = "ceo", but the server keeps rejecting my syntax. I have tried inner joins, without inner joins, it's all really too complex for me, so I'm not sure what to do next.

UPDATE firms
JOIN investors USING (firms.id = investors.firm)
SET firms.ceo = investors.name
WHERE investors.firm_role = "ceo"

Error:

SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '.id = investors.firm) SET firms.ceo = investors.name WHERE investors.firm_role =' at line 1

Body:
Try this Syntax

update patients set column_name="value" where (condition)

for example im using c# and it goes

update patients set " + dgv.Columns[c].HeaderText + "='" + dgv.Rows[dgv.CurrentCell.RowIndex].Cells[c].Value.ToString() + "' where idno='" + dgv.Rows[dgv.CurrentCell.RowIndex].Cells[0].Value.ToString() + "'"


问:
Perl - Insert lines after a match is found in a file
I have a file with the following syntax in some_1.xyz

```<code>module some_1 {
INPUT PINS
OUTPUT PINS
}
</code>```

and I want to insert APPLY DELAYS xx and APPLY LOADS ld after line module some_1 {

The following code works fine for just one file i.e., if I replace some_1.xyz to *.xyz then the script doesn't work. I tried introducing sleep(xx) but the code doesn't work for multiple files and I could not figure out why it isn't working. Any pointers is appreciated. Thanks

```<code>@modulename_array = `grep "module " some_1.xyz | cut -f 2 -d ' '`;
@line = `grep "module " some_1.xyz`;

chomp(@line);
chomp(@kfarray);

$i = 0;
foreach (@modulename_array) {
  print "Applying delay and load to $_.xyz $line[$i] \n";

  `perl -ni -le 'print; print "\tAPPLY DELAY xx \n \tAPPLY LOADS  ld\n" if/$line[$i]/' $_.xyz`;
  $i++;
  #sleep(3);

}
</code>```

答:
```<code>$text='bla bla mytext bla bla';
$find='.*mytext.*';
$repl='replacement';

$text=~ s/($find)/$1$repl/g;
</code>```

$1 is basically your match and you can use it when you make the replacement, either before or after your $repl string. )))

EASY

ContentLicense: CC BY-SA 2.5

Body:
I have a file with the following syntax in some_1.xyz

module some_1 {
INPUT PINS
OUTPUT PINS
}

and I want to insert APPLY DELAYS xx and APPLY LOADS ld after line module some_1 {

The following code works fine for just one file i.e., if I replace some_1.xyz to *.xyz then the script doesn't work. I tried introducing sleep(xx) but the code doesn't work for multiple files and I could not figure out why it isn't working. Any pointers is appreciated. Thanks

@modulename_array = `grep "module " some_1.xyz | cut -f 2 -d ' '`;
@line = `grep "module " some_1.xyz`;

chomp(@line);
chomp(@kfarray);

$i = 0;
foreach (@modulename_array) {
  print "Applying delay and load to $_.xyz $line[$i] \n";

  `perl -ni -le 'print; print "\tAPPLY DELAY xx \n \tAPPLY LOADS  ld\n" if/$line[$i]/' $_.xyz`;
  $i++;
  #sleep(3);

}

Body:
$text='bla bla mytext bla bla';
$find='.*mytext.*';
$repl='replacement';

$text=~ s/($find)/$1$repl/g;

$1 is basically your match and you can use it when you make the replacement, either before or after your $repl string. )))

EASY


问:
How to reset a RXJS scan operator based on another Observable
I have a component which triggers an onScrollEnd event when the last item in a virtual list is rendered. This event will do a new API request to fetch the next page and merge them with the previous results using the scan operator.

This component also has a search field which triggers an onSearch event.

How do I clear the previous accumulated results from the scan operator when a search event is triggered? Or do I need to refactor my logic here?

```<code>const loading$ = new BehaviorSubject(false);
const offset$ = new BehaviorSubject(0);
const search$ = new BehaviorSubject(null);

const options$: Observable<any[]> = merge(offset$, search$).pipe(
  // 1. Start the loading indicator.
  tap(() => loading$.next(true)),
  // 2. Fetch new items based on the offset.
  switchMap(([offset, searchterm]) => userService.getUsers(offset, searchterm)),
  // 3. Stop the loading indicator.
  tap(() => loading$.next(false)),
  // 4. Complete the Observable when there is no 'next' link.
  takeWhile((response) => response.links.next),
  // 5. Map the response.
  map(({ data }) =>
    data.map((user) => ({
      label: user.name,
      value: user.id
    }))
  ),
  // 6. Accumulate the new options with the previous options.
  scan((acc, curr) => {
    // TODO: Dont merge on search$.next
    return [...acc, ...curr]);
  }
);

// Fetch next page
onScrollEnd: (offset: number) => offset$.next(offset);
// Fetch search results
onSearch: (term) => {
  search$.next(term);
};
</code>```

答:
I think you could achieve what you want just by restructuring your chain (I'm omitting tap calls that trigger loading for simplicity):

```<code>search$.pipe(
  switchMap(searchterm =>
    concat(
      userService.getUsers(0, searchterm),
      offset$.pipe(concatMap(offset => userService.getUsers(offset, searchterm)))),
    ).pipe(
      map(({ data }) => data.map((user) => ({
        label: user.name,
        value: user.id
      }))),
      scan((acc, curr) => [...acc, ...curr], []),
    ),
  ),
);
</code>```

Every emission from search$ will create a new inner Observable with its own scan that will start with an empty accumulator.

Body:
I have a component which triggers an onScrollEnd event when the last item in a virtual list is rendered. This event will do a new API request to fetch the next page and merge them with the previous results using the scan operator.

This component also has a search field which triggers an onSearch event.

How do I clear the previous accumulated results from the scan operator when a search event is triggered? Or do I need to refactor my logic here?

const loading$ = new BehaviorSubject(false);
const offset$ = new BehaviorSubject(0);
const search$ = new BehaviorSubject(null);

const options$: Observable<any[]> = merge(offset$, search$).pipe(
  // 1. Start the loading indicator.
  tap(() => loading$.next(true)),
  // 2. Fetch new items based on the offset.
  switchMap(([offset, searchterm]) => userService.getUsers(offset, searchterm)),
  // 3. Stop the loading indicator.
  tap(() => loading$.next(false)),
  // 4. Complete the Observable when there is no 'next' link.
  takeWhile((response) => response.links.next),
  // 5. Map the response.
  map(({ data }) =>
    data.map((user) => ({
      label: user.name,
      value: user.id
    }))
  ),
  // 6. Accumulate the new options with the previous options.
  scan((acc, curr) => {
    // TODO: Dont merge on search$.next
    return [...acc, ...curr]);
  }
);

// Fetch next page
onScrollEnd: (offset: number) => offset$.next(offset);
// Fetch search results
onSearch: (term) => {
  search$.next(term);
};

Body:
I think you could achieve what you want just by restructuring your chain (I'm omitting tap calls that trigger loading for simplicity):

search$.pipe(
  switchMap(searchterm =>
    concat(
      userService.getUsers(0, searchterm),
      offset$.pipe(concatMap(offset => userService.getUsers(offset, searchterm)))),
    ).pipe(
      map(({ data }) => data.map((user) => ({
        label: user.name,
        value: user.id
      }))),
      scan((acc, curr) => [...acc, ...curr], []),
    ),
  ),
);

Every emission from search$ will create a new inner Observable with its own scan that will start with an empty accumulator.


问:
Mainframe commands for DS - move columns in ISPF Edit
how can we move the data in middle of PS file to left side in Mainframe? any shortcut command for this?

I have a Data set with data at column 13 and it has to be moved to column 11, Any short key to move it.

Want to align rest of the rows in DS as 1st row

```<code> BROWSE    OSMDEV.ITALY3.DATA
 Command ===>
----+----1----+----2----+----3----+----4----+-

758         200510  4323T
758           2005  10  4323N
758           2005  10  51149
758           2005  10  51154
758           2005  10  6758E
758           2005  13  34437
758           2005  13  34441
758           2005  13  53445
</code>```

答:
Use the ISPF 'BNDS' line command command and set the bounds (via the '<' and '>' characters) to column 11 and column 20:

(Bounds are used to constrain scrolling, shift line commands ( ">", "<", ")", "(" ), text line commands ("TS", "TF", "TE") and FIND , CHANGE , EXCLUDE and SORT commands.)

Now use the '(' (Shift left) command to shift the data 2 characters to the left.

(We will use the '((' form of the '(' command to indicate that we are applying the '(' command to a block of rows and the default shift value is 2, which is what you want, so we don't have to specify a value).

The previously set bounds will ensure that only data in columns 11 through to 20 will be moved:

Body:
how can we move the data in middle of PS file to left side in Mainframe? any shortcut command for this?

I have a Data set with data at column 13 and it has to be moved to column 11, Any short key to move it.

Want to align rest of the rows in DS as 1st row

 BROWSE    OSMDEV.ITALY3.DATA
 Command ===>
----+----1----+----2----+----3----+----4----+-

758         200510  4323T
758           2005  10  4323N
758           2005  10  51149
758           2005  10  51154
758           2005  10  6758E
758           2005  13  34437
758           2005  13  34441
758           2005  13  53445


问:
python-pandas and databases like mysql
The documentation for Pandas has numerous examples of best practices for working with data stored in various formats.

However, I am unable to find any good examples for working with databases like MySQL for example.

Can anyone point me to links or give some code snippets of how to convert query results using mysql-python to data frames in Pandas efficiently ?

答:
This helped for me for connecting to AWS MYSQL(RDS) from python 3.x based lambda function and loading into a pandas DataFrame

```<code>import json
import boto3
import pymysql
import pandas as pd
user = 'username'
password = 'XXXXXXX'
client = boto3.client('rds')
def lambda_handler(event, context):
    conn = pymysql.connect(host='xxx.xxxxus-west-2.rds.amazonaws.com', port=3306, user=user, passwd=password, db='database name', connect_timeout=5)
    df= pd.read_sql('select * from TableName limit 10',con=conn)
    print(df)
    # TODO implement
    #return {
    #    'statusCode': 200,
    #    'df': df
    #}
</code>```

Title: python-pandas and databases like mysql

Body:
This helped for me for connecting to AWS MYSQL(RDS) from python 3.x based lambda function and loading into a pandas DataFrame

import json
import boto3
import pymysql
import pandas as pd
user = 'username'
password = 'XXXXXXX'
client = boto3.client('rds')
def lambda_handler(event, context):
    conn = pymysql.connect(host='xxx.xxxxus-west-2.rds.amazonaws.com', port=3306, user=user, passwd=password, db='database name', connect_timeout=5)
    df= pd.read_sql('select * from TableName limit 10',con=conn)
    print(df)
    # TODO implement
    #return {
    #    'statusCode': 200,
    #    'df': df
    #}


问:
When to register a method that will call Form.Invoke to an event?
I get the following exception in a Windows Form application

System.InvalidOperationException: Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

The method where the exception occurs calls this.Invoke (System.Windows.Forms.Form.Invoke). This method is registered to the event of another class in the constructor, which seems to lead to a race condition and this exception.

```<code>public Form1()
{
    InitializeComponent();
    SomeOtherClass.Instance.MyEvent += new SomeDelegate(MyMethod);
}

private void MyMethod()
{
    this.Invoke((MethodInvoker)delegate
    {
        // ... some code ...
    }
}
</code>```

At which stage of the form lifecycle is the Handle created? In which event of the form would it be safe to register the method to the foreign event?

答: I think if you register the method in OnShow event you should be safe.</p>

ContentLicense: CC BY-SA 3.0

Body:
I get the following exception in a Windows Form application

System.InvalidOperationException: Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

The method where the exception occurs calls this.Invoke (System.Windows.Forms.Form.Invoke). This method is registered to the event of another class in the constructor, which seems to lead to a race condition and this exception.

public Form1()
{
    InitializeComponent();
    SomeOtherClass.Instance.MyEvent += new SomeDelegate(MyMethod);
}

private void MyMethod()
{
    this.Invoke((MethodInvoker)delegate
    {
        // ... some code ...
    }
}

At which stage of the form lifecycle is the Handle created? In which event of the form would it be safe to register the method to the foreign event?


问:
How to remove any unicode repeating letter?
In english, sometimes you have repeating letter like this :
hello my hero hhhhhhhhhhh that's for h, but I want to remove all kinds of letters repeating like this 2 or more times and replace them with a space in unicode letter. I have arabic here. I only have one letter I can remove, this is my code:

```<code>#remove laughing
def remove_laughs(self, text):
    text=re.sub("ه{2,}", "", text)
    return text
</code>```

答:
try this:

from itertools import groupby

def remove_dups(s):
    replace_with = ' '
    return ''.join([x if sum(1 for i in y)<2 else replace_with for x,y in groupby(s)])
```

Body:
In english, sometimes you have repeating letter like this :
hello my hero hhhhhhhhhhh that's for h, but I want to remove all kinds of letters repeating like this 2 or more times and replace them with a space in unicode letter. I have arabic here. I only have one letter I can remove, this is my code:

#remove laughing
def remove_laughs(self, text):
    text=re.sub("ه{2,}", "", text)
    return text


问:
Displaying only the title in the specific date of the calendar
I use fullcalendar in angularjs as follows to display some event values in the calendar

It displays the values correctly.

```<code><html>
   <head>
   <link rel="stylesheet" href="../fullcalendar-
   4.1.0/packages/core/main.css"></script>
   <link rel="stylesheet" href="../fullcalendar-
   4.1.0/packages/daygrid/main.css"></script>
   <link rel="stylesheet" href="../fullcalendar-
   4.1.0/packages/list/main.css"></script>
   <link rel="stylesheet" href="../fullcalendar-
  4.1.0/packages/timegrid/main.css"></script>
  <script type="text/javascript" src="../fullcalendar-
    4.1.0/packages/core/main.js"></script>
    <script type="text/javascript" src="../fullcalendar-
    4.1.0/packages/daygrid/main.js"></script>
    <script type="text/javascript" src="../fullcalendar-
    4.1.0/packages/timegrid/main.js"></script>
    <script type="text/javascript" src="../fullcalendar-
   4.1.0/packages/list/main.js"></script>
   </head>
   <script>
    $scope.event = {events: [{
            title:'test1',
            start: '2019-05-05 08:00',
            end: '2019-05-10 08:00'
          },
          {
            title:'test2',
            start: '2019-05-05 12:00'
        }]};
    var calendarEl = document.getElementById('calendar');

        var calendar = new FullCalendar.Calendar(calendarEl, {
            events: $scope.event.events,
            plugins: [ 'dayGrid','timeGrid','list' ],
            header: {
                      left: 'prev,next today',
                      center: 'title',
                      right: 'dayGridMonth,dayGridWeek,timeGridDay'
                    }
        });
        calendar.render();
    });
   </script>
   <body ng-app="myApp" ng-controller="myController">
   <div id="calendar" ng-model="eventSources"></div>
   </body>
   </html>
</code>```

Although I have declared a title in the above it always appends the time with a or p accordingly on the specific date. How can I only display the title in the calendar ?

答:
if there is a time specified, it will be displayed as a (for AM) or p (for PM); for all-day events, you can skip entering a time at all... you can check the following code below:

UPDATE: You can use CSS to remove the time also - this way there will be no difference between all-day events and events with a fixed start and/or end times.

angular.module('myApp', [])
  .controller('myController', function($scope) {
    $scope.event = {
      events: [{
          title: 'test1',
          start: '2019-05-05',
          end: '2019-05-10'
        },
        {
          title: 'test2',
          start: '2019-05-05'
        },
        {
          title: 'test3',
          start: '2019-05-13 15:00',
          end: '2019-05-15 11:30'
        },
        {
          title: 'test4',
          start: '2019-05-26 10:00',
          end: '2019-05-28 13:30'
        }
      ]
    };
    var calendarEl = document.getElementById('calendar');

    var calendar = new FullCalendar.Calendar(calendarEl, {
      events: $scope.event.events,
      plugins: ['dayGrid', 'timeGrid', 'list'],
      header: {
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,dayGridWeek,timeGridDay'
      }
    });
    calendar.render();
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  margin: 0;
  padding: 0;
  font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
  font-size: 14px;
}

#calendar {
  max-width: 900px;
  margin: 40px auto;
}

.fc-day-grid-event .fc-time {
  display: none;
}</code>```

<link href='https://fullcalendar.io/assets/demo-to-codepen.css' rel='stylesheet' />
<link href='https://fullcalendar.io/releases/core/4.1.0/main.min.css' rel='stylesheet' />
<link href='https://fullcalendar.io/releases/daygrid/4.1.0/main.min.css' rel='stylesheet' />
<link href='https://fullcalendar.io/releases/timegrid/4.1.0/main.min.css' rel='stylesheet' />

```

Body:
I use fullcalendar in angularjs as follows to display some event values in the calendar

It displays the values correctly.

   <link rel="stylesheet" href="../fullcalendar-
   4.1.0/packages/core/main.css"></script>
   <link rel="stylesheet" href="../fullcalendar-
   4.1.0/packages/daygrid/main.css"></script>
   <link rel="stylesheet" href="../fullcalendar-
   4.1.0/packages/list/main.css"></script>
   <link rel="stylesheet" href="../fullcalendar-
  4.1.0/packages/timegrid/main.css"></script>

Although I have declared a title in the above it always appends the time with a or p accordingly on the specific date. How can I only display the title in the calendar ?

Body:
if there is a time specified, it will be displayed as a (for AM) or p (for PM); for all-day events, you can skip entering a time at all... you can check the following code below:

UPDATE: You can use CSS to remove the time also - this way there will be no difference between all-day events and events with a fixed start and/or end times.

angular.module('myApp', [])
  .controller('myController', function($scope) {
    $scope.event = {
      events: [{
          title: 'test1',
          start: '2019-05-05',
          end: '2019-05-10'
        },
        {
          title: 'test2',
          start: '2019-05-05'
        },
        {
          title: 'test3',
          start: '2019-05-13 15:00',
          end: '2019-05-15 11:30'
        },
        {
          title: 'test4',
          start: '2019-05-26 10:00',
          end: '2019-05-28 13:30'
        }
      ]
    };
    var calendarEl = document.getElementById('calendar');

    var calendar = new FullCalendar.Calendar(calendarEl, {
      events: $scope.event.events,
      plugins: ['dayGrid', 'timeGrid', 'list'],
      header: {
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,dayGridWeek,timeGridDay'
      }
    });
    calendar.render();
  });

html,
body {
  margin: 0;
  padding: 0;
  font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
  font-size: 14px;
}

#calendar {
  max-width: 900px;
  margin: 40px auto;
}

.fc-day-grid-event .fc-time {
  display: none;
}

<link href='https://fullcalendar.io/assets/demo-to-codepen.css' rel='stylesheet' />
<link href='https://fullcalendar.io/releases/core/4.1.0/main.min.css' rel='stylesheet' />
<link href='https://fullcalendar.io/releases/daygrid/4.1.0/main.min.css' rel='stylesheet' />
<link href='https://fullcalendar.io/releases/timegrid/4.1.0/main.min.css' rel='stylesheet' />
<script src='https://fullcalendar.io/assets/demo-to-codepen.js'></script>
<script src='https://fullcalendar.io/releases/core/4.1.0/main.min.js'></script>
<script src='https://fullcalendar.io/releases/interaction/4.1.0/main.min.js'></script>
<script src='https://fullcalendar.io/releases/daygrid/4.1.0/main.min.js'></script>
<script src='https://fullcalendar.io/releases/timegrid/4.1.0/main.min.js'></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myController">
  <div id="calendar" ng-model="eventSources"></div>
</body>


问:
what is the c++ equivalent of map(int,input().split()) of python?
I find it hard to do all the string manipulation and then parsing into an array of integers in c++ while we could get away with only a single line in python.

whats the easiest way to split the string of integers into an array of integers in c++ ?

答:
The question is too broad and there are many solutions depending on the format of your string. In the case that you want to split a string using a custom delimiter and convert it to integers (or whatever) I personally use the following function (I have absolutely no idea if there are faster ways to do it): </p>

```<code>void split_string_with_delim(std::string input, std::string delimiter, std::vector<std::int> &output){
    ulong pos;
    while ((pos = input.find(delimiter)) != std::string::npos) {
        std::string token = input.substr(0, pos);
        output.push_back(std::stoi(token));
        input.erase(0, pos + delimiter.length());
    }
    output.push_back(std::stoi(input));
}
</code>```

Body:
The question is too broad and there are many solutions depending on the format of your string. In the case that you want to split a string using a custom delimiter and convert it to integers (or whatever) I personally use the following function (I have absolutely no idea if there are faster ways to do it):

void split_string_with_delim(std::string input, std::string delimiter, std::vector<std::int> &output){
    ulong pos;
    while ((pos = input.find(delimiter)) != std::string::npos) {
        std::string token = input.substr(0, pos);
        output.push_back(std::stoi(token));
        input.erase(0, pos + delimiter.length());
    }
    output.push_back(std::stoi(input));
}


问:
compare two files and store the output in a file only if there is a mismatch
I am comparing multiple files in a while loop and storing the output in new files.

I am doing like below

```<code>while IFS='|' read -r work_table_name final_table_name;do
    comm -23 <(sort /home/$USER/work_schema/${work_table_name}_work_schema.txt) <(sort /home/$USER/final_schema/${final_table_name}_final_schema.txt) > /home/$USER/mismatched_schema/${final_table_name}.txt
done < /home/$USER/tables.txt
</code>```

I am getting what I want. But just need a bit of result of the whole while loop.

I want to create files only when there is a mismatch between the files. If there is no mismatch then don't create a file at all.

How can I achieve that?

答:
But just need a bit of result of the whole while loop.

So redirect the whole while loop output:

```<code>while read -r ....; do
    comm -23 <(...) <(...)
done < input > output
</code>```

Or append:

```<code># this will truncate the output file, so we start empty
: > output

while read -r ....; do
     comm -23 <(...) <(...) >> output
done < input
</code>```

I basically don't want to create a empty file while comparing two files

So check if it's empty or not...

```<code>out=$(comm -23 <(....) <(....))
if ((${#out} != 0)); then
    printf "%s" "$out"
fi
</code>```

Body:
I am comparing multiple files in a while loop and storing the output in new files.

I am doing like below

while IFS='|' read -r work_table_name final_table_name;do
    comm -23 <(sort /home/$USER/work_schema/${work_table_name}_work_schema.txt) <(sort /home/$USER/final_schema/${final_table_name}_final_schema.txt) > /home/$USER/mismatched_schema/${final_table_name}.txt
done < /home/$USER/tables.txt

I am getting what I want. But just need a bit of result of the whole while loop.

I want to create files only when there is a mismatch between the files. If there is no mismatch then don't create a file at all.

How can I achieve that?

Body:
But just need a bit of result of the whole while loop.

So redirect the whole while loop output:

while read -r ....; do
    comm -23 <(...) <(...)
done < input > output

Or append:

# this will truncate the output file, so we start empty
: > output

while read -r ....; do
     comm -23 <(...) <(...) >> output
done < input

I basically don't want to create a empty file while comparing two files

So check if it's empty or not...

out=$(comm -23 <(....) <(....))
if ((${#out} != 0)); then
    printf "%s" "$out"
fi


问:
Removing all invalid characters (e.g. \uf0b7) from text
I currently have several text coming in which sometimes contains the character 'invalid character' e.g. \uf0b7 or \uf077. I don't have a way of knowing which of the invalid character codes a specific text might contain and I wondered if there was a way to make sure that a string is cleaned of all types of 'invalid character', since a process later on (which is dependent on a third party package) can not receive a string which contains it.

I've tried searching for a solution, but all I get it is answers regarding regular characters which people want removed (e.g. '^%$&*') which they have classified as invalid characters, however I want to remove/replace the actual character 'invalid character' in all its forms

答:
The Python library codecs might be of help.  Take a look at the documentation here: https://docs.python.org/2/library/codecs.htm

In my use case, I was doing some analysis of documents that had non-ASCII text.  For my purposes, ignoring the invalid characters was acceptable.  I opened the files with the following line and was able to parse the corpus.

```<code>for filename in os.listdir(ROOT_DIR):
    with codecs.open(os.path.join(ROOT_DIR, filename), encoding = 'UTF8', errors ='replace' ) as f:
</code>```

Body:
The Python library codecs might be of help.  Take a look at the documentation here: https://docs.python.org/2/library/codecs.htm

In my use case, I was doing some analysis of documents that had non-ASCII text.  For my purposes, ignoring the invalid characters was acceptable.  I opened the files with the following line and was able to parse the corpus.

for filename in os.listdir(ROOT_DIR):
    with codecs.open(os.path.join(ROOT_DIR, filename), encoding = 'UTF8', errors ='replace' ) as f:


问:
vue.js component not updated after vuex action on another component
I've a component which render a booking table; When I update my store in another component, the table isn't updated (but the store does and so the computed properties; My guess is that the problem is related to the filter not being updated but I'm not sure at all.

To do so, I've a vuex store:

```<code>...
const store = new Vuex.Store({
  state: {
    bookings: [],
    datesel: '',
  },
  getters: {
    bookings: (state) => {
        return state.bookings
    },
  },
  mutations: {
    SET_BOOKINGS: (state, bookings) => {
        state.bookings = bookings
    },
  },
  actions: {
    setBookings: ({commit, state}, bookings) => {
        commit('SET_BOOKINGS', bookings)
        return state.bookings
    },
  }
})
export default store;
</code>```

The table is basically a v-for with a filter:

```<code> <template v-for="booking in getBookings( heure, terrain )">
</code>```

Where getBookings is a method:

```<code>getBookings(hour, court) {
              return this.$store.state.bookings.filter(booking => booking.heure == hour && booking.terrain == court);
            }
</code>```

I've another component which will update my bookings state through a method:

```<code>bookCourt() {
                axios.post('http://localhost/bdcbooking/public/api/reservations/ponctuelles',
                  {
                        date: this.datesel,
                        membre_id: '1',
                        heure: this.chosenHour,
                        terrain: this.chosenCourt,
                        saison_id: '1'

                  })

              .then(response => {
                // JSON responses are automatically parsed.
                console.log(response.data);

              })
              .catch(e => {
                this.errors.push(e)
              })
              axios.get('http://localhost/bdcbooking/public/api/getReservationsDate?datesel=' + this.datesel)
              .then(response => {
                // JSON responses are automatically parsed.
                console.log(response.data);
                this.bookings = response.data;

              })
              .catch(e => {
                this.errors.push(e)
              })
              $(this.$refs.vuemodal).modal('hide');

            }
</code>```

While this.bookings is a computed property:

```<code>computed: {
          bookings: {
            get () {
                return this.$store.getters.bookings
            },
            set (bookings) {
                return this.$store.dispatch('setBookings', bookings)
                console.log('on lance l action');
            }
          }
    }
</code>```

答:
Your table is not updated because getBookings is a simple method and hence the method won't be fired again based on vuex state changes.

You can make this getBookings method as an computed property that returns filtered results and will also upadte on state changes.

Body:
I've a component which render a booking table; When I update my store in another component, the table isn't updated (but the store does and so the computed properties; My guess is that the problem is related to the filter not being updated but I'm not sure at all.

To do so, I've a vuex store:

...
const store = new Vuex.Store({
  state: {
    bookings: [],
    datesel: '',
  },
  getters: {
    bookings: (state) => {
        return state.bookings
    },
  },
  mutations: {
    SET_BOOKINGS: (state, bookings) => {
        state.bookings = bookings
    },
  },
  actions: {
    setBookings: ({commit, state}, bookings) => {
        commit('SET_BOOKINGS', bookings)
        return state.bookings
    },
  }
})
export default store;

The table is basically a v-for with a filter:

 <template v-for="booking in getBookings( heure, terrain )">

Where getBookings is a method:

getBookings(hour, court) {
              return this.$store.state.bookings.filter(booking => booking.heure == hour && booking.terrain == court);
            }

I've another component which will update my bookings state through a method:

bookCourt() {
                axios.post('http://localhost/bdcbooking/public/api/reservations/ponctuelles',
                  {
                        date: this.datesel,
                        membre_id: '1',
                        heure: this.chosenHour,
                        terrain: this.chosenCourt,
                        saison_id: '1'

                  })

              .then(response => {
                // JSON responses are automatically parsed.
                console.log(response.data);

              })
              .catch(e => {
                this.errors.push(e)
              })
              axios.get('http://localhost/bdcbooking/public/api/getReservationsDate?datesel=' + this.datesel)
              .then(response => {
                // JSON responses are automatically parsed.
                console.log(response.data);
                this.bookings = response.data;

              })
              .catch(e => {
                this.errors.push(e)
              })
              $(this.$refs.vuemodal).modal('hide');

            }

While this.bookings is a computed property:

computed: {
          bookings: {
            get () {
                return this.$store.getters.bookings
            },
            set (bookings) {
                return this.$store.dispatch('setBookings', bookings)
                console.log('on lance l action');
            }
          }
    }


问:
Do not download empty folders while downloading from SFTP server using Python
I got a code to download files recursively in Python on this site. This code also downloads empty directories on server also.

Please help me to modify this code so that it does not download empty directories from the server.

Code I have (based on Python pysftp get_r from Linux works fine on Linux but not on Windows):

```<code>import os
import pysftp
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
sftp=pysftp.Connection('192.168.X.X', username='username',password='password',cnopts=cnopts)

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir(remotedir):
        remotepath = remotedir + "/" + entry
        localpath = os.path.join(localdir, entry)
        mode = sftp.stat(remotepath).st_mode
        if S_ISDIR(mode):
            try:
                os.mkdir(localpath,mode=777)
            except OSError:
                pass
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

remote_path=input("enter the remote_path: ")
local_path=input("enter the local_path: ")

get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)
</code>```

答:
You can delay creating a local directory, until you encounter a file you want to download there:</p>

```<code>from stat import S_ISDIR, S_ISREG
</code>```

```<code>def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir(remotedir):
        remotepath = remotedir + "/" + entry
        localpath = os.path.join(localdir, entry)
        mode = sftp.stat(remotepath).st_mode
        if S_ISDIR(mode):
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            os.makedirs(localdir, exist_ok=True)
            sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)
</code>```

Body:
I got a code to download files recursively in Python on this site. This code also downloads empty directories on server also.

Please help me to modify this code so that it does not download empty directories from the server.

Code I have (based on Python pysftp get_r from Linux works fine on Linux but not on Windows):

import os
import pysftp
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
sftp=pysftp.Connection('192.168.X.X', username='username',password='password',cnopts=cnopts)

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir(remotedir):
        remotepath = remotedir + "/" + entry
        localpath = os.path.join(localdir, entry)
        mode = sftp.stat(remotepath).st_mode
        if S_ISDIR(mode):
            try:
                os.mkdir(localpath,mode=777)
            except OSError:
                pass
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

remote_path=input("enter the remote_path: ")
local_path=input("enter the local_path: ")

get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)

Body:
You can delay creating a local directory, until you encounter a file you want to download there:

from stat import S_ISDIR, S_ISREG

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir(remotedir):
        remotepath = remotedir + "/" + entry
        localpath = os.path.join(localdir, entry)
        mode = sftp.stat(remotepath).st_mode
        if S_ISDIR(mode):
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            os.makedirs(localdir, exist_ok=True)
            sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)


问:
NSThread and object retain count issue
I want to be able to call an object's method on a new thread; but, I am confused about how to manage retain counts (or even if it is an issue).

In a non-threaded scenario, I would do this:

```<code>MyObject *newObject = [[MyObject alloc] init];
[newObject doSomething];
[newObject release];
</code>```

In this scenario, everything's fine. However, my question is whether the following threaded version is a problem:

```<code>MyObject *newObject = [[MyObject alloc] init];
[NSThread detachNewThreadSelector:@selector(doSomething)
                         toTarget:newObject
                       withObject:nil];
[newObject release];
</code>```

In this case, do I have to worry about newObject being released while -doSomething is processing? If the answer is yes, then it seems messy to have -doSomething retain self.

Is this an issue? And, if so, what's the correct solution?

答:
From the Xcode API docs:

The objects aTarget and anArgument are retained during the execution of the detached thread, then released. The detached thread is exited (using the exit class method) as soon as aTarget has completed executing the aSelector method.

So, the way you have coded it is fine. You can and should release newObject.

OwnerDisplayName: Scott S

LastEditorDisplayName: Chris Hanson

Title: NSThread and object retain count issue

Body:
I want to be able to call an object's method on a new thread; but, I am confused about how to manage retain counts (or even if it is an issue).

In a non-threaded scenario, I would do this:

MyObject *newObject = [[MyObject alloc] init];
[newObject doSomething];
[newObject release];

In this scenario, everything's fine. However, my question is whether the following threaded version is a problem:

MyObject *newObject = [[MyObject alloc] init];
[NSThread detachNewThreadSelector:@selector(doSomething)
                         toTarget:newObject
                       withObject:nil];
[newObject release];

In this case, do I have to worry about newObject being released while -doSomething is processing? If the answer is yes, then it seems messy to have -doSomething retain self.

Is this an issue? And, if so, what's the correct solution?

OwnerDisplayName: DasBoot


问:
How to convert Bystream Video to file video in java
I'm build a project to convert video to byte stream, doing some encryption, and convert agaian stream that have been encrypting into video file. I am using mpeg video..

Anybody know how to convert from byte stream to file video? in case, mpeg file...thanks before

答:
To convert a file into a byte stream, simply open it using FileInputStream.

```<code>FileInputStream fis = new FileInputStream ("filename.mov");
</code>```

You'll probably want to buffer it as video files are quite large

```<code>BufferedInputStream bis = new BufferedInputStream (fis);
</code>```

To write out the file, simply open it using FileOutputStream:

```<code>FileOutputStream fos = new FileOutputStream ("fileout.mov");
</code>```

and then write to it using the FileOutputStream.

Body:
To convert a file into a byte stream, simply open it using FileInputStream.

FileInputStream fis = new FileInputStream ("filename.mov");

You'll probably want to buffer it as video files are quite large

BufferedInputStream bis = new BufferedInputStream (fis);

To write out the file, simply open it using FileOutputStream:

FileOutputStream fos = new FileOutputStream ("fileout.mov");

and then write to it using the FileOutputStream.


问:
How to copy a file created in a python script to a remote server which needs password, using pscp?
I need to copy many files created in a python script from local to a remote server. On the command prompt I use this line :

"pscp c:\users\myaccount\documents\foler\file.txt name@server:/home/folder".

But this requires a password that I can enter on the command prompt.

On my python script I "import os" then :

cmd = "pscp local_path server_path"

os.system(cmd)

But I don't know how to enter the password in my script.

Thanks

答:
try using paramiko package https://docs.paramiko.org/en/2.4/</p>

```<code>s = paramiko.SSHClient()
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    s.connect("xxx.xxx.xxx.xxx",22,username=xxx,password='',timeout=4)

    sftp = s.open_sftp()
    sftp.put('/home/me/file.ext', '/remote/home/file.ext')
</code>```

Body:
try using paramiko package https://docs.paramiko.org/en/2.4/

s = paramiko.SSHClient()
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    s.connect("xxx.xxx.xxx.xxx",22,username=xxx,password='',timeout=4)

    sftp = s.open_sftp()
    sftp.put('/home/me/file.ext', '/remote/home/file.ext')


问:
re-execute the MVC pipeline with another route from a resource filter

TL;DR

How do I reinvoke the MVC routing engine and MvcHandler from a IAsyncResourceFilter, using another route? I basically want to invoke the pipeline twice (in parallel?).

background

I'm building a HAL implementation for an ASP.Net Core API. To implement HAL, a returned resource should be able to embed other resources in order to reduce the chattiness between client and server. A response would look like this:

```<code>{
   "_links": {
      "self": {
         "href": "/myResource/1"
      }
   },
   "name": "myResource",
   "foo": "bar",
   "_embedded": {
      "relatedResource": {
         "_links": {
            "self": {
               "href": "/relatedResources/5"
            }
         },
         "name": "relatedResource",
         "baz": "foo"
      }
   }
}
</code>```

I want to decouple the embedding of resources from the controllers, so I figured I would simply

invoke the MVC pipeline for the original request.

invoke the MVC pipeline for the resources to embed.

embed the the resources from 2 to the response of 1.

If this would work, this would enable caching of the resources to embed as well as authorization and what not.

I want to use a ResourceFilter, because I need to access the controller and action the request will be routed to, in order to know what resources should be embedded. So I need access to the ControllerActionDescriptor.

```<code>public class HalEmbed : IAsyncResourceFilter
{
    public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
    {
        // Implementation not useful for question
        var actionToEmbed = GetActionToEmbed();

        await next();

        // TODO: How do I do this?
        var embedResult = await ReExecutePipelineHere(actionToEmbed.Url);

        // Will be magic if I know how to do the above.
        Embed(embedResult, context.Result);
    }
}
</code>```

This diagram I found in the docs implies it should be possible to re-execute the pipeline from a resource filter somehow:

So how do I re-execute the MVC pipeline with another url, while also being able to execute the pipeline for the current url?

答:
I managed to re-invoke (part of) the MVC pipeline, by adding custom middleware that passes a custom HttpContext to the calls for adding embedded resources. I'm not sure whether this allows me to leverage response caching and authorization to the full extent yet, but in a simple api, it does re-invoke the MVC pipeline.

It is, however, rather cumbersome. Here's some pseudo-code below to show how it may be done.

```<code>public class HalMiddleware
{
    private RequestDelegate next;
    public HalMiddleware(RequestDelegate next)
    {
        // We need the MVC pipeline after our custom middleware.
        this.next = next
            ?? throw new ArgumentNullException(nameof(next));
    }

    public async Task Invoke(HttpContext context)
    {
        // Invoke the 'normal' pipeline first.
        // Note that the mvc middleware would serialize the response...
        // Prevent that by injecting a custom IActionResultExecutor<ObjectResult>,
        // that sets the ActionResult to the context instead of serializing.
        await this.next(context);

        // Our objectresultexecutor added some information on the HttpContext.
        if (!context.Items.TryGetValue("HalFormattingContext", out object formatObject)
            ||!(formatObject is HalFormattingContext halFormattingContext))
        {
            logger.LogDebug("Hal formatting context not found, other formatters are handling this response.");
            return;
        }

        // some code to create a resource object from the result.
        var rootResource = ConstructRootResource(halFormattingContext.ObjectResult);
        halFormattingContext.ObjectResult.Value = rootResource;

        // some code to figure out which actions/routes to embed.
        var toEmbeds = GetRoutesToEmbed(halFormattingContext.ActionContext);
        var requestFeature = context.Features.Get<IHttpRequestFeature>();
        foreach (var toEmbed in toEmbeds)
        {
            var halRequestFeature = new HalHttpRequestFeature(requestFeature)
            {
                Method = "GET",
                Path = toEmbed.Path
            };

            // The HalHttpContext creates a custom request and response in the constructor
            // and creates a new feature collection with custom request and response features.
            var halContext = new HalHttpContext(context, halRequestFeature);
            await this.next(halContext);

            // Now the custom ObjectResultExecutor set the ActionResult to a property of the custom HttpResponse.
            var embedActionResult = ((HalHttpResponse)halContext.Response).ObjectResult;

            // some code to embed the new actionresult.
            Embed(rootResource, embedActionResult, toEmbed);
        }

        // Then invoke the default ObjectResultExecutor to serialize the new result.
        await halFormattingContext.DefaultExecutor.ExecuteAsync(
            halFormattingContext.ActionContext,
            halFormattingContext.ObjectResult);
    }
}
</code>```

Body:
TL;DR

How do I reinvoke the MVC routing engine and MvcHandler from a IAsyncResourceFilter, using another route? I basically want to invoke the pipeline twice (in parallel?).

background

I'm building a HAL implementation for an ASP.Net Core API. To implement HAL, a returned resource should be able to embed other resources in order to reduce the chattiness between client and server. A response would look like this:

{
   "_links": {
      "self": {
         "href": "/myResource/1"
      }
   },
   "name": "myResource",
   "foo": "bar",
   "_embedded": {
      "relatedResource": {
         "_links": {
            "self": {
               "href": "/relatedResources/5"
            }
         },
         "name": "relatedResource",
         "baz": "foo"
      }
   }
}

I want to decouple the embedding of resources from the controllers, so I figured I would simply

invoke the MVC pipeline for the original request.

invoke the MVC pipeline for the resources to embed.

embed the the resources from 2 to the response of 1.

If this would work, this would enable caching of the resources to embed as well as authorization and what not.

I want to use a ResourceFilter, because I need to access the controller and action the request will be routed to, in order to know what resources should be embedded. So I need access to the ControllerActionDescriptor.

public class HalEmbed : IAsyncResourceFilter
{
    public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
    {
        // Implementation not useful for question
        var actionToEmbed = GetActionToEmbed();

        await next();

        // TODO: How do I do this?
        var embedResult = await ReExecutePipelineHere(actionToEmbed.Url);

        // Will be magic if I know how to do the above.
        Embed(embedResult, context.Result);
    }
}

This diagram I found in the docs implies it should be possible to re-execute the pipeline from a resource filter somehow:

So how do I re-execute the MVC pipeline with another url, while also being able to execute the pipeline for the current url?

Body:
I managed to re-invoke (part of) the MVC pipeline, by adding custom middleware that passes a custom HttpContext to the calls for adding embedded resources. I'm not sure whether this allows me to leverage response caching and authorization to the full extent yet, but in a simple api, it does re-invoke the MVC pipeline.

It is, however, rather cumbersome. Here's some pseudo-code below to show how it may be done.

public class HalMiddleware
{
    private RequestDelegate next;
    public HalMiddleware(RequestDelegate next)
    {
        // We need the MVC pipeline after our custom middleware.
        this.next = next
            ?? throw new ArgumentNullException(nameof(next));
    }

    public async Task Invoke(HttpContext context)
    {
        // Invoke the 'normal' pipeline first.
        // Note that the mvc middleware would serialize the response...
        // Prevent that by injecting a custom IActionResultExecutor<ObjectResult>,
        // that sets the ActionResult to the context instead of serializing.
        await this.next(context);

        // Our objectresultexecutor added some information on the HttpContext.
        if (!context.Items.TryGetValue("HalFormattingContext", out object formatObject)
            ||!(formatObject is HalFormattingContext halFormattingContext))
        {
            logger.LogDebug("Hal formatting context not found, other formatters are handling this response.");
            return;
        }

        // some code to create a resource object from the result.
        var rootResource = ConstructRootResource(halFormattingContext.ObjectResult);
        halFormattingContext.ObjectResult.Value = rootResource;

        // some code to figure out which actions/routes to embed.
        var toEmbeds = GetRoutesToEmbed(halFormattingContext.ActionContext);
        var requestFeature = context.Features.Get<IHttpRequestFeature>();
        foreach (var toEmbed in toEmbeds)
        {
            var halRequestFeature = new HalHttpRequestFeature(requestFeature)
            {
                Method = "GET",
                Path = toEmbed.Path
            };

            // The HalHttpContext creates a custom request and response in the constructor
            // and creates a new feature collection with custom request and response features.
            var halContext = new HalHttpContext(context, halRequestFeature);
            await this.next(halContext);

            // Now the custom ObjectResultExecutor set the ActionResult to a property of the custom HttpResponse.
            var embedActionResult = ((HalHttpResponse)halContext.Response).ObjectResult;

            // some code to embed the new actionresult.
            Embed(rootResource, embedActionResult, toEmbed);
        }

        // Then invoke the default ObjectResultExecutor to serialize the new result.
        await halFormattingContext.DefaultExecutor.ExecuteAsync(
            halFormattingContext.ActionContext,
            halFormattingContext.ObjectResult);
    }
}


问:
What are the benefits of using a sigmoid function?
I am dipping my toe into neural networks and starting with some basic perceptrons. In one video, this guy is explaining how to make a machine that can 'learn' how to distinguish two arrays. He explains the training process, but just shoves all of his inputs and weights into the sigmoid function. I did some research on the sigmoid function and was wondering why it is used in machine learning and why programmers use it to test their inputs.</p>

答:
This function's job is to make the numbers between 0 and 1, usually for supervised classification problems. for example in binary supervised classification problems that the labels are only two (for example in the picture below), then one data that is far from others will effect too much on the separator line.

But when we use Sigmoid function we can see that a data far from others won't effect the separator too much.

Also this function can show you a probability as well. for example if you have a new data to predict, then you can use the line and see how much it is possible that the data belongs to some label. (Take a look at the picture to understand better)

picture Link : https://pasteboard.co/IgLjcYN.jpg

 y  and feature -> x">


问:
How to update Site.less/site.css and bundle/minify to generate output with BuildBundlerMinifier
I have several questions on my ASP.NET MVC CORE 2.2 project.
The main goal is very simple, i want to update my stylesheet and then deploy this result. I have a Site.less, site.css, site.min.css, site.min.css.gz that i want to update with a css class style, a bundleconfig.json with my input css, javascript files to be bundled and a compilerconfig.json that has Site.less as an input and site.css as output. I also have BuildBundlerMinifier installed on my project (NuGet).

Questions:

1- What file should i update when adding some new style: Site.less, site.css or both?
2- What are the steps to minify and bundle before i publish my app?

bundleconfig.json:

```<code>[
  {
    "outputFileName": "wwwroot/css/bundle.min.css",
    // An array of relative input file paths. Globbing patterns supported
    "inputFiles": [
      (...)
      "wwwroot/css/Site.min.css"
    ]
  },
  (...)
    // Optionally specify minification options
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    // Optionally generate .map file
    "sourceMap": false
  }
]
</code>```

compilerconfig.json

```<code>[
  {
    "inputFile": "wwwroot/css/Site.less",
    "outputFile": "wwwroot/css/site.css"
  }
]
</code>```

When i rebuild my project in my Output window (Visual Studio 2017) i have the following messages.

Cleaning output from bundleconfig.json,
  Done cleaning output file from bundleconfig.json, Begin processing bundleconfig.json, Minified wwwroot/css/bundle.min.css, Done processing bundleconfig.json

Thank you.

答:
My first question is answered.

I have installed an extension in Visual Studio 2017 (Tools -> Extensions and Updates) named Web Compiler. When i make an update in my less file, the css file and min.css are auto generated (min.css.gz is not and don't know why). The files that the code is auto generated are water marked with Generated keyword.

To produce the auto generated files you only need to rebuild the project.

This works with other files but in my case i am only using this ones.

EDIT

My second question is also answered.

I have installed another extension: Bundler & Minifier

To produce bundle you need to have those config json files i have posted in my first post and then open Task Runner Explorer and double click on wwwroot/css/bundle.min.css (inside StyleSheets menu) and the bundle file will be auto generated.

Body:
I have several questions on my ASP.NET MVC CORE 2.2 project.
The main goal is very simple, i want to update my stylesheet and then deploy this result. I have a Site.less, site.css, site.min.css, site.min.css.gz that i want to update with a css class style, a bundleconfig.json with my input css, javascript files to be bundled and a compilerconfig.json that has Site.less as an input and site.css as output. I also have BuildBundlerMinifier installed on my project (NuGet).

Questions:

1- What file should i update when adding some new style: Site.less, site.css or both?
2- What are the steps to minify and bundle before i publish my app?

bundleconfig.json:

[
  {
    "outputFileName": "wwwroot/css/bundle.min.css",
    // An array of relative input file paths. Globbing patterns supported
    "inputFiles": [
      (...)
      "wwwroot/css/Site.min.css"
    ]
  },
  (...)
    // Optionally specify minification options
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    // Optionally generate .map file
    "sourceMap": false
  }
]

compilerconfig.json

[
  {
    "inputFile": "wwwroot/css/Site.less",
    "outputFile": "wwwroot/css/site.css"
  }
]

When i rebuild my project in my Output window (Visual Studio 2017) i have the following messages.

Cleaning output from bundleconfig.json,
  Done cleaning output file from bundleconfig.json, Begin processing bundleconfig.json, Minified wwwroot/css/bundle.min.css, Done processing bundleconfig.json

Thank you.


问:
UIKit state preservation not restoring scroll offset
I have an app that is using UIKit state preservation in iOS 6. I am able to save/restore the state of the view controllers, ie which tab is selected and navigation controller hierarchy, however I cannot get my table view to restore it's offset. I have a restoration identifier in my storyboard for the view as well as the view controller and the view controller (the table's data source) implements UIDataSourceModelAssociation as follows:

```<code>- (NSString *)modelIdentifierForElementAtIndexPath:(NSIndexPath *)indexPath inView:(UIView *)view
{
    TSStatus *status = [self._fetchedResultsController objectAtIndexPath:indexPath];

    return status.objectID.URIRepresentation.absoluteString;
}

- (NSIndexPath *)indexPathForElementWithModelIdentifier:(NSString *)identifier inView:(UIView *)view
{
    NSURL *statusURL = [NSURL URLWithString:identifier];
    NSManagedObjectID *statusID = [[TSDataController sharedController].persistentStoreCoordinator managedObjectIDForURIRepresentation:statusURL];
    TSStatus *status = (TSStatus *)[[TSDataController sharedController].mainContext objectWithID:statusID];

    return [__fetchedResultsController indexPathForObject:status];
}
</code>```

modelIdentifierForElementAtIndexPath:inView: is getting called when the app goes into the background, however modelIdentifierForElementAtIndexPath:inView: never gets called.

答:
See Apple's State restoration sample for how to achieve this. The magic fix happens in the decodeRestorableStateWithCoder method with a call to reloadData:

MyTableViewController.m

```<code>// this is called when the app is re-launched
- (void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
    // important: don't affect our views just yet, we might not visible or we aren't the current
    // view controller, save off our ivars and restore our text view in viewWillAppear
    //
    NSLog(@"MyTableViewController: decodeRestorableStateWithCoder");

    [super decodeRestorableStateWithCoder:coder];

    self.tableView.editing = [coder decodeBoolForKey:kUnsavedEditStateKey];

    [self.tableView reloadData];
}
</code>```

Note it is odd that they encode the editing state because editing is ended by their enter background notification handler before preservation begins so it will always restore not editing. Also they try to set self.tableView.editing instead of self.editing so the edit button wouldn't update. Also note the comment about not affecting the views which is odd firstly given they do affect the views and second viewWillAppear is called before decoding state. Given these mistakes I wouldn't use this example to tune your programming skills.

The other answer states to reload in the indexPathForElementWithModelIdentifier which is not a good idea given it is called multiple times (at least twice) to find various index paths of visible and selected objects.

Body:
I have an app that is using UIKit state preservation in iOS 6. I am able to save/restore the state of the view controllers, ie which tab is selected and navigation controller hierarchy, however I cannot get my table view to restore it's offset. I have a restoration identifier in my storyboard for the view as well as the view controller and the view controller (the table's data source) implements UIDataSourceModelAssociation as follows:

- (NSString *)modelIdentifierForElementAtIndexPath:(NSIndexPath *)indexPath inView:(UIView *)view
{
    TSStatus *status = [self._fetchedResultsController objectAtIndexPath:indexPath];

    return status.objectID.URIRepresentation.absoluteString;
}

- (NSIndexPath *)indexPathForElementWithModelIdentifier:(NSString *)identifier inView:(UIView *)view
{
    NSURL *statusURL = [NSURL URLWithString:identifier];
    NSManagedObjectID *statusID = [[TSDataController sharedController].persistentStoreCoordinator managedObjectIDForURIRepresentation:statusURL];
    TSStatus *status = (TSStatus *)[[TSDataController sharedController].mainContext objectWithID:statusID];

    return [__fetchedResultsController indexPathForObject:status];
}

modelIdentifierForElementAtIndexPath:inView: is getting called when the app goes into the background, however modelIdentifierForElementAtIndexPath:inView: never gets called.

Body:
See Apple's State restoration sample for how to achieve this. The magic fix happens in the decodeRestorableStateWithCoder method with a call to reloadData:

MyTableViewController.m

// this is called when the app is re-launched
- (void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
    // important: don't affect our views just yet, we might not visible or we aren't the current
    // view controller, save off our ivars and restore our text view in viewWillAppear
    //
    NSLog(@"MyTableViewController: decodeRestorableStateWithCoder");

    [super decodeRestorableStateWithCoder:coder];

    self.tableView.editing = [coder decodeBoolForKey:kUnsavedEditStateKey];

    [self.tableView reloadData];
}

Note it is odd that they encode the editing state because editing is ended by their enter background notification handler before preservation begins so it will always restore not editing. Also they try to set self.tableView.editing instead of self.editing so the edit button wouldn't update. Also note the comment about not affecting the views which is odd firstly given they do affect the views and second viewWillAppear is called before decoding state. Given these mistakes I wouldn't use this example to tune your programming skills.

The other answer states to reload in the indexPathForElementWithModelIdentifier which is not a good idea given it is called multiple times (at least twice) to find various index paths of visible and selected objects.


问:
How to send data from dialog back to parent container with react?
I have a react-big-calendar (The parent container), I have also a select which, the events of the calendar are fetched according to this select ( doctor name ) and I have a button when I click on it, the dialog will be appears (another component), on this dialog, I have a form to add an event after the select, when I post my API, I save it on local storage, but the event added doesn't appears on my calendar just after refresh the page and reselect the doctor name.
But I want, when I click on the save button, will be added directly on the calendar and it will be appeared on the calendar.

My code of calendar is :

```<code>   import Popup from './Popup';
export default class Calendar extends Component {
constructor(props){
    super(props);
    this.state = {
      events : [],
      open: false,
}}
componentDidMount = () => {
    fetch(process.env.REACT_APP_API_BACKEND_YET+'get_liste_praticien.php')
      .then(Response => Response.json())
      .then(data => {
        this.setState ({ praticiens : data })
        localStorage.setItem('Liste de praticiens ', JSON.stringify(this.state.praticiens))
    })
}
fetchData = (nom,identifiant_user) => {
    this.setState({
      events: [],
      evtStorage:[],
      prevEvents:[],
      evtBackend:[]
    })
      fetch(process.env.REACT_APP_API_BACKEND+'get_liste_planning')
        .then(Response => Response.json())
        .then(data => {
          let evts = data.ListeResult;
          for (let i = 0; i < evts.length; i++) {
            evts[i].start = moment(evts[i].start).toDate();
            evts[i].end = moment(evts[i].end).toDate();
           if(evts[i].typeplanning === '0') this.setState({isConges:true})
            this.state.events.push(evts[i])
          }
          this.setState({
            evtBackend: evts,
            events:  evts
          })
          localStorage.setItem("Liste de planning de " + nom, JSON.stringify(this.state.events));
        })
        const evtCached1 = JSON.parse(localStorage.getItem('Liste récente de planning de ' + nom));
        if(evtCached1 !== null) {
          for (let j = 0; j < evtCached1.length; j++) {
            evtCached1[j].start = moment(evtCached1[j].start).toDate();
            evtCached1[j].end = moment(evtCached1[j].end).toDate();
            if(evtCached1[j].typeplanning === '0') this.setState({isConges:true})
            this.state.events.push(evtCached1[j]);
          }
          this.setState({
            events:this.state.events,
          });
          localStorage.removeItem("Liste de planning de " + nom);
        }}
// For the select
handlePraticienChange = id_user => {
    this.setState({
      openPopupAjout: true,
      id_user: id_user
    },() => {
      this.state.praticiens.map((praticien)=> {
          if(this.state.id_user === praticien.id_user){
            this.setState ({ nom_user: praticien.nom_user})
           this.fetchData(praticien.nom_user, praticien.identifiant_user);
          }
      })
      }
    );
  }
// for the popup
 ModalAjoutb = (ref) => {
    if (ref) {
      this.ajoutb = ref.handleAjouterb;
    } else {
      this.ajoutb = null;
    }
  }
render() {

    return (
<div>
    <button className="bp3-button bp3-icon-add-to-artifact .bp3-fill" tabIndex="0" onClick={() => this.ajoutb(this.state.id_user, this.state.events)}>Add event</button>
    <Select  onChange={this.handlePraticienChange} value={this.state.id_user}>
        {this.state.praticiens.map((praticien) =>
            <Option key={praticien.id_user} value={praticien.id_user}>{praticien.nom_user}</Option>
        )}
    </Select>
    <DragAndDropCalendar
        selectable
        localizer={localizer}
        events={this.state.events}
        views={['month','week','day']}
        defaultView="week"
        culture = 'fr'
    />
    <Popup ref={this.ModalAjoutb} id_user={this.state.id_user} events={this.state.events} />
</div>
);
}}
</code>```

My code of dialog is :

```<code>export default class Popup extends Component {
constructor(props){
    super(props);
    this.state = {
      events : [],
}}
handleAjouterb = (id_user) => {
    this.setState({
      openPopupAjout: true,
      id_user,
    }, () => {
        this.fetchingPopup(this.state.id_user, this.state.identifiant_user, this.state.nom_user)
    });
  }
fetchingPopup = (id_user, identifiant_user, nom_user) =>{
    const praticiensCached = JSON.parse(localStorage.getItem('Liste de praticiens '));
    for (let j = 0; j < praticiensCached.length; j++) {
      if(id_user === praticiensCached[j].id_user){
        identifiant_user = praticiensCached[j].identifiant_user;
        this.setState ({ nom_user: praticiensCached[j].nom_user })
    }
}
handleValider = event => {
    event.preventDefault();
    const praticiensCached = JSON.parse(localStorage.getItem('Liste de praticiens '));
    for (let j = 0; j < praticiensCached.length; j++) {
      if(this.state.id_user === praticiensCached[j].id_user)
        this.state.identifiant_user = praticiensCached[j].identifiant_user;
    }

      const formData = new FormData();

      formData.append('identifiant_user', this.state.identifiant_user);
      formData.append('heuredebut', this.state.tranchesC[0].startC);
      formData.append('heurefin', this.state.tranchesC[0].endC);
      formData.append('libelleconge', this.state.libelle);
      axios({
        method: 'post',
        url: process.env.REACT_APP_API_BACKEND+'add_event_docteur',
        data: formData,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        }
      })
      .then(() => {
        fetch(process.env.REACT_APP_API_BACKEND+'get_liste_planning/start='+moment().startOf('isoweek').subtract(14,'days').toJSON()+'&end='+moment().endOf('isoweek').add(2,'months').toJSON()+'&identifiant_user='+this.state.identifiant_user)
          .then(Response => Response.json())
          .then(data => {
            let evts = data.ListeResult;
            for (let i = 0; i < evts.length; i++) {
              evts[i].start = moment(evts[i].start).toDate();
              evts[i].end = moment(evts[i].end).toDate();
              this.state.events.push(evts[i])
            }
            this.setState({
              events:  this.state.events
            }, ()=> {
              localStorage.setItem('Liste récente de planning de ' + this.state.nom_user, JSON.stringify(this.state.events));
              localStorage.removeItem("Liste de planning de " + this.state.nom_user);
              localStorage.setItem("Liste de planning de " + this.state.nom_user, JSON.stringify(this.state.events));
            })
          })
       })
}

render() {

    return (
<div>
    <Dialog
        icon="application"
        onClose={this.handleClose}
        title="Organisation des plannings du docteur"
        {...this.state}
        isOpen={this.state.openPopupAjout}>
           <Input id="libelle" style={{ width: '480px' }} value={this.state.libelle} onChange={this.handleInputChange('libelle')}/>
            <label className="pt-label .modifier"><strong>Date</strong></label>
            <LocaleProvider locale={fr_FR}>
                <RangePicker id="date" name= "date"  locale="fr" placeholder={["Date de début","Date de fin"]} separator="-" onChange={this.handleDateCChange}
                    value={this.state.dateIC} format="DD/MM/YYYY" allowClear={false}/>
            </LocaleProvider>
            <label className="pt-label .modifier"> <strong>Heure de début</strong></label>
            <Time value={el.startC} onChange={time => this.handleKeyboardStartCChange(i, time)} style={heure} disableUnderline={true} inputComponent={TextMaskCustom}
                    endAdornment={ <InputAdornment position="end" style={{opacity:'0.4'}}> <IconButton   onClick={() => this.openDialogC(i, el.startC, "startC")}><i  style={{fontSize:'18px'}} className="zmdi zmdi-alarm" /></IconButton>  </InputAdornment>}
            />
            <label className="pt-label .modifier"> <strong>Heure de fin</strong></label>
            <Time value={el.endC} onChange={time => this.handleKeyboardEndCChange(i, time)} style={heure} disableUnderline={true} inputComponent={TextMaskCustom}
                    endAdornment={ <InputAdornment position="end" style={{opacity:'0.4'}}> <IconButton  onClick={() => this.openDialogC(i, el.endC, "endC")}><i  style={{fontSize:'18px'}} className="zmdi zmdi-alarm" /></IconButton></InputAdornment> }/>

            <Clock maxWidth="xs" open={this.state.isOpenC} onBackdropClick={this.closeDialogC}>
            <TimePicker  mode="24h" value={this.createDateFromTextValueC(this.state.datePickerValueC)} onChange={this.handleDialogCChange}/>
            <DialogActions> <ButtonOk onClick={this.closeDialogC} color="primary"> Ok </ButtonOk></DialogActions>
            </Clock>
                <AnchorButton style={{display:'inline-block'}} intent={Intent.SUCCESS} onClick={this.handleValider}>Valider</AnchorButton>

</div>
);
}}
</code>```

I want to refresh the list of my events and appear my  event added on the calendar afer post form on the popup and not after the  refresh of the page and I will reselect the doctor.

How can I fix it ?

答:
I think, you can achieve it using code like this:

```<code>export default ComponentA extends Component {
  // set localStorage to bar state value
  // via click or whatever ...
    foo () {
    this.setState({
      bar: localStorage.getItem('bar')
    })
  }

  render () {
    // send the value of state to ComponentB
    return <ComponentB foo={this.state.bar}>
  }
}
</code>```

Into your component

```<code>export default class ComponentB extends Component {
    render () {
    // display the value of foo prop
    return <div>{this.props.foo}</div>
  }
}
</code>```

Note: You can always try to get the content of your localStoragedirectly from the ComponentB(Maybe using ComponentDidUpdate???) but the way I show you is better.

Body:
I have a react-big-calendar (The parent container), I have also a select which, the events of the calendar are fetched according to this select ( doctor name ) and I have a button when I click on it, the dialog will be appears (another component), on this dialog, I have a form to add an event after the select, when I post my API, I save it on local storage, but the event added doesn't appears on my calendar just after refresh the page and reselect the doctor name.
But I want, when I click on the save button, will be added directly on the calendar and it will be appeared on the calendar.

My code of calendar is :

   import Popup from './Popup';
export default class Calendar extends Component {
constructor(props){
    super(props);
    this.state = {
      events : [],
      open: false,
}}
componentDidMount = () => {
    fetch(process.env.REACT_APP_API_BACKEND_YET+'get_liste_praticien.php')
      .then(Response => Response.json())
      .then(data => {
        this.setState ({ praticiens : data })
        localStorage.setItem('Liste de praticiens ', JSON.stringify(this.state.praticiens))
    })
}
fetchData = (nom,identifiant_user) => {
    this.setState({
      events: [],
      evtStorage:[],
      prevEvents:[],
      evtBackend:[]
    })
      fetch(process.env.REACT_APP_API_BACKEND+'get_liste_planning')
        .then(Response => Response.json())
        .then(data => {
          let evts = data.ListeResult;
          for (let i = 0; i < evts.length; i++) {
            evts[i].start = moment(evts[i].start).toDate();
            evts[i].end = moment(evts[i].end).toDate();
           if(evts[i].typeplanning === '0') this.setState({isConges:true})
            this.state.events.push(evts[i])
          }
          this.setState({
            evtBackend: evts,
            events:  evts
          })
          localStorage.setItem("Liste de planning de " + nom, JSON.stringify(this.state.events));
        })
        const evtCached1 = JSON.parse(localStorage.getItem('Liste récente de planning de ' + nom));
        if(evtCached1 !== null) {
          for (let j = 0; j < evtCached1.length; j++) {
            evtCached1[j].start = moment(evtCached1[j].start).toDate();
            evtCached1[j].end = moment(evtCached1[j].end).toDate();
            if(evtCached1[j].typeplanning === '0') this.setState({isConges:true})
            this.state.events.push(evtCached1[j]);
          }
          this.setState({
            events:this.state.events,
          });
          localStorage.removeItem("Liste de planning de " + nom);
        }}
// For the select
handlePraticienChange = id_user => {
    this.setState({
      openPopupAjout: true,
      id_user: id_user
    },() => {
      this.state.praticiens.map((praticien)=> {
          if(this.state.id_user === praticien.id_user){
            this.setState ({ nom_user: praticien.nom_user})
           this.fetchData(praticien.nom_user, praticien.identifiant_user);
          }
      })
      }
    );
  }
// for the popup
 ModalAjoutb = (ref) => {
    if (ref) {
      this.ajoutb = ref.handleAjouterb;
    } else {
      this.ajoutb = null;
    }
  }
render() {

    return (

    <button className="bp3-button bp3-icon-add-to-artifact .bp3-fill" tabIndex="0" onClick={() => this.ajoutb(this.state.id_user, this.state.events)}>Add event</button>
    <Select  onChange={this.handlePraticienChange} value={this.state.id_user}>
        {this.state.praticiens.map((praticien) =>
            <Option key={praticien.id_user} value={praticien.id_user}>{praticien.nom_user}</Option>
        )}
    </Select>
    <DragAndDropCalendar
        selectable
        localizer={localizer}
        events={this.state.events}
        views={['month','week','day']}
        defaultView="week"
        culture = 'fr'
    />
    <Popup ref={this.ModalAjoutb} id_user={this.state.id_user} events={this.state.events} />

);
}}

My code of dialog is :

export default class Popup extends Component {
constructor(props){
    super(props);
    this.state = {
      events : [],
}}
handleAjouterb = (id_user) => {
    this.setState({
      openPopupAjout: true,
      id_user,
    }, () => {
        this.fetchingPopup(this.state.id_user, this.state.identifiant_user, this.state.nom_user)
    });
  }
fetchingPopup = (id_user, identifiant_user, nom_user) =>{
    const praticiensCached = JSON.parse(localStorage.getItem('Liste de praticiens '));
    for (let j = 0; j < praticiensCached.length; j++) {
      if(id_user === praticiensCached[j].id_user){
        identifiant_user = praticiensCached[j].identifiant_user;
        this.setState ({ nom_user: praticiensCached[j].nom_user })
    }
}
handleValider = event => {
    event.preventDefault();
    const praticiensCached = JSON.parse(localStorage.getItem('Liste de praticiens '));
    for (let j = 0; j < praticiensCached.length; j++) {
      if(this.state.id_user === praticiensCached[j].id_user)
        this.state.identifiant_user = praticiensCached[j].identifiant_user;
    }

      const formData = new FormData();

      formData.append('identifiant_user', this.state.identifiant_user);
      formData.append('heuredebut', this.state.tranchesC[0].startC);
      formData.append('heurefin', this.state.tranchesC[0].endC);
      formData.append('libelleconge', this.state.libelle);
      axios({
        method: 'post',
        url: process.env.REACT_APP_API_BACKEND+'add_event_docteur',
        data: formData,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        }
      })
      .then(() => {
        fetch(process.env.REACT_APP_API_BACKEND+'get_liste_planning/start='+moment().startOf('isoweek').subtract(14,'days').toJSON()+'&end='+moment().endOf('isoweek').add(2,'months').toJSON()+'&identifiant_user='+this.state.identifiant_user)
          .then(Response => Response.json())
          .then(data => {
            let evts = data.ListeResult;
            for (let i = 0; i < evts.length; i++) {
              evts[i].start = moment(evts[i].start).toDate();
              evts[i].end = moment(evts[i].end).toDate();
              this.state.events.push(evts[i])
            }
            this.setState({
              events:  this.state.events
            }, ()=> {
              localStorage.setItem('Liste récente de planning de ' + this.state.nom_user, JSON.stringify(this.state.events));
              localStorage.removeItem("Liste de planning de " + this.state.nom_user);
              localStorage.setItem("Liste de planning de " + this.state.nom_user, JSON.stringify(this.state.events));
            })
          })
       })
}

render() {

    return (

    <Dialog
        icon="application"
        onClose={this.handleClose}
        title="Organisation des plannings du docteur"
        {...this.state}
        isOpen={this.state.openPopupAjout}>
           <Input id="libelle" style={{ width: '480px' }} value={this.state.libelle} onChange={this.handleInputChange('libelle')}/>
            Date
            <LocaleProvider locale={fr_FR}>
                <RangePicker id="date" name= "date"  locale="fr" placeholder={["Date de début","Date de fin"]} separator="-" onChange={this.handleDateCChange}
                    value={this.state.dateIC} format="DD/MM/YYYY" allowClear={false}/>
            </LocaleProvider>
             Heure de début
            <Time value={el.startC} onChange={time => this.handleKeyboardStartCChange(i, time)} style={heure} disableUnderline={true} inputComponent={TextMaskCustom}
                    endAdornment={ <InputAdornment position="end" style={{opacity:'0.4'}}> <IconButton   onClick={() => this.openDialogC(i, el.startC, "startC")}></IconButton>  </InputAdornment>}
            />
             Heure de fin
            <Time value={el.endC} onChange={time => this.handleKeyboardEndCChange(i, time)} style={heure} disableUnderline={true} inputComponent={TextMaskCustom}
                    endAdornment={ <InputAdornment position="end" style={{opacity:'0.4'}}> <IconButton  onClick={() => this.openDialogC(i, el.endC, "endC")}></IconButton></InputAdornment> }/>

            <Clock maxWidth="xs" open={this.state.isOpenC} onBackdropClick={this.closeDialogC}>
            <TimePicker  mode="24h" value={this.createDateFromTextValueC(this.state.datePickerValueC)} onChange={this.handleDialogCChange}/>
            <DialogActions> <ButtonOk onClick={this.closeDialogC} color="primary"> Ok </ButtonOk></DialogActions>
            </Clock>
                <AnchorButton style={{display:'inline-block'}} intent={Intent.SUCCESS} onClick={this.handleValider}>Valider</AnchorButton>

);
}}

I want to refresh the list of my events and appear my  event added on the calendar afer post form on the popup and not after the  refresh of the page and I will reselect the doctor.

How can I fix it ?

Body:
I think, you can achieve it using code like this:

export default ComponentA extends Component {
  // set localStorage to bar state value
  // via click or whatever ...
    foo () {
    this.setState({
      bar: localStorage.getItem('bar')
    })
  }

  render () {
    // send the value of state to ComponentB
    return <ComponentB foo={this.state.bar}>
  }
}

Into your component

export default class ComponentB extends Component {
    render () {
    // display the value of foo prop
    return <div>{this.props.foo}</div>
  }
}

Note: You can always try to get the content of your localStoragedirectly from the ComponentB(Maybe using ComponentDidUpdate???) but the way I show you is better.


问:
Cannot convert value of type 'URL?' to expected argument type 'Data'
I am trying to build a video recorder app where after recording a video, I can upload the file to aws S3. I am having problems using the uploadData() function inside my video recording app.

I'm using the camerakit-ios library (https://github.com/CameraKit/camerakit-ios) and the aws-amplify ios library.

I modified the handleSave function by using it to call another function uploadData(), which I referenced from here (https://aws-amplify.github.io/docs/ios/storage).

I'm receiving an error Cannot convert value of type 'URL?' to expected argument type 'Data' in my handleSave() function. I know that it's because the format is wrong, but I'm really new to using the iOS and AWS S3 libraries together. How should I implement this?

```<code>class VideoPreviewViewController: UIViewController {

    ...

    @IBAction func handleSave(_ sender: Any) {
        if let url = self.url {
            uploadData(data: self.url) //ERROR: Cannot convert value of type 'URL?' to expected argument type 'Data'
        }
    }

    func uploadData(data: Data) {

//        let data: Data = Data() // Data to be uploaded

        let expression = AWSS3TransferUtilityUploadExpression()
        expression.progressBlock = {(task, progress) in
            DispatchQueue.main.async(execute: {
                // Do something e.g. Update a progress bar.
            })
        }

        var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
        completionHandler = { (task, error) -> Void in
            DispatchQueue.main.async(execute: {
                // Do something e.g. Alert a user for transfer completion.
                // On failed uploads, `error` contains the error object.
            })
        }

        let transferUtility = AWSS3TransferUtility.default()

        transferUtility.uploadData(data,
                                   bucket: "YourBucket",
                                   key: "YourFileName",
                                   contentType: "text/plain",
                                   expression: expression,
                                   completionHandler: completionHandler).continueWith {
                                    (task) -> AnyObject! in
                                    if let error = task.error {
                                        print("Error: \(error.localizedDescription)")
                                    }

                                    if let _ = task.result {
                                        // Do something with uploadTask.
                                    }
                                    return nil;
        }
    }
}

</code>```

答:
You have to get the Data from the URL

```<code>   if let url = self.url,
      let data = try? Data(contentsOf: url) {
         uploadData(data: data)
    }
</code>```

This syntax is reasonable if the URL is local, for a remote URL you need an asynchronous API.

Body:
I am trying to build a video recorder app where after recording a video, I can upload the file to aws S3. I am having problems using the uploadData() function inside my video recording app.

I'm using the camerakit-ios library (https://github.com/CameraKit/camerakit-ios) and the aws-amplify ios library.

I modified the handleSave function by using it to call another function uploadData(), which I referenced from here (https://aws-amplify.github.io/docs/ios/storage).

I'm receiving an error Cannot convert value of type 'URL?' to expected argument type 'Data' in my handleSave() function. I know that it's because the format is wrong, but I'm really new to using the iOS and AWS S3 libraries together. How should I implement this?

class VideoPreviewViewController: UIViewController {

    ...

    @IBAction func handleSave(_ sender: Any) {
        if let url = self.url {
            uploadData(data: self.url) //ERROR: Cannot convert value of type 'URL?' to expected argument type 'Data'
        }
    }

    func uploadData(data: Data) {

//        let data: Data = Data() // Data to be uploaded

        let expression = AWSS3TransferUtilityUploadExpression()
        expression.progressBlock = {(task, progress) in
            DispatchQueue.main.async(execute: {
                // Do something e.g. Update a progress bar.
            })
        }

        var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
        completionHandler = { (task, error) -> Void in
            DispatchQueue.main.async(execute: {
                // Do something e.g. Alert a user for transfer completion.
                // On failed uploads, `error` contains the error object.
            })
        }

        let transferUtility = AWSS3TransferUtility.default()

        transferUtility.uploadData(data,
                                   bucket: "YourBucket",
                                   key: "YourFileName",
                                   contentType: "text/plain",
                                   expression: expression,
                                   completionHandler: completionHandler).continueWith {
                                    (task) -> AnyObject! in
                                    if let error = task.error {
                                        print("Error: \(error.localizedDescription)")
                                    }

                                    if let _ = task.result {
                                        // Do something with uploadTask.
                                    }
                                    return nil;
        }
    }
}

Body:
You have to get the Data from the URL

   if let url = self.url,
      let data = try? Data(contentsOf: url) {
         uploadData(data: data)
    }

This syntax is reasonable if the URL is local, for a remote URL you need an asynchronous API.