问:
How to make a list of lists?
Is there some way to create a list of lists in Python?  Analogous to zeroes or similar functions.

What I am thinking of is something like this (pseudocode to follow):

```<code>def listoflists(nlists, nitems, fill)
    ...

listoflists(2,3, -1) # returns [[-1,-1,-1],[-1,-1,-1]]
</code>```

答:
This should work, thanks!   </p>

```<code>def listoflists(nlists, nitems, fill):
    f_list = []
    for i in range(nlists):
        n_list = []
        for j in range(nitems):
            n_list.append(fill)
        f_list.append(n_list)
        n_list = []
    return f_list

print(listoflists(2,3,-1))
</code>```

Title: How to make a list of lists?

Body:
Is there some way to create a list of lists in Python?  Analogous to zeroes or similar functions.

What I am thinking of is something like this (pseudocode to follow):

def listoflists(nlists, nitems, fill)
    ...

listoflists(2,3, -1) # returns [[-1,-1,-1],[-1,-1,-1]]

Body:
This should work, thanks!

def listoflists(nlists, nitems, fill):
    f_list = []
    for i in range(nlists):
        n_list = []
        for j in range(nitems):
            n_list.append(fill)
        f_list.append(n_list)
        n_list = []
    return f_list

print(listoflists(2,3,-1))


来源: stackexchange

问:
Exit from a command if it takes too much time in powershell
```<code>$uri="http:\\www.SomeUrl.com"
Measure-Command { $request = Invoke-WebRequest -Uri $uri -UseBasicParsing}
</code>```

In above powershell script, how can I exit from Invoke-WebRequest if it takes time more than 10 secs, and return a error code if possible.

答:
You can use the Timeout parameter to the Invoke-WebRequest command,

```<code>$uri="http://www.SomeUrl.com"
Measure-Command { $request = Invoke-WebRequest -Uri $uri -UseBasicParsing -Timeout 10}
</code>```

You can cover it with try / catch block to get the error message.

```<code>try {
    $uri="http://www.SomeUrl.com"
    Measure-Command { $request = Invoke-WebRequest -Uri $uri -UseBasicParsing -Timeout 10 -ErrorAction Stop}
}
catch {
    Write-Output "Timeout occured. Exception: $_"
}
</code>```

You can also use -Headers @{"Cache-Control"="no-cache"} with Invoke-WebRequest which will not cache the pages you are visiting.

ContentLicense: CC BY-SA 4.0

Body:
$uri="http:\\www.SomeUrl.com"
Measure-Command { $request = Invoke-WebRequest -Uri $uri -UseBasicParsing}

In above powershell script, how can I exit from Invoke-WebRequest if it takes time more than 10 secs, and return a error code if possible.

Body:
You can use the Timeout parameter to the Invoke-WebRequest command,

$uri="http://www.SomeUrl.com"
Measure-Command { $request = Invoke-WebRequest -Uri $uri -UseBasicParsing -Timeout 10}

You can cover it with try / catch block to get the error message.

try {
    $uri="http://www.SomeUrl.com"
    Measure-Command { $request = Invoke-WebRequest -Uri $uri -UseBasicParsing -Timeout 10 -ErrorAction Stop}
}
catch {
    Write-Output "Timeout occured. Exception: $_"
}

You can also use -Headers @{"Cache-Control"="no-cache"} with Invoke-WebRequest which will not cache the pages you are visiting.


问:
javascript window redirect doesn't work in chrome ((canceled) - status )
I'm trying to do a redirect using the below code:

```<code><script  type="text/javascript">
window.location.href = "http://google.com"
</script>
</code>```

FF and IE work as they should. Chrome doesn't.

The request above to http://google.com, gets a 'canceled' status in Chrome browser > Development tools >  "Network".

I've tried several other functions:

```<code>location.href = url
location.replace(url)
document.location = url
location.assign(url)
window.open(url, '_self')
</code>```

Same code pasted within a local html file works fine.

Below is the redirect request that it's canceled by chrome: http://pastebin.com/hD36M1RG

Any clues?
Thanks

答: using setTimeout worked for me, and i'm facing this problem with vue-router, tring to redirect to an auth page in 'beforeEach' hook.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to do a redirect using the below code:

FF and IE work as they should. Chrome doesn't.

The request above to http://google.com, gets a 'canceled' status in Chrome browser > Development tools >  "Network".

I've tried several other functions:

location.href = url
location.replace(url)
document.location = url
location.assign(url)
window.open(url, '_self')

Same code pasted within a local html file works fine.

Below is the redirect request that it's canceled by chrome: http://pastebin.com/hD36M1RG

Any clues?
Thanks


问:
How to disable specific dates in react-native-datetime-picker?
Dates can be disabled in react-day-picker, but i could not find a way to disable specific dates in react-native-datetime-picker. It is possible to disable a range of dates but not a specific date.
Is it possible to disable certain dates in the react-native-datetime-picker?</p>

答:
You can't use react-native-date-picker for this. but there is library available for this . it is react-native-calendars . Following snippet will give you the idea how to do it.

```<code>const vacation = {key:'vacation', color: 'red', selectedDotColor: 'blue'};
const massage = {key:'massage', color: 'blue', selectedDotColor: 'blue'};
const workout = {key:'workout', color: 'green'};

<Calendar
  markedDates={{
    '2017-10-25': {dots: [vacation, massage, workout], selected: true, selectedColor: 'red'},
    '2017-10-26': {dots: [massage, workout], disabled: true}
  }}
  markingType={'multi-dot'}
/>
</code>```

For more info react-native-calendars

Body:
You can't use react-native-date-picker for this. but there is library available for this . it is react-native-calendars . Following snippet will give you the idea how to do it.

const vacation = {key:'vacation', color: 'red', selectedDotColor: 'blue'};
const massage = {key:'massage', color: 'blue', selectedDotColor: 'blue'};
const workout = {key:'workout', color: 'green'};

<Calendar
  markedDates={{
    '2017-10-25': {dots: [vacation, massage, workout], selected: true, selectedColor: 'red'},
    '2017-10-26': {dots: [massage, workout], disabled: true}
  }}
  markingType={'multi-dot'}
/>

For more info react-native-calendars


问:
Longest sub string and its length without repeated chars
```<code>def findLongestSubstring(string):
  st = 0  # starting point of current substring.
  maxlen = 0 # maximum length substring without repeating characters.
  start = 0 # starting index of maximum length substring.
  pos = {} # Hash Map to store last occurrence of each already visited character
  pos[string[0]] = 0 #Last occurrence of first character is index 0

  for i in range(1, len(string)):
    # If this character is not present in hash, character, store this in hash.
    if string[i] not in pos:
      pos[string[i]] = i
    else:
      # If this character is present in hash then check if that occurrence
      # is before or after starting point of current substring.
      if pos[string[i]] >= st:
                # find length of current substring and update maxlen and start accordingly.
        currlen = i - st
        if maxlen < currlen:
          maxlen = currlen
          start = st

        # Next substring will start after the last occurrence of current
        # character to avoid its repetition.
        st = pos[string[i]] + 1

      pos[string[i]] = i # Update last occurrence of current character.

  # Compare length of last substring with maxlen & update maxlen and start accordingly.
  if maxlen < i - st:
    maxlen = i - st
    start = st

  # The required longest substring without repeating characters is from string[start]
  #to string[start+maxlen-1].
  print("Lenth is:", len(string[start : start + maxlen]) )
  print( string[start : start + maxlen] )
  return string[start : start + maxlen]
</code>```

<p>Above code works for the most part. But for below test case, it fail. What am I doing wrong? Code was copied from GeeksforGeeks. Code is returning "ba", instead of "bad". </p>

```<code>assert(findLongestSubstring("babad") == "bad" )
</code>```

答:
Your last length check should work if you increment i by 1.

```<code>  # Compare length of last substring with maxlen & update maxlen and start accordingly.
  if maxlen < (i + 1) - st:
    maxlen = (i + 1) - st
    start = st
</code>```

Body:
def findLongestSubstring(string):
  st = 0  # starting point of current substring.
  maxlen = 0 # maximum length substring without repeating characters.
  start = 0 # starting index of maximum length substring.
  pos = {} # Hash Map to store last occurrence of each already visited character
  pos[string[0]] = 0 #Last occurrence of first character is index 0

  for i in range(1, len(string)):
    # If this character is not present in hash, character, store this in hash.
    if string[i] not in pos:
      pos[string[i]] = i
    else:
      # If this character is present in hash then check if that occurrence
      # is before or after starting point of current substring.
      if pos[string[i]] >= st:
                # find length of current substring and update maxlen and start accordingly.
        currlen = i - st
        if maxlen < currlen:
          maxlen = currlen
          start = st

        # Next substring will start after the last occurrence of current
        # character to avoid its repetition.
        st = pos[string[i]] + 1

      pos[string[i]] = i # Update last occurrence of current character.

  # Compare length of last substring with maxlen & update maxlen and start accordingly.
  if maxlen < i - st:
    maxlen = i - st
    start = st

  # The required longest substring without repeating characters is from string[start]
  #to string[start+maxlen-1].
  print("Lenth is:", len(string[start : start + maxlen]) )
  print( string[start : start + maxlen] )
  return string[start : start + maxlen]

Above code works for the most part. But for below test case, it fail. What am I doing wrong? Code was copied from GeeksforGeeks. Code is returning "ba", instead of "bad".

assert(findLongestSubstring("babad") == "bad" )

Body:
Your last length check should work if you increment i by 1.

  # Compare length of last substring with maxlen & update maxlen and start accordingly.
  if maxlen < (i + 1) - st:
    maxlen = (i + 1) - st
    start = st


问:
<input type="file"> accept by extensions not work
I used accept to limit selected file type.

but sometimes it failed, e.g. this m4v file.

http://sites.lafayette.edu/newquisk/files/2011/08/ken-video.m4v

```<code><label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile" accept=".mp4">
</code>```

I thought this setting can only accept *.mp4 file.

but the m4v file is selectable under this condition.

althought type of this file is video/mp4 but doesn't it filter by extension?

I can ignore this file by JavaScript, but I still want to find a way to make this kinds of file are not selectable in file select popup?

答:
Since m4v file has the same type with mp4 file, you may want to check file name instead of file type:

var element = document.querySelector('#myfile');

element.addEventListener('change', function () {
  var file = this.files[0];
  if (!file) return;

  // if you select m4v file, file.type should be "video/mp4"

  if (file.name.endsWith('.mp4')) {
    console.log(file);
  } else {
    console.log('not ends with .mp4');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="file" id="myfile" name="myfile" accept=".mp4"></code>```

Body:
I used accept to limit selected file type.

but sometimes it failed, e.g. this m4v file.

http://sites.lafayette.edu/newquisk/files/2011/08/ken-video.m4v

Select a file:
<input type="file" id="myfile" name="myfile" accept=".mp4">

I thought this setting can only accept *.mp4 file.

but the m4v file is selectable under this condition.

althought type of this file is video/mp4 but doesn't it filter by extension?

I can ignore this file by JavaScript, but I still want to find a way to make this kinds of file are not selectable in file select popup?

Body:
Since m4v file has the same type with mp4 file, you may want to check file name instead of file type:

var element = document.querySelector('#myfile');

element.addEventListener('change', function () {
  var file = this.files[0];
  if (!file) return;

  // if you select m4v file, file.type should be "video/mp4"

  if (file.name.endsWith('.mp4')) {
    console.log(file);
  } else {
    console.log('not ends with .mp4');
  }
});

<input type="file" id="myfile" name="myfile" accept=".mp4">


问:
PowerShell Where-Object like multiple string values
I'm using the following in a do-until block to loop until a specified Exchange Online migration status is present:

```<code>(Get-Migrationbatch -Identity $MigrationBatchName | Where {$_.Status -like "Completed" -or "CompletedWithErrors" -or "Corrupted" -or "Failed" -or "Stopped"})
</code>```

However, the above still returns a job with the status of "Syncing" and so continues the script regardless.

I've tried -match, -eq but still the same.

What am I missing?

答:
another option convert filter array to regex string...</p>

```<code>$filter_status = @("Completed", "CompletedWithErrors","Curropted","Failed", "Stopped")
(Get-Migrationbatch -Identity $MigrationBatchName | Where Status -Match ($filter_status -Join "|")
</code>```

Body:
I'm using the following in a do-until block to loop until a specified Exchange Online migration status is present:

(Get-Migrationbatch -Identity $MigrationBatchName | Where {$_.Status -like "Completed" -or "CompletedWithErrors" -or "Corrupted" -or "Failed" -or "Stopped"})

However, the above still returns a job with the status of "Syncing" and so continues the script regardless.

I've tried -match, -eq but still the same.

What am I missing?

Body:
another option convert filter array to regex string...

$filter_status = @("Completed", "CompletedWithErrors","Curropted","Failed", "Stopped")
(Get-Migrationbatch -Identity $MigrationBatchName | Where Status -Match ($filter_status -Join "|")


问:
React dnd broad not working on the typescript
I tried to using this react dnd  on the react typescript. sample  not working on the type script project , any one know how to do that correctly on the react typescript

```<code>import React, { Component } from 'react';
    import ReactDOM from 'react-dom';
    import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';

    // fake data generator
    const getItems = (count, offset = 0) =>
      Array.from({ length: count }, (v, k) => k).map(k => ({
        id: `item-${k + offset}`,
        content: `Item: ${k + offset}, Random value: ${Math.round(Math.random() * 100)}`,
        color: Math.random () > 0.66 ? 'pink': Math.random() > 0.5 ? 'lightgreen' : 'beige'
      }))

    // a little function to help us with reordering the result
    const reorder = (list, startIndex, endIndex) => {
      const result = Array.from(list)
      const [removed] = result.splice(startIndex, 1)
      result.splice(endIndex, 0, removed)
      return result
    }

    /**
     * Moves an item from one list to another list.
     */
    const move = (source, destination, droppableSource, droppableDestination) => {
      const sourceClone = Array.from(source)
      const destClone = Array.from(destination)
      const [removed] = sourceClone.splice(droppableSource.index, 1)

      destClone.splice(droppableDestination.index, 0, removed)

      const result = {}
      result[droppableSource.droppableId] = sourceClone
      result[droppableDestination.droppableId] = destClone

      return result
    }

    const grid = 4

    const getItemStyle = (isDragging, draggableStyle) => ({
      // some basic styles to make the items look a bit nicer
      userSelect: 'none',
      padding: grid * 2,
      margin: `0 0 ${grid}px 0`,

      // change background colour if dragging
      background: isDragging ? 'lightgreen' : 'lightgrey',

      // styles we need to apply on draggables
      ...draggableStyle
    })

    const getListStyle = isDraggingOver => ({
      background: isDraggingOver ? 'lightblue' : '#eee',
      padding: grid,
      margin: '3px',
      width: 250
    })

    class App extends Component {
      state = {
        list1: getItems(5,1),
        list2: getItems(4, 6),
        list3: getItems(6, 10)
      }

      /**
       * A semi-generic way to handle multiple lists. Matches
       * the IDs of the droppable container to the names of the
       * source arrays stored in the state.
       */
      droppableIds = {
        droppable1: 'list1',
        droppable2: 'list2',
        droppable3: 'list3'
      }

      getList = id => this.state[this.droppableIds[id]]

      onDragEnd = result => {
        const { source, destination } = result

        // dropped outside the list
        if (!destination) { return }

        if (source.droppableId === destination.droppableId) {
          const items = reorder(
            this.getList(source.droppableId),
            source.index,
            destination.index
          )

          let copiedState = Object.assign({}, this.state)

          if (source.droppableId === 'droppable1') {
            copiedState.list1 = items
          } else if (source.droppableId === 'droppable2') {
            copiedState.list2 = items
          } else if (source.droppableId === 'droppable3') {
            copiedState.list3 = items
          }

          this.setState(copiedState)
        } else {
          const result = move(
            this.getList(source.droppableId),
            this.getList(destination.droppableId),
            source,
            destination
          )

          console.warn('result', result)
          this.setState({
            list1: result.droppable1 ? result.droppable1 : this.state.list1,
            list2: result.droppable2 ? result.droppable2 : this.state.list2,
            list3: result.droppable3 ? result.droppable3 : this.state.list3
          })
        }
      }

      // Normally you would want to split things out into separate components.
      // But in this example everything is just done in one place for simplicity
      render() {
        const lists = [
          {
            droppableId: 'droppable1',
            listId: 'list1',
            title: 'List A'
          },
          {
            droppableId: 'droppable2',
            listId: 'list2',
            title: 'List B'
          },
          {
            droppableId: 'droppable3',
            listId: 'list3',
            title: 'List C'
          },
        ]
        return (
          <div style={{ display: 'flex' }}>
            <DragDropContext onDragEnd={this.onDragEnd}>

              {lists.map((list, listIndex) =>
                <Droppable key={'list-droppable-' + listIndex} droppableId={list.droppableId}>
                  {(provided, snapshot) => (
                    <div
                      ref={provided.innerRef}
                      style={getListStyle(snapshot.isDraggingOver)}>
                      <h4>
                        {list.title}
                      </h4>
                      {this.state[list.listId] && this.state[list.listId].map((item, index) => (
                        <Draggable
                          key={item.id}
                          draggableId={item.id}
                          index={index}>
                          {(provided, snapshot) => (
                            <div
                              ref={provided.innerRef}
                              { ...provided.draggableProps }
                              { ...provided.dragHandleProps }
                              style={getItemStyle(
                                snapshot.isDragging,
                                provided.draggableProps.style
                              )}>
                              <div style={{ background: item.color }}>
                                {item.content}
                              </div>
                            </div>
                          )}
                        </Draggable>
                      ))}
                      {provided.placeholder}
                    </div>
                  )}
                </Droppable>
              )}
            </DragDropContext>
          </div>
        )
      }
    }

    // Put the things into the DOM!
    ReactDOM.render(<App />, document.getElementById('root'));
</code>```

答:
Try something like this.

```<code>import React, { Component } from "react";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";

// fake data generator
const getItems = (count: number, offset: number): object =>
  Array.from({ length: count }, (v, k): number => k).map(
    (k: number): {} => ({
      id: `item-${k + offset}`,
      content: `Item: ${k + offset}, Random value: ${Math.round(
        Math.random() * 100
      )}`,
      color:
        Math.random() > 0.66
          ? "pink"
          : Math.random() > 0.5
          ? "lightgreen"
          : "beige"
    })
  );

// a little function to help us with reordering the result
const reorder = (list: [], startIndex: number, endIndex: number): object => {
  const result = Array.from(list);
  const [removed] = result.splice(startIndex, 1);
  result.splice(endIndex, 0, removed);
  return result;
};

/**
 * Moves an item from one list to another list.
 */
const move = (
  source: any,
  destination: any,
  droppableSource: any,
  droppableDestination: any
): {} => {
  const sourceClone = Array.from(source);
  const destClone = Array.from(destination);
  const [removed] = sourceClone.splice(droppableSource.index, 1);

  destClone.splice(droppableDestination.index, 0, removed);

  let result: any = {};
  result[droppableSource.droppableId] = sourceClone;
  result[droppableDestination.droppableId] = destClone;

  return result;
};

const grid = 4;

const getItemStyle = (isDragging: boolean, draggableStyle: any): object => ({
  // some basic styles to make the items look a bit nicer
  userSelect: "none",
  padding: grid * 2,
  margin: `0 0 ${grid}px 0`,

  // change background colour if dragging
  background: isDragging ? "lightgreen" : "lightgrey",

  // styles we need to apply on draggables
  ...draggableStyle
});

const getListStyle = (isDraggingOver: boolean): object => ({
  background: isDraggingOver ? "lightblue" : "#eee",
  padding: grid,
  margin: "3px",
  width: 250
});

interface State {
  list1: object;
  list2: object;
  list3: object;
}

class App extends Component<State> {
  state: State = {
    list1: getItems(5, 1),
    list2: getItems(4, 6),
    list3: getItems(6, 10)
  };

  /**
   * A semi-generic way to handle multiple lists. Matches
   * the IDs of the droppable container to the names of the
   * source arrays stored in the state.
   */
  droppableIds = {
    droppable1: "list1",
    droppable2: "list2",
    droppable3: "list3"
  };

  getList = (id: string): any => this.state[this.droppableIds[id]];

  onDragEnd = (result: any) => {
    const { source, destination } = result;

    // dropped outside the list
    if (!destination) {
      return;
    }

    if (source.droppableId === destination.droppableId) {
      const items: object = reorder(
        this.getList(source.droppableId),
        source.index,
        destination.index
      );

      let copiedState: any = Object.assign({}, this.state);

      if (source.droppableId === "droppable1") {
        copiedState.list1 = items;
      } else if (source.droppableId === "droppable2") {
        copiedState.list2 = items;
      } else if (source.droppableId === "droppable3") {
        copiedState.list3 = items;
      }

      this.setState(copiedState);
    } else {
      const result: any = move(
        this.getList(source.droppableId),
        this.getList(destination.droppableId),
        source,
        destination
      );

      this.setState({
        list1: result.droppable1 ? result.droppable1 : this.state.list1,
        list2: result.droppable2 ? result.droppable2 : this.state.list2,
        list3: result.droppable3 ? result.droppable3 : this.state.list3
      });
    }
  };
  render() {
    const lists = [
      {
        droppableId: "droppable1",
        listId: "list1",
        title: "List A"
      },
      {
        droppableId: "droppable2",
        listId: "list2",
        title: "List B"
      },
      {
        droppableId: "droppable3",
        listId: "list3",
        title: "List C"
      }
    ];
    return (
      <div style={{ display: "flex" }}>
        <DragDropContext onDragEnd={this.onDragEnd}>
          {lists.map((list, listIndex) => (
            <Droppable
              key={"list-droppable-" + listIndex}
              droppableId={list.droppableId}
            >
              {(provided: any, snapshot: any) => (
                <div
                  ref={provided.innerRef}
                  style={getListStyle(snapshot.isDraggingOver)}
                >
                  <h4>{list.title}</h4>
                  {this.state[list.listId] &&
                    this.state[list.listId].map((item: any, index: number) => (
                      <Draggable
                        key={item.id}
                        draggableId={item.id}
                        index={index}
                      >
                        {(provided: any, snapshot: any) => (
                          <div
                            ref={provided.innerRef}
                            {...provided.draggableProps}
                            {...provided.dragHandleProps}
                            style={getItemStyle(
                              snapshot.isDragging,
                              provided.draggableProps.style
                            )}
                          >
                            <div style={{ background: item.color }}>
                              {item.content}
                            </div>
                          </div>
                        )}
                      </Draggable>
                    ))}
                  {provided.placeholder}
                </div>
              )}
            </Droppable>
          ))}
        </DragDropContext>
      </div>
    );
  }
}

export default App;
</code>```

And here is a working example codesandox

Body:
I tried to using this react dnd  on the react typescript. sample  not working on the type script project , any one know how to do that correctly on the react typescript

import React, { Component } from 'react';
    import ReactDOM from 'react-dom';
    import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';

    // fake data generator
    const getItems = (count, offset = 0) =>
      Array.from({ length: count }, (v, k) => k).map(k => ({
        id: `item-${k + offset}`,
        content: `Item: ${k + offset}, Random value: ${Math.round(Math.random() * 100)}`,
        color: Math.random () > 0.66 ? 'pink': Math.random() > 0.5 ? 'lightgreen' : 'beige'
      }))

    // a little function to help us with reordering the result
    const reorder = (list, startIndex, endIndex) => {
      const result = Array.from(list)
      const [removed] = result.splice(startIndex, 1)
      result.splice(endIndex, 0, removed)
      return result
    }

    /**
     * Moves an item from one list to another list.
     */
    const move = (source, destination, droppableSource, droppableDestination) => {
      const sourceClone = Array.from(source)
      const destClone = Array.from(destination)
      const [removed] = sourceClone.splice(droppableSource.index, 1)

      destClone.splice(droppableDestination.index, 0, removed)

      const result = {}
      result[droppableSource.droppableId] = sourceClone
      result[droppableDestination.droppableId] = destClone

      return result
    }

    const grid = 4

    const getItemStyle = (isDragging, draggableStyle) => ({
      // some basic styles to make the items look a bit nicer
      userSelect: 'none',
      padding: grid * 2,
      margin: `0 0 ${grid}px 0`,

      // change background colour if dragging
      background: isDragging ? 'lightgreen' : 'lightgrey',

      // styles we need to apply on draggables
      ...draggableStyle
    })

    const getListStyle = isDraggingOver => ({
      background: isDraggingOver ? 'lightblue' : '#eee',
      padding: grid,
      margin: '3px',
      width: 250
    })

    class App extends Component {
      state = {
        list1: getItems(5,1),
        list2: getItems(4, 6),
        list3: getItems(6, 10)
      }

      /**
       * A semi-generic way to handle multiple lists. Matches
       * the IDs of the droppable container to the names of the
       * source arrays stored in the state.
       */
      droppableIds = {
        droppable1: 'list1',
        droppable2: 'list2',
        droppable3: 'list3'
      }

      getList = id => this.state[this.droppableIds[id]]

      onDragEnd = result => {
        const { source, destination } = result

        // dropped outside the list
        if (!destination) { return }

        if (source.droppableId === destination.droppableId) {
          const items = reorder(
            this.getList(source.droppableId),
            source.index,
            destination.index
          )

          let copiedState = Object.assign({}, this.state)

          if (source.droppableId === 'droppable1') {
            copiedState.list1 = items
          } else if (source.droppableId === 'droppable2') {
            copiedState.list2 = items
          } else if (source.droppableId === 'droppable3') {
            copiedState.list3 = items
          }

          this.setState(copiedState)
        } else {
          const result = move(
            this.getList(source.droppableId),
            this.getList(destination.droppableId),
            source,
            destination
          )

          console.warn('result', result)
          this.setState({
            list1: result.droppable1 ? result.droppable1 : this.state.list1,
            list2: result.droppable2 ? result.droppable2 : this.state.list2,
            list3: result.droppable3 ? result.droppable3 : this.state.list3
          })
        }
      }

      // Normally you would want to split things out into separate components.
      // But in this example everything is just done in one place for simplicity
      render() {
        const lists = [
          {
            droppableId: 'droppable1',
            listId: 'list1',
            title: 'List A'
          },
          {
            droppableId: 'droppable2',
            listId: 'list2',
            title: 'List B'
          },
          {
            droppableId: 'droppable3',
            listId: 'list3',
            title: 'List C'
          },
        ]
        return (

            <DragDropContext onDragEnd={this.onDragEnd}>

              {lists.map((list, listIndex) =>
                <Droppable key={'list-droppable-' + listIndex} droppableId={list.droppableId}>
                  {(provided, snapshot) => (

                        {list.title}

                      {this.state[list.listId] && this.state[list.listId].map((item, index) => (
                        <Draggable
                          key={item.id}
                          draggableId={item.id}
                          index={index}>
                          {(provided, snapshot) => (

                                {item.content}

                          )}
                        </Draggable>
                      ))}
                      {provided.placeholder}

                  )}
                </Droppable>
              )}
            </DragDropContext>

        )
      }
    }

    // Put the things into the DOM!
    ReactDOM.render(<App />, document.getElementById('root'));

Body:
Try something like this.

import React, { Component } from "react";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";

// fake data generator
const getItems = (count: number, offset: number): object =>
  Array.from({ length: count }, (v, k): number => k).map(
    (k: number): {} => ({
      id: `item-${k + offset}`,
      content: `Item: ${k + offset}, Random value: ${Math.round(
        Math.random() * 100
      )}`,
      color:
        Math.random() > 0.66
          ? "pink"
          : Math.random() > 0.5
          ? "lightgreen"
          : "beige"
    })
  );

// a little function to help us with reordering the result
const reorder = (list: [], startIndex: number, endIndex: number): object => {
  const result = Array.from(list);
  const [removed] = result.splice(startIndex, 1);
  result.splice(endIndex, 0, removed);
  return result;
};

/**
 * Moves an item from one list to another list.
 */
const move = (
  source: any,
  destination: any,
  droppableSource: any,
  droppableDestination: any
): {} => {
  const sourceClone = Array.from(source);
  const destClone = Array.from(destination);
  const [removed] = sourceClone.splice(droppableSource.index, 1);

  destClone.splice(droppableDestination.index, 0, removed);

  let result: any = {};
  result[droppableSource.droppableId] = sourceClone;
  result[droppableDestination.droppableId] = destClone;

  return result;
};

const grid = 4;

const getItemStyle = (isDragging: boolean, draggableStyle: any): object => ({
  // some basic styles to make the items look a bit nicer
  userSelect: "none",
  padding: grid * 2,
  margin: `0 0 ${grid}px 0`,

  // change background colour if dragging
  background: isDragging ? "lightgreen" : "lightgrey",

  // styles we need to apply on draggables
  ...draggableStyle
});

const getListStyle = (isDraggingOver: boolean): object => ({
  background: isDraggingOver ? "lightblue" : "#eee",
  padding: grid,
  margin: "3px",
  width: 250
});

interface State {
  list1: object;
  list2: object;
  list3: object;
}

class App extends Component<State> {
  state: State = {
    list1: getItems(5, 1),
    list2: getItems(4, 6),
    list3: getItems(6, 10)
  };

  /**
   * A semi-generic way to handle multiple lists. Matches
   * the IDs of the droppable container to the names of the
   * source arrays stored in the state.
   */
  droppableIds = {
    droppable1: "list1",
    droppable2: "list2",
    droppable3: "list3"
  };

  getList = (id: string): any => this.state[this.droppableIds[id]];

  onDragEnd = (result: any) => {
    const { source, destination } = result;

    // dropped outside the list
    if (!destination) {
      return;
    }

    if (source.droppableId === destination.droppableId) {
      const items: object = reorder(
        this.getList(source.droppableId),
        source.index,
        destination.index
      );

      let copiedState: any = Object.assign({}, this.state);

      if (source.droppableId === "droppable1") {
        copiedState.list1 = items;
      } else if (source.droppableId === "droppable2") {
        copiedState.list2 = items;
      } else if (source.droppableId === "droppable3") {
        copiedState.list3 = items;
      }

      this.setState(copiedState);
    } else {
      const result: any = move(
        this.getList(source.droppableId),
        this.getList(destination.droppableId),
        source,
        destination
      );

      this.setState({
        list1: result.droppable1 ? result.droppable1 : this.state.list1,
        list2: result.droppable2 ? result.droppable2 : this.state.list2,
        list3: result.droppable3 ? result.droppable3 : this.state.list3
      });
    }
  };
  render() {
    const lists = [
      {
        droppableId: "droppable1",
        listId: "list1",
        title: "List A"
      },
      {
        droppableId: "droppable2",
        listId: "list2",
        title: "List B"
      },
      {
        droppableId: "droppable3",
        listId: "list3",
        title: "List C"
      }
    ];
    return (
      <div style={{ display: "flex" }}>
        <DragDropContext onDragEnd={this.onDragEnd}>
          {lists.map((list, listIndex) => (
            <Droppable
              key={"list-droppable-" + listIndex}
              droppableId={list.droppableId}
            >
              {(provided: any, snapshot: any) => (
                <div
                  ref={provided.innerRef}
                  style={getListStyle(snapshot.isDraggingOver)}
                >
                  <h4>{list.title}</h4>
                  {this.state[list.listId] &&
                    this.state[list.listId].map((item: any, index: number) => (
                      <Draggable
                        key={item.id}
                        draggableId={item.id}
                        index={index}
                      >
                        {(provided: any, snapshot: any) => (
                          <div
                            ref={provided.innerRef}
                            {...provided.draggableProps}
                            {...provided.dragHandleProps}
                            style={getItemStyle(
                              snapshot.isDragging,
                              provided.draggableProps.style
                            )}
                          >
                            <div style={{ background: item.color }}>
                              {item.content}
                            </div>
                          </div>
                        )}
                      </Draggable>
                    ))}
                  {provided.placeholder}
                </div>
              )}
            </Droppable>
          ))}
        </DragDropContext>
      </div>
    );
  }
}

export default App;

And here is a working example codesandox


问:
How to pass function of one class as argument of another function of another class
I have created a class Base which has a function addSuccessor() that takes address of function as argument and stores it in successor. How do I pass a function of another object in addSuccessor().
Here is my program. I think my main() has some mistake.

```<code>#include <iostream>
#include<vector>
using namespace std;
class Base{
public:
    void (*successor)()=NULL;
    void addSuccessor ( void (*f)() )
    {
        successor=f;
    }
    void start()
    {
        cout<<"In Class"<<endl;
        if(!successor==NULL)
            successor();
        else
            cout<<"No Successor"<<endl;
    }
};
class Second{
    public:
    void foo()
    {
        cout<<"Successor";
    }
};

int main()
{
    Base obj;
    Second obj2;

    obj.addSuccessor(&obj2.foo());
    obj.start();

}
</code>```

答:
As a complement to the discussion above (based on @L.F.'s answer):</p>

```<code>#include <functional>
#include <iostream>
#include <utility>

class Base {
    std::function<int(int)> successor;
public:
    template <typename F>
    void add_successor(F&& f)
    {
        successor = std::forward<F>(f);
    }
    void start()
    {
        if (successor) {
            auto z = std::invoke(successor, 100);
            std::cout << "Output = " << z << "\n";
        } else {
            std::cout << "No Successor\n";
        }
    }
};

class Second {
public:
    int foo(int x)
    {
        auto y = x + x;
        std::cout << "Successor\n";
        return y;
    }
};

int main()
{
    Base obj;
    Second obj2;

    obj.add_successor([&](int x)->int { return obj2.foo(x); });
    obj.start();
}
</code>```

Body:
I have created a class Base which has a function addSuccessor() that takes address of function as argument and stores it in successor. How do I pass a function of another object in addSuccessor().
Here is my program. I think my main() has some mistake.

#include <iostream>
#include<vector>
using namespace std;
class Base{
public:
    void (*successor)()=NULL;
    void addSuccessor ( void (*f)() )
    {
        successor=f;
    }
    void start()
    {
        cout<<"In Class"<<endl;
        if(!successor==NULL)
            successor();
        else
            cout<<"No Successor"<<endl;
    }
};
class Second{
    public:
    void foo()
    {
        cout<<"Successor";
    }
};

int main()
{
    Base obj;
    Second obj2;

    obj.addSuccessor(&obj2.foo());
    obj.start();

}

Body:
As a complement to the discussion above (based on @L.F.'s answer):

#include <functional>
#include <iostream>
#include <utility>

class Base {
    std::function<int(int)> successor;
public:
    template <typename F>
    void add_successor(F&& f)
    {
        successor = std::forward<F>(f);
    }
    void start()
    {
        if (successor) {
            auto z = std::invoke(successor, 100);
            std::cout << "Output = " << z << "\n";
        } else {
            std::cout << "No Successor\n";
        }
    }
};

class Second {
public:
    int foo(int x)
    {
        auto y = x + x;
        std::cout << "Successor\n";
        return y;
    }
};

int main()
{
    Base obj;
    Second obj2;

    obj.add_successor([&](int x)->int { return obj2.foo(x); });
    obj.start();
}


问:
How to tell if the user already rated my UWP app?
Windows 10 Store UWP apps can use StoreContext.RequestRateAndReviewAppAsync function, or simply a URL like this ms-windows-store://review/?ProductId=9WZDNCRFHVJL, to display a user rating window for the app:

I prefer the URL method since I can simply invoke it via ShellExecute method.

But my question is how do I find out if the user had already rated my app, so that I don't display that rating window again?

答: This is unfortunately not possible, but there is probably a good reason for it - if developers were able to check this programmatically, they could "cheat the system" by giving users who rated some bonuses/perks for reviewing the app.</p>


问:
why are conditional comments implemented in IE?
less of how & more of a why question here...I tried searching around some & couldn't quite find the answer I was looking for.

I'm curious why conditional comments exist within IE? did Microsoft implement this into the different browser versions because they knew they were not standards compliant?

I know certain version of other browsers can be targeted using conditional comments but those for IE far outnumber any other browsers.

I'd be interested in hearing any info regarding the origin & history of conditional comments.

答:
They implemented it with ie5 and saw it as a good thing to optimise sites for IE.

Conditional comments have certain advantages over scripting methods of browser detection.

Low client-side impact.

When a downlevel browser encounters a downlevel-hidden conditional comment, the browser skips over the HTML inside the comment, and the content elements are not parsed, downloaded, or rendered. This saves client machine resources.

No script required.

Conditional comments do not require scripting and DHTML, and when no scripting is used in a Web page, no scripting engine needs to be loaded. Conditional comments are processed during the downloading and parsing phase, so only the content that is targeted for the browser is actually downloaded. Conditional comments can be combined freely with other browser detection techniques.

Separate code from detection logic.

Using conditional comments, script logic can be separated into smaller and simpler segments of code, which are easier to maintain and understand. Plus, code segments are loaded only by the browser version for which they were intended.

Cross-browser.

Conditional comments have been around since Internet Explorer 5, but their use is not restricted to Internet Explorer alone. Conditional comments can be used to customize content delivered to browsers that support conditional comments and those that do not.

more info: http://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx


问:
(Resolved)(type 'String' is not a subtype of type 'int') - Flutter
This question has already been answered, continue reading if you think you have the same error, the answer was given by the user: Tariqul Islam

since a few days ago there was a flutter update my code shows the following error:

_TypeError (type 'String' is not a subtype of type 'int')

Obviously the application worked perfectly before this update, even after changing from "int" to "String" the same error I get but the other way around:

_TypeError (type 'int' is not a subtype of type 'String')

As much as I change the values the same error still appears to me, it is also clear that the RestApi that I am using did not have any changes.

I get the error when I get to "Chip", after I change it to String I get the same error in "Number", and after I change both the same error appears but the other way around as I indicated above

Here the Json file model:

```<code>          class EventoModel {
        String id;
        String nombreEvento;
        List<Participantes> participantes;

        EventoModel({
          this.id,
          this.nombreEvento,
          this.participantes
        });

        factory EventoModel.fromJson(Map<String, dynamic> parsedJson){
          var list = parsedJson['participantes'] as List;
          //print(list.runtimeType);
          List<Participantes> participantesList = list.map((i) => Participantes.fromJson(i)).toList();
          return EventoModel(
            id            : parsedJson ['id'],
            nombreEvento  : parsedJson ['nombreEvento'],
            participantes : participantesList
          );
        }
      }

      class Participantes {
      String uniqueId;
      String apellido;
      int chip;
      String nombre;
      int numero;
      String place;
      String tiempo;

      Participantes({
        this.apellido,
        this.chip,
        this.nombre,
        this.numero,
        this.place,
        this.tiempo,
      });

      factory Participantes.fromJson(Map<String, dynamic> parsedJson) {
        //print(list.runtimeType);
        return Participantes(
          apellido  : parsedJson['Apellido'],
          chip      : parsedJson['Chip'],
          nombre    : parsedJson['Nombre'],
          numero    : parsedJson['Numero'],
          place     : parsedJson['Place'],
          tiempo    : parsedJson['Tiempo'],
        );
      }

      Map<String, dynamic> toJson() {
        return {
          'Apellido'  : apellido,
          'Chip'      : chip,
          'Nombre'    : nombre,
          'Numero'    : numero,
          'Place'     : place,
          'Tiempo'    : tiempo,
        };
      }
    }
</code>```

This is the Json file Example:

```<code>              {
              "nombreEvento" : "Clasico El Colombiano 2020",
              "participantes" : [ {
                "Apellido" : "MARTINEZ GUTIERREZ",
                "Chip" : "739",
                "Nombre" : "JOSE",
                "Numero" : "139",
                "Place" : "1.",
                "Tiempo" : "00:30:12,91"
                }, {
                "Apellido" : "SUAREZ MORERA",
                "Chip" : "707",
                "Nombre" : "DANIEL",
                "Numero" : "107",
                "Place" : "2.",
                "Tiempo" : "02:00:17,54"
                }, {
                "Apellido" : "RODRIGUEZ VARGAS",
                "Chip" : "1686",
                "Nombre" : "JOSE LUIS",
                "Numero" : "274",
                "Place" : "3.",
                "Tiempo" : "02:01:09,09"
                }
              ]
            }
</code>```

Could someone please help me? : c

答:
Just do int chip to String chip, and int numero to String numero because in your JSON data comes in String

```<code> class Participantes {
      String uniqueId;
      String apellido;
      String chip;
      String nombre;
      String numero;
      String place;
      String tiempo;

      Participantes({
        this.apellido,
        this.chip,
        this.nombre,
        this.numero,
        this.place,
        this.tiempo,
      });
</code>```

Body:
This question has already been answered, continue reading if you think you have the same error, the answer was given by the user: Tariqul Islam

since a few days ago there was a flutter update my code shows the following error:

_TypeError (type 'String' is not a subtype of type 'int')

Obviously the application worked perfectly before this update, even after changing from "int" to "String" the same error I get but the other way around:

_TypeError (type 'int' is not a subtype of type 'String')

As much as I change the values the same error still appears to me, it is also clear that the RestApi that I am using did not have any changes.

I get the error when I get to "Chip", after I change it to String I get the same error in "Number", and after I change both the same error appears but the other way around as I indicated above

Here the Json file model:

          class EventoModel {
        String id;
        String nombreEvento;
        List<Participantes> participantes;

        EventoModel({
          this.id,
          this.nombreEvento,
          this.participantes
        });

        factory EventoModel.fromJson(Map<String, dynamic> parsedJson){
          var list = parsedJson['participantes'] as List;
          //print(list.runtimeType);
          List<Participantes> participantesList = list.map((i) => Participantes.fromJson(i)).toList();
          return EventoModel(
            id            : parsedJson ['id'],
            nombreEvento  : parsedJson ['nombreEvento'],
            participantes : participantesList
          );
        }
      }

      class Participantes {
      String uniqueId;
      String apellido;
      int chip;
      String nombre;
      int numero;
      String place;
      String tiempo;

      Participantes({
        this.apellido,
        this.chip,
        this.nombre,
        this.numero,
        this.place,
        this.tiempo,
      });

      factory Participantes.fromJson(Map<String, dynamic> parsedJson) {
        //print(list.runtimeType);
        return Participantes(
          apellido  : parsedJson['Apellido'],
          chip      : parsedJson['Chip'],
          nombre    : parsedJson['Nombre'],
          numero    : parsedJson['Numero'],
          place     : parsedJson['Place'],
          tiempo    : parsedJson['Tiempo'],
        );
      }

      Map<String, dynamic> toJson() {
        return {
          'Apellido'  : apellido,
          'Chip'      : chip,
          'Nombre'    : nombre,
          'Numero'    : numero,
          'Place'     : place,
          'Tiempo'    : tiempo,
        };
      }
    }

This is the Json file Example:

              {
              "nombreEvento" : "Clasico El Colombiano 2020",
              "participantes" : [ {
                "Apellido" : "MARTINEZ GUTIERREZ",
                "Chip" : "739",
                "Nombre" : "JOSE",
                "Numero" : "139",
                "Place" : "1.",
                "Tiempo" : "00:30:12,91"
                }, {
                "Apellido" : "SUAREZ MORERA",
                "Chip" : "707",
                "Nombre" : "DANIEL",
                "Numero" : "107",
                "Place" : "2.",
                "Tiempo" : "02:00:17,54"
                }, {
                "Apellido" : "RODRIGUEZ VARGAS",
                "Chip" : "1686",
                "Nombre" : "JOSE LUIS",
                "Numero" : "274",
                "Place" : "3.",
                "Tiempo" : "02:01:09,09"
                }
              ]
            }

Could someone please help me? : c

Body:
Just do int chip to String chip, and int numero to String numero because in your JSON data comes in String

 class Participantes {
      String uniqueId;
      String apellido;
      String chip;
      String nombre;
      String numero;
      String place;
      String tiempo;

      Participantes({
        this.apellido,
        this.chip,
        this.nombre,
        this.numero,
        this.place,
        this.tiempo,
      });


答:
In Json you are receiving Chip and Numero as String but in your model file you are declaring as integer. change the datatype to String in your model file.</p>

```<code>String numero;
String chip;
</code>```

Title: (Resolved)(type 'String' is not a subtype of type 'int') - Flutter

Body:
In Json you are receiving Chip and Numero as String but in your model file you are declaring as integer. change the datatype to String in your model file.

String numero;
String chip;


问:
Why is my syntax wrong in my JOIN statement?
I have a simple SQL query with a where and a join. I tried to execute this command :
SELECT * FROM gym_service WHERE gym_id = ? JOIN services ON service_id = id. The ? is by the value in the code :

```<code>persistent.transaction(tx => {
            tx.executeSql('SELECT * FROM gym_service WHERE gym_id = ? JOIN services ON service_id = id', [gym.id],
            (t, s) => {
                console.log(s)
            }, (t, e) => {
                console.log(e)
            })
        })
</code>```

However, I always get this strange error : Error code 1: near "JOIN": syntax error

I believe everything is done properly, what is the issue with my code ?

答:
WHERE clause should be used after joining the tables.

For Joining tables use INNER JOIN, LEFT JOIN, RIGHT OUTER JOIN as per your need.

Below query will fulfill your above requirement.

SELECT *
FROM gym_service gs
INNER JOIN services s ON gs.service_id = s.id
WHERE gs.gym_id = ?

Body:
I have a simple SQL query with a where and a join. I tried to execute this command :
SELECT * FROM gym_service WHERE gym_id = ? JOIN services ON service_id = id. The ? is by the value in the code :

persistent.transaction(tx => {
            tx.executeSql('SELECT * FROM gym_service WHERE gym_id = ? JOIN services ON service_id = id', [gym.id],
            (t, s) => {
                console.log(s)
            }, (t, e) => {
                console.log(e)
            })
        })

However, I always get this strange error : Error code 1: near "JOIN": syntax error

I believe everything is done properly, what is the issue with my code ?


问:
Old cached image displays after clear local cache, want to display newly downloaded image from network
In my app I download an image from the network then save this image in local cache storage with a specific name such as test.jpeg, then I display the test.jpeg image in Android device.

If I clear local cache for the app in android settings, then again download new image from network and save the new image with the same name (test.jpeg). Then I display the image, I expect the new image should be displayed but it displayed the old image.

After killing the app and running it again then it displays the new image.

To download and save the image I use Dio library.

Here is sample code of download and save to local directory

```<code>Dio client;
String imageSavePath =
    path.join((await getTemporaryDirectory()).path, “test.jpeg”);
await  client.download(url, imageSavePath);
</code>```

So, how can I display newly downloaded image without closing the app.

答:
Please check below link https://api.flutter.dev/flutter/painting/imageCache.html

```<code>import 'package:flutter/services.dart';

imageCache.clear();
</code>```

It might works for you.

Body:
In my app I download an image from the network then save this image in local cache storage with a specific name such as test.jpeg, then I display the test.jpeg image in Android device.

If I clear local cache for the app in android settings, then again download new image from network and save the new image with the same name (test.jpeg). Then I display the image, I expect the new image should be displayed but it displayed the old image.

After killing the app and running it again then it displays the new image.

To download and save the image I use Dio library.

Here is sample code of download and save to local directory

Dio client;
String imageSavePath =
    path.join((await getTemporaryDirectory()).path, “test.jpeg”);
await  client.download(url, imageSavePath);

So, how can I display newly downloaded image without closing the app.

Body:
Please check below link https://api.flutter.dev/flutter/painting/imageCache.html

import 'package:flutter/services.dart';

imageCache.clear();

It might works for you.


问:
Update Hosts file with .bat file
I need to update my hosts file at our sites with 2 rules.

Ip address should be change from the current ip we have saved in hosts file:
111.111.111.111 -> 111.111.111.222

If there is no IP address that matches the 111.111.111.222 add it at the end of the line;

1st part works fine, but I can't seem to wrap my head around the 2nd rule...

currently what I have
.

```<code>@echo off

set newip=111.111.111.222

setlocal enabledelayedexpansion

for /f "delims=" %%A in (C:\Windows\System32\drivers\etc\hosts) do (

set line0=%%A

set line1=!line0:111.111.111.111=%newip%!

echo=!line1!>>C:\Windows\System32\drivers\hosts

)

endlocal

move /y C:\Windows\System32\hosts C:\Windows\System32\drivers\etc

pause
</code>```

How should I approach it?

答:
```<code>@echo off
setlocal

set "oldip=111.111.111.111"
set "newip=111.111.111.222"

pushd "%systemroot%\System32\drivers\etc" || (
    >&2 echo Failed to change directory.
    exit /b 1
)

if not exist "hosts" (
    >&2 echo Failed to find file named hosts.
    exit /b 1
)

(
    set "updated_entry="

    for /f "tokens=1*" %%A in (hosts) do @(
        if "%%~A" == "%oldip%" (
            echo %newip% %%B
            set "updated_entry=defined"
        ) else (
            if "%%~A" == "%newip%" set "updated_entry=defined"
            echo %%A %%B
        )
    )

    if not defined updated_entry echo %newip% ?domain?
) > "hosts.tmp"

move /y "hosts.tmp" "hosts"
if exist "hosts.tmp" del "hosts.tmp"
</code>```

Change to %systemroot%\System32\drivers\etc directory so the directory
with the hosts file is the current directory. Check if the hosts file
does exist to continue.

The for options of tokens=1* will store the ip address in %%A and
the remainder of the current line in %%B. Comparing the new ip address
with the ip address read is done with "%%~A" == "%oldip%".

If the update of the ip address is not done, as the variable named
updated_entry is defined if it has, then it will write it at the
end of the file. Not sure what domain to insert so using just ?domain?.

The new file with changes is hosts.tmp which is renamed to hosts.
hosts.tmp will be deleted if something fails, just to cleanup.

Title: Update Hosts file with .bat file

Body:
I need to update my hosts file at our sites with 2 rules.

Ip address should be change from the current ip we have saved in hosts file:
111.111.111.111 -> 111.111.111.222

If there is no IP address that matches the 111.111.111.222 add it at the end of the line;

1st part works fine, but I can't seem to wrap my head around the 2nd rule...

currently what I have
.

@echo off

set newip=111.111.111.222

setlocal enabledelayedexpansion

for /f "delims=" %%A in (C:\Windows\System32\drivers\etc\hosts) do (

set line0=%%A

set line1=!line0:111.111.111.111=%newip%!

echo=!line1!>>C:\Windows\System32\drivers\hosts

)

endlocal

move /y C:\Windows\System32\hosts C:\Windows\System32\drivers\etc

pause

How should I approach it?

Body:
@echo off
setlocal

set "oldip=111.111.111.111"
set "newip=111.111.111.222"

pushd "%systemroot%\System32\drivers\etc" || (
    >&2 echo Failed to change directory.
    exit /b 1
)

if not exist "hosts" (
    >&2 echo Failed to find file named hosts.
    exit /b 1
)

(
    set "updated_entry="

    for /f "tokens=1*" %%A in (hosts) do @(
        if "%%~A" == "%oldip%" (
            echo %newip% %%B
            set "updated_entry=defined"
        ) else (
            if "%%~A" == "%newip%" set "updated_entry=defined"
            echo %%A %%B
        )
    )

    if not defined updated_entry echo %newip% ?domain?
) > "hosts.tmp"

move /y "hosts.tmp" "hosts"
if exist "hosts.tmp" del "hosts.tmp"

Change to %systemroot%\System32\drivers\etc directory so the directory
with the hosts file is the current directory. Check if the hosts file
does exist to continue.

The for options of tokens=1* will store the ip address in %%A and
the remainder of the current line in %%B. Comparing the new ip address
with the ip address read is done with "%%~A" == "%oldip%".

If the update of the ip address is not done, as the variable named
updated_entry is defined if it has, then it will write it at the
end of the file. Not sure what domain to insert so using just ?domain?.

The new file with changes is hosts.tmp which is renamed to hosts.
hosts.tmp will be deleted if something fails, just to cleanup.


问:
Writing an Exodus II file programmatically
I want to write an Exodus II (.ex2) file to create a visualization with moving objects in ParaView, something similar to the "can.ex2" example included with the ParaView distribution.

Can anyone show how to do this programmatically? C/C++ preferrably.

答:
To write Exodus II files you should use the Exodus II library. (ParaView uses this library to read/write Exodus II files). The Exodus II library is document (with links to the source) here: https://gsjaardema.github.io/seacas/html/index.html.

Note that the Exodus II library is part of a larger library of tools (named SEACAS). However, it is possible to get the Exodus II library independent of the other utilities as described here: https://github.com/gsjaardema/seacas#exodus.


问:
How to build a remote_to link and pass a param
I have a model: ThreadParticipation

I want to build a link that send the ThreadParticipation.id and a param hide == true.

How can I build a link that does this?

ThreadParticipation Controller:

```<code>def hide
  @record = ThreadParticipation.find(params[:id)
  @record.hide == params[:hide]
  @record.save
end
</code>```

View:

```<code><%= link_to "hide", '/thread/:id/thread_participations/:id/hide', :remote => true %>
</code>```

Does that look right? How do I pass a param a long with the link_to (hide == true) ? Any ideas?

Thanks

答:
You could try this

```<code><%= link_to "hide", "/thread/#{thread_id}/thread_participations/#{id}/hide?hide=true", :remote => true %>
</code>```

Or better still, define a route to get the /thread/:thread_id/thread_participation/:id part. Lets say the route is hide_thead_pariticipation_thread_path

```<code><%= link_to "hide", hide_thread_participation_path(thread_id,:hide => true), :remote => true %>
</code>```

Also your controller code seems to be using "@record.hide == params[:hide]". Maybe its just a = there?

Body:
I have a model: ThreadParticipation

I want to build a link that send the ThreadParticipation.id and a param hide == true.

How can I build a link that does this?

ThreadParticipation Controller:

def hide
  @record = ThreadParticipation.find(params[:id)
  @record.hide == params[:hide]
  @record.save
end

View:

<%= link_to "hide", '/thread/:id/thread_participations/:id/hide', :remote => true %>

Does that look right? How do I pass a param a long with the link_to (hide == true) ? Any ideas?

Thanks

Body:
You could try this

<%= link_to "hide", "/thread/#{thread_id}/thread_participations/#{id}/hide?hide=true", :remote => true %>

Or better still, define a route to get the /thread/:thread_id/thread_participation/:id part. Lets say the route is hide_thead_pariticipation_thread_path

<%= link_to "hide", hide_thread_participation_path(thread_id,:hide => true), :remote => true %>

Also your controller code seems to be using "@record.hide == params[:hide]". Maybe its just a = there?


问:
Pandas fill consecutive null date values from previous dates + a constant number of days
I have a dataframe that contains a data column

```<code>Comp_date
0 2020-04-24
1        NaT
2        NaT
3        NaT
4 2020-08-06
5        NaT
6        NaT
7        NaT
8 2020-08-22
9        NaT
</code>```

I am trying to fill the null with the value of the previous date + add a constant number of days (10). But I am unable to do so. I tried the following

```<code>df['Comp_date']=df['Comp_date'].fillna((df['Comp_date'].shift()+pd.to_timedelta(10, unit='D')), inplace=True)
</code>```

Nothing happens and I get the same result. Any help?
expected outcome

```<code>    Comp_date
0   2020-04-24
1   2020-05-04
2   2020-05-14
3   2020-05-24
4   2020-08-06
5   2020-08-16
6   2020-08-26
7   2020-09-05
8   2020-08-22
9   2020-09-01
</code>```

答:
I'm not clear on your question, but this adds a constant number of days to the last observed Comp_date.

```<code>constant_number_of_days = 2
df2 = df['Comp_date'].ffill().to_frame()
df2.loc[df['Comp_date'].isnull(), 'Comp_date'] += pd.Timedelta(days=constant_number_of_days)
>>> df2
   Comp_date
0 2020-04-24
1 2020-04-26
2 2020-04-26
3 2020-04-26
4 2020-08-06
5 2020-08-08
6 2020-08-08
7 2020-08-08
8 2020-08-22
9 2020-08-24
</code>```

Body:
I have a dataframe that contains a data column

Comp_date
0 2020-04-24
1        NaT
2        NaT
3        NaT
4 2020-08-06
5        NaT
6        NaT
7        NaT
8 2020-08-22
9        NaT

I am trying to fill the null with the value of the previous date + add a constant number of days (10). But I am unable to do so. I tried the following

df['Comp_date']=df['Comp_date'].fillna((df['Comp_date'].shift()+pd.to_timedelta(10, unit='D')), inplace=True)

Nothing happens and I get the same result. Any help?
expected outcome

    Comp_date
0   2020-04-24
1   2020-05-04
2   2020-05-14
3   2020-05-24
4   2020-08-06
5   2020-08-16
6   2020-08-26
7   2020-09-05
8   2020-08-22
9   2020-09-01

Body:
I'm not clear on your question, but this adds a constant number of days to the last observed Comp_date.

constant_number_of_days = 2
df2 = df['Comp_date'].ffill().to_frame()
df2.loc[df['Comp_date'].isnull(), 'Comp_date'] += pd.Timedelta(days=constant_number_of_days)
>>> df2
   Comp_date
0 2020-04-24
1 2020-04-26
2 2020-04-26
3 2020-04-26
4 2020-08-06
5 2020-08-08
6 2020-08-08
7 2020-08-08
8 2020-08-22
9 2020-08-24


问:
trying to implement a sidenavigation in angular
I have an app.component.ts and i have created a component using ng generate c.That new component is suppose to have a sidenavigation and the side navigation needs to toggle upon a click of button.

I am trying to implement the side navigation menu but i am getting an error like below:
    "message": "Cannot find module '@angular/material/MatSidenavModule'.",

My navigation.component.html file

```<code><mat-sidenav-container>
    <mat-sidenav mode="side" opened>Sidenav content</mat-sidenav>
    <mat-sidenav-content>Main content</mat-sidenav-content>
  </mat-sidenav-container>
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatSidenavModule } from '@angular/material/MatSidenavModule';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NavigationComponent } from './navigation/navigation.component';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    NavigationComponent,

  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    MatSidenavModule,

  ],
  exports:[MatSidenavModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答:
with refrence to https://material.angular.io/components/sidenav/api
you have to import MatSidenavModule to your app.module.ts

```<code>import {MatSidenavModule} from '@angular/material/sidenav';
</code>```

For your ref use this example: https://stackblitz.com/angular/vrxballxmbo?file=src%2Fapp%2Fsidenav-drawer-overview-example.ts

Body:
I have an app.component.ts and i have created a component using ng generate c.That new component is suppose to have a sidenavigation and the side navigation needs to toggle upon a click of button.

I am trying to implement the side navigation menu but i am getting an error like below:
    "message": "Cannot find module '@angular/material/MatSidenavModule'.",

My navigation.component.html file

<mat-sidenav-container>
    <mat-sidenav mode="side" opened>Sidenav content</mat-sidenav>
    <mat-sidenav-content>Main content</mat-sidenav-content>
  </mat-sidenav-container>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatSidenavModule } from '@angular/material/MatSidenavModule';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NavigationComponent } from './navigation/navigation.component';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    NavigationComponent,

  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    MatSidenavModule,

  ],
  exports:[MatSidenavModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Body:
with refrence to https://material.angular.io/components/sidenav/api
you have to import MatSidenavModule to your app.module.ts

import {MatSidenavModule} from '@angular/material/sidenav';

For your ref use this example: https://stackblitz.com/angular/vrxballxmbo?file=src%2Fapp%2Fsidenav-drawer-overview-example.ts


问:
How to use 'relativize' in dnspython but prevent replacing full names with '@'?
I am using the dnspython package. While processing a file and passing relativize=False in dnspython's from_file() function, each name of a record is displayed fully, (e.g. 'smtp.example.com.')

I prefer an overview which shows only "smtp" in case of that subdomain. This could be realized by using relativize=True in the from_file() function. However, in that case, all full DNS names ('example.com') are replaced by an @ (at symbol).

Can I configure dnspython to relativize subdomains, but show the full DNS name without only showing the @?

答:
Symbol @ is used by DNS data format. See RFC1035 paragraph 5.1:

A free standing @ is used to denote the current origin.

So it is standard to use @ for current zone name. You can replace @ with zone (domain) name if it is needed. Though it is strange to mix relative and full domain names.


问:
Adobe Experience Manager Testing
Basically am from QA department and have good experience in software testing. Recently committed in AEM technology project and am new to AEM. Can you please share the questionnaire / things i need to look before going for testing?</p>

答:
As AEM based on components and services so you should first learn the basic terminology about AEM. For that you go through the helpx documents.
Also here is the link to the unit testing framework</p>

Title: Adobe Experience Manager Testing


答:
As per official documentation it should be

import {MatSidenavModule} from '@angular/material/sidenav';

But in your code it is

import { MatSidenavModule } from '@angular/material/MatSidenavModule';

Title: trying to implement a sidenavigation in angular


问:
Index of array looks like function name
I learning about laravel and php and recently I have encountered some problem which I try  to describe:
I'm trying to echo an average age of male. I'm using this function which I found on forum related to laravel:
$resultMale = DB::select($maleSQL, array(1));

My problem is that it returns arrays which indexes are taken from this query

$maleSQL = "SELECT books.name, books.book_date, AVG(reviews.age) FROM books, reviews where name='{$this->name}' and sex='m' and {$this->condition};";

and so if I want to access to data which is indexed as "name" I use:

echo "{$resultMale[0]->name}";

But my problem starts when i try to access data under AVG(reviews.age)

```<code> echo "{$resultMale[0]->AVG(reviews.age)}";
</code>```

It is detected as a function inside this array not as an index.
error in laravel

I've tried using foreach loop as well as:

```<code> $bypassFunctionAVG="avg(reviews.age)";
 echo "{$resultMale[0]->{$bypassFunctionAVG}}";
</code>```

I've tried also renaming this index without success.
So there goes my question: how do I echo data of this array  under this index?

答:
This might work...

```<code>$avg = $resultMale[0]->{"AVG(reviews.age)"}
echo $avg;
</code>```

Otherwise, try using an alias (notice, "AS avg")

```<code>$maleSQL = "SELECT books.name, books.book_date, AVG(reviews.age) AS avg FROM books, reviews where name='{$this->name}' and sex='m' and {$this->condition};";

echo $resultMale[0]->avg;
</code>```

Also double quotes is not necessary to echo variables as you have done it above. They are useful in some cases but not necessary. echo $var, echo "$var", echo "{$var}" will all do the same thing.

These things will have the same result...

```<code>$value = 25;
echo "The value is $value.";
echo "The value is {$value}.";
echo "The value is " . $value . ".";
echo 'The value is ' . $value . '.';
</code>```

These will not have the same result as above...

```<code>// use {} around non-trivial variable expressions
echo "The value is $object->value.";

// single quotes don't do anything to variables
echo 'The value is $value.';
</code>```

Title: Index of array looks like function name

Body:
I learning about laravel and php and recently I have encountered some problem which I try  to describe:
I'm trying to echo an average age of male. I'm using this function which I found on forum related to laravel:
$resultMale = DB::select($maleSQL, array(1));

My problem is that it returns arrays which indexes are taken from this query

$maleSQL = "SELECT books.name, books.book_date, AVG(reviews.age) FROM books, reviews where name='{$this->name}' and sex='m' and {$this->condition};";

and so if I want to access to data which is indexed as "name" I use:

echo "{$resultMale[0]->name}";

But my problem starts when i try to access data under AVG(reviews.age)

 echo "{$resultMale[0]->AVG(reviews.age)}";

It is detected as a function inside this array not as an index.
error in laravel

I've tried using foreach loop as well as:

 $bypassFunctionAVG="avg(reviews.age)";
 echo "{$resultMale[0]->{$bypassFunctionAVG}}";

I've tried also renaming this index without success.
So there goes my question: how do I echo data of this array  under this index?

Body:
This might work...

$avg = $resultMale[0]->{"AVG(reviews.age)"}
echo $avg;

Otherwise, try using an alias (notice, "AS avg")

$maleSQL = "SELECT books.name, books.book_date, AVG(reviews.age) AS avg FROM books, reviews where name='{$this->name}' and sex='m' and {$this->condition};";

echo $resultMale[0]->avg;

Also double quotes is not necessary to echo variables as you have done it above. They are useful in some cases but not necessary. echo $var, echo "$var", echo "{$var}" will all do the same thing.

These things will have the same result...

$value = 25;
echo "The value is $value.";
echo "The value is {$value}.";
echo "The value is " . $value . ".";
echo 'The value is ' . $value . '.';

These will not have the same result as above...

// use {} around non-trivial variable expressions
echo "The value is $object->value.";

// single quotes don't do anything to variables
echo 'The value is $value.';


问:
String value coming with two double quoted to .ts
If I given the normal value say hello in input field, it is coming like "hello", And if I have given the value like "hello", it is storing like ""hello"" . How to identify this two double quoted string and make it to one double quote .? </p>

答:
Use str.replace(/"/g, '') and wrap your string with artificial quotes. Something like

```<code>function stripQuotes(str) {
    let stripped = str.replace(/"/g, '');
    return '"'+stripped+'"';
}
</code>```

Now calling stripQuotes(""Hello"") will return "Hello", your desired result.

Body:
Use str.replace(/"/g, '') and wrap your string with artificial quotes. Something like

function stripQuotes(str) {
    let stripped = str.replace(/"/g, '');
    return '"'+stripped+'"';
}

Now calling stripQuotes(""Hello"") will return "Hello", your desired result.


问:
Rails: order the results returned from DISTINCT ON * ORDER
I have the following Rails models: Chat and Messages where a chat can have many messages. I have the following Rails query to pull the last message from the user for each chat where he is a recipient:

```<code>def index
  messages = Message.where(recipient_id: id)
                    .select('DISTINCT ON ("chat_id") *')
                    .order(:chat_id, created_at)
end
</code>```

This gives me the last message to the user of each chat that the user is a part of. I would now like to sort the results of this query by when the messages were created so that the latest messages go to the top. However, if I add

sorted = messages.order(created_at: :desc)

It doesn't sort the results of the first query, it simply appends the order by to the first query (which I know is the expected behavior) so I don't get a sorted list by created date. How can I do an order by to the result of the first query? Essentially something that would mimic the following with Rails syntax:

```<code>SELECT *
FROM (SELECT DISTINCT ON (chat_id) *
      FROM messages
      ORDER BY chat_id, created_at DESC) last_messages
ORDER BY created_at DESC
</code>```

答:
try this</p>

```<code>Message.from(
  Message.where(recipient_id: id)
    .select('DISTINCT ON ("chat_id") *')
    .order("chat_id, created_at DESC"),
    :messages
).order(created_at: :desc)
</code>```

Body:
I have the following Rails models: Chat and Messages where a chat can have many messages. I have the following Rails query to pull the last message from the user for each chat where he is a recipient:

def index
  messages = Message.where(recipient_id: id)
                    .select('DISTINCT ON ("chat_id") *')
                    .order(:chat_id, created_at)
end

This gives me the last message to the user of each chat that the user is a part of. I would now like to sort the results of this query by when the messages were created so that the latest messages go to the top. However, if I add

sorted = messages.order(created_at: :desc)

It doesn't sort the results of the first query, it simply appends the order by to the first query (which I know is the expected behavior) so I don't get a sorted list by created date. How can I do an order by to the result of the first query? Essentially something that would mimic the following with Rails syntax:

SELECT *
FROM (SELECT DISTINCT ON (chat_id) *
      FROM messages
      ORDER BY chat_id, created_at DESC) last_messages
ORDER BY created_at DESC

Body:
try this

Message.from(
  Message.where(recipient_id: id)
    .select('DISTINCT ON ("chat_id") *')
    .order("chat_id, created_at DESC"),
    :messages
).order(created_at: :desc)


问:
running local webpage using a docker IIS container
Running Docker for windows to host a local IIS to test a webpage, using the default windows IIS dockerpage

I am not sure what part to change in my dockerfile that allows me to run my webpage. Simply editing the COPY command in the dockerfile is what I thought I would need to change, but that isnt the case. What do I need to do to have it run a different html file instead of the default windows IIS page?

EDIT : Was able to find the open container by searching wwwroot in my C:, and I copy and pasted my hello world index.html page and was able to get it running

答:
You could follow below steps:

Create a Dockerfile with your website

```<code>FROM mcr.microsoft.com/windows/servercore/iis

RUN powershell -NoProfile -Command Remove-Item -Recurse C:\inetpub\wwwroot\*

WORKDIR /inetpub/wwwroot

COPY content/ .
</code>```

You can then build and run the Docker image:

```<code>$ docker build -t iis-site .
$ docker run -d -p 8000:80 --name my-running-site iis-site
</code>```

There is no need to specify an ENTRYPOINT in your Dockerfile since the microsoft/iis base image already includes an entrypoint application that monitors the status of the IIS World Wide Web Publishing Service (W3SVC).

With the current release, you can't use http://localhost to browse your site from the container host. This is because of a known behavior in WinNAT, and will be resolved in future. Until that is addressed, you need to use the IP address of the container.

Once the container starts, you'll need to finds its IP address so that you can connect to your running container from a browser. You use the docker inspect command to do that:

```<code>docker inspect -f "{{ .NetworkSettings.Networks.nat.IPAddress }}" my-running-site
</code>```

You will see an output similar to this:

```<code>172.28.103.186
</code>```

You can connect the running container using the IP address and configured port, http://172.28.103.186:8000 in the example shown.
In addition to static content, IIS can run other workloads including but not limited to ASP.NET, ASP.NET Core, NodeJS, PHP, and Apache Tomcat.

For more detail you could refer below links:

https://learn.microsoft.com/en-us/aspnet/mvc/overview/deployment/docker-aspnetmvc

https://mcpmag.com/articles/2019/11/20/iis-on-windows-server-containers.aspx

Cannot access an IIS container from browser - Docker

Body:
You could follow below steps:

Create a Dockerfile with your website

FROM mcr.microsoft.com/windows/servercore/iis

RUN powershell -NoProfile -Command Remove-Item -Recurse C:\inetpub\wwwroot\*

WORKDIR /inetpub/wwwroot

COPY content/ .

You can then build and run the Docker image:

$ docker build -t iis-site .
$ docker run -d -p 8000:80 --name my-running-site iis-site

There is no need to specify an ENTRYPOINT in your Dockerfile since the microsoft/iis base image already includes an entrypoint application that monitors the status of the IIS World Wide Web Publishing Service (W3SVC).

With the current release, you can't use http://localhost to browse your site from the container host. This is because of a known behavior in WinNAT, and will be resolved in future. Until that is addressed, you need to use the IP address of the container.

Once the container starts, you'll need to finds its IP address so that you can connect to your running container from a browser. You use the docker inspect command to do that:

docker inspect -f "{{ .NetworkSettings.Networks.nat.IPAddress }}" my-running-site

You will see an output similar to this:

172.28.103.186

You can connect the running container using the IP address and configured port, http://172.28.103.186:8000 in the example shown.
In addition to static content, IIS can run other workloads including but not limited to ASP.NET, ASP.NET Core, NodeJS, PHP, and Apache Tomcat.

For more detail you could refer below links:

https://learn.microsoft.com/en-us/aspnet/mvc/overview/deployment/docker-aspnetmvc

https://mcpmag.com/articles/2019/11/20/iis-on-windows-server-containers.aspx

Cannot access an IIS container from browser - Docker


问:
OneHotEncoder ValueError: Found unknown categories
I am building the OneHotEncoder using the full file.

```<code>def buildOneHotEncoder(training_file_name, categoricalCols):
    one_hot_encoder = OneHotEncoder(sparse=False)

    df = pd.read_csv(training_file_name, skiprows=0, header=0)
    df = df[categoricalCols]
    df = removeNaN(df, categoricalCols)
    logging.info(str(df.columns))
    one_hot_encoder.fit(df)
    return one_hot_encoder
</code>```

```<code>def removeNaN(df, categoricalCols):
    # Replace any NaN values
    for col in categoricalCols:
        df[[col]] = df[[col]].fillna(value=CONSTANT_FILLER)
    return df
</code>```

Now i am using this same encoder when i processing the same file in chunks

```<code>for chunk in pd.read_csv(training_file_name, chunksize=CHUNKSIZE):
....
  INPUT = chunk[categoricalCols]
  INPUT = removeNaN(INPUT, categoricalCols)
  one_hot_encoded = one_hot_encoder.transform(INPUT)
....
</code>```

It's giving me error 'ValueError: Found unknown categories ['missing'] in column 2 during transform'

I can't process the full file at once as during training iterations memory is required to use all cores.

答:
The issue was with applying

```<code>df_merged_set_test = chunk.where(chunk['weblab']=="missing")
</code>```

I was filtering the dataset based on the a field so for the all rows which are it fill NaN. I was later on replacing them with a missing flag.

The correct way

Clean the dataset i.e fill all na values for all columns

Then filter and drop NaN rows i.e all values NaN rows .where(chunk['weblab']=="missing").dropna()

Body:
I am building the OneHotEncoder using the full file.

def buildOneHotEncoder(training_file_name, categoricalCols):
    one_hot_encoder = OneHotEncoder(sparse=False)

    df = pd.read_csv(training_file_name, skiprows=0, header=0)
    df = df[categoricalCols]
    df = removeNaN(df, categoricalCols)
    logging.info(str(df.columns))
    one_hot_encoder.fit(df)
    return one_hot_encoder

def removeNaN(df, categoricalCols):
    # Replace any NaN values
    for col in categoricalCols:
        df[[col]] = df[[col]].fillna(value=CONSTANT_FILLER)
    return df

Now i am using this same encoder when i processing the same file in chunks

for chunk in pd.read_csv(training_file_name, chunksize=CHUNKSIZE):
....
  INPUT = chunk[categoricalCols]
  INPUT = removeNaN(INPUT, categoricalCols)
  one_hot_encoded = one_hot_encoder.transform(INPUT)
....

It's giving me error 'ValueError: Found unknown categories ['missing'] in column 2 during transform'

I can't process the full file at once as during training iterations memory is required to use all cores.

Body:
The issue was with applying

df_merged_set_test = chunk.where(chunk['weblab']=="missing")

I was filtering the dataset based on the a field so for the all rows which are it fill NaN. I was later on replacing them with a missing flag.

The correct way

Clean the dataset i.e fill all na values for all columns

Then filter and drop NaN rows i.e all values NaN rows .where(chunk['weblab']=="missing").dropna()


问:
Accessing UI Thread Window from another thread and class for AAD WIndow
I am building a WPF that prompts the user to login to Azure AD, and I am unable to get the call to fire, instead it hangs the UI thread. Here is the code that I am trying to call

```<code> authResult = _application.AcquireTokenInteractive(_scopes)
                          .WithParentActivityOrWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle)
                          .ExecuteAsync().Result;
</code>```

I have tried wrapping this in a dispatcher call, like so

```<code>internal static Dispatcher GetDispatcher(this DispatcherObject source)
{
    //use the application's dispatcher by default
    if (Application.Current != null) return Application.Current.Dispatcher;

    //fallback for WinForms environments
    if (source.Dispatcher != null) return source.Dispatcher;

    // ultimately use the thread's dispatcher
    return Dispatcher.CurrentDispatcher;
}

var dispatcher = MainWindow.main.GetDispatcher();

if (!dispatcher.CheckAccess())
{
    var action = new Action(() => {
        authResult = _application.AcquireTokenInteractive(_scopes)
                     .WithParentActivityOrWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle)
                     .ExecuteAsync().Result;
        });
        dispatcher.Invoke(DispatcherPriority.Normal, action);
        return;
}
</code>```

If I move the interactive call in my MainWindow.xaml.cs, it works fine, but I want to move it to a service class to clean things up. What could I be doing wrong? The above code is in a function that has a signature like this

```<code> public async Task AuthenticateRequestAsync(HttpRequestMessage request)
</code>```

I can provide additional info if needed.

答:
```<code>_application.AcquireTokenInteractive(_scopes)
                          .WithParentActivityOrWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle)
                          .ExecuteAsync().Result;
</code>```

Calling Result will block the UI thread.
Instead, you need to await the call.

```<code>await _application.AcquireTokenInteractive(_scopes)
                          .WithParentActivityOrWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle)
                          .ExecuteAsync();
</code>```

You will need to mark the function async as well.

Body:
I am building a WPF that prompts the user to login to Azure AD, and I am unable to get the call to fire, instead it hangs the UI thread. Here is the code that I am trying to call

 authResult = _application.AcquireTokenInteractive(_scopes)
                          .WithParentActivityOrWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle)
                          .ExecuteAsync().Result;

I have tried wrapping this in a dispatcher call, like so

internal static Dispatcher GetDispatcher(this DispatcherObject source)
{
    //use the application's dispatcher by default
    if (Application.Current != null) return Application.Current.Dispatcher;

    //fallback for WinForms environments
    if (source.Dispatcher != null) return source.Dispatcher;

    // ultimately use the thread's dispatcher
    return Dispatcher.CurrentDispatcher;
}

var dispatcher = MainWindow.main.GetDispatcher();

if (!dispatcher.CheckAccess())
{
    var action = new Action(() => {
        authResult = _application.AcquireTokenInteractive(_scopes)
                     .WithParentActivityOrWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle)
                     .ExecuteAsync().Result;
        });
        dispatcher.Invoke(DispatcherPriority.Normal, action);
        return;
}

If I move the interactive call in my MainWindow.xaml.cs, it works fine, but I want to move it to a service class to clean things up. What could I be doing wrong? The above code is in a function that has a signature like this

 public async Task AuthenticateRequestAsync(HttpRequestMessage request)

I can provide additional info if needed.

Body:
_application.AcquireTokenInteractive(_scopes)
                          .WithParentActivityOrWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle)
                          .ExecuteAsync().Result;

Calling Result will block the UI thread.
Instead, you need to await the call.

await _application.AcquireTokenInteractive(_scopes)
                          .WithParentActivityOrWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle)
                          .ExecuteAsync();

You will need to mark the function async as well.


问:
Error while connecting to Database/postgresql/python
What I am trying to do is save an image to my PostgreSQL database, I found a code that helps with this. But I am having difficulty pushing the image into the database as this error keep popping out:

Error while connecting to PostgreSQL [Errno 13] Permission denied:
  'C:/Users/hc559/Downloads/facial-master/facial-master/dataset/adrian'
  Po

stgreSQL connection is closed

I tried to resolve by setting the file permission to everyone but to no avail.

```<code>import sys
import psycopg2
import argparse

try:
    connection = psycopg2.connect(user = "postgres",
                                  password = "123",
                                  host = "127.0.0.1",
                                  port = "5432",
                                  database = "postgres")

    cursor = connection.cursor()
    # Print PostgreSQL Connection properties
    print ( connection.get_dsn_parameters(),"\n")

    # Print PostgreSQL version
    cursor.execute("SELECT version();")
    record = cursor.fetchone()
    print("You are connected to - ", record,"\n")

    def main(argv):
        parser = argparse.ArgumentParser()
        parser_action = parser.add_mutually_exclusive_group(required=True)
        parser_action.add_argument("--store", action='store_const', const=True, help="Load an image from the named file and save it in the DB")
        parser_action.add_argument("--fetch", type=int, help="Fetch an image from the DB and store it in the named file, overwriting it if it exists. Takes the database file identifier as an argument.", metavar='42')
        parser.add_argument("filename", help="Name of file to write to / fetch from")

        args = parser.parse_args(argv[1:])

    args = {

        'store': 'C:/Users/L30809.NYPSIT.000/Downloads/new/opencv-face-recognition/facial/dataset/Avan',
        'fetch': 'C:/Users/L30809.NYPSIT.000/Downloads/new/opencv-face-recognition/facial/dataset/Avan',
        'filename': 'C:/Users/hc559/Downloads/facial-master/facial-master/dataset/adrian'

}

    # and run the command
    if args['store']:
        # Reads the whole file into memory. If you want to avoid that,
        # use large object storage instead of bytea; see the psycopg2
        # and postgresql documentation.
        f = open(args['filename'],'rb')

        # The following code works as-is in Python 3.
        #
        # In Python 2, you can't just pass a 'str' directly, as psycopg2
        # will think it's an encoded text string, not raw bytes. You must
        # either use psycopg2.Binary to wrap it, or load the data into a
        # "bytearray" object.
        #
        # so either:
        #
        #   filedata = psycopg2.Binary( f.read() )
        #
        # or
        #
        #   filedata = buffer( f.read() )
        #
        filedata = f.read()
        cursor.execute("INSERT INTO files(id, orig_filename, file_data) VALUES (DEFAULT,%s,%s) RETURNING id", (args['filename'], filedata))
        returned_id = cursor.fetchone()[0]
        f.close()
        connection.commit()
        print("Stored {0} into DB record {1}".format(args['filename'], returned_id))

    elif args['fetch'] is not None:
        # Fetches the file from the DB into memory then writes it out.
        # Same as for store, to avoid that use a large object.
        f = open(args['filename'],'wb')
        cursor.execute("SELECT file_data, orig_filename FROM files WHERE id = %s", (int(args['fetch']),))
        (file_data, orig_filename) = cursor.fetchone()

            # In Python 3 this code works as-is.
            # In Python 2, you must get the str from the returned buffer object.
        f.write(file_data)
        f.close()
        print("Fetched {0} into file {1}; original filename was {2}".format(args['fetch'], args['filename'], orig_filename))

    connection.close()

    if __name__ == '__main__':
        main(sys.argv)

except (Exception, psycopg2.Error) as error :
    print ("Error while connecting to PostgreSQL", error)
finally:
    #closing database connection.
        if(connection):
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed")
</code>```

答: You need to adjust the database and table permissions permissions for the conneting user. You do this in the file pg_hba.conf or by using a statement like 'grant  on  to ' .</p>

Body:
What I am trying to do is save an image to my PostgreSQL database, I found a code that helps with this. But I am having difficulty pushing the image into the database as this error keep popping out:

Error while connecting to PostgreSQL [Errno 13] Permission denied:
  'C:/Users/hc559/Downloads/facial-master/facial-master/dataset/adrian'
  Po

stgreSQL connection is closed

I tried to resolve by setting the file permission to everyone but to no avail.

import sys
import psycopg2
import argparse

try:
    connection = psycopg2.connect(user = "postgres",
                                  password = "123",
                                  host = "127.0.0.1",
                                  port = "5432",
                                  database = "postgres")

    cursor = connection.cursor()
    # Print PostgreSQL Connection properties
    print ( connection.get_dsn_parameters(),"\n")

    # Print PostgreSQL version
    cursor.execute("SELECT version();")
    record = cursor.fetchone()
    print("You are connected to - ", record,"\n")

    def main(argv):
        parser = argparse.ArgumentParser()
        parser_action = parser.add_mutually_exclusive_group(required=True)
        parser_action.add_argument("--store", action='store_const', const=True, help="Load an image from the named file and save it in the DB")
        parser_action.add_argument("--fetch", type=int, help="Fetch an image from the DB and store it in the named file, overwriting it if it exists. Takes the database file identifier as an argument.", metavar='42')
        parser.add_argument("filename", help="Name of file to write to / fetch from")

        args = parser.parse_args(argv[1:])

    args = {

        'store': 'C:/Users/L30809.NYPSIT.000/Downloads/new/opencv-face-recognition/facial/dataset/Avan',
        'fetch': 'C:/Users/L30809.NYPSIT.000/Downloads/new/opencv-face-recognition/facial/dataset/Avan',
        'filename': 'C:/Users/hc559/Downloads/facial-master/facial-master/dataset/adrian'

}

    # and run the command
    if args['store']:
        # Reads the whole file into memory. If you want to avoid that,
        # use large object storage instead of bytea; see the psycopg2
        # and postgresql documentation.
        f = open(args['filename'],'rb')

        # The following code works as-is in Python 3.
        #
        # In Python 2, you can't just pass a 'str' directly, as psycopg2
        # will think it's an encoded text string, not raw bytes. You must
        # either use psycopg2.Binary to wrap it, or load the data into a
        # "bytearray" object.
        #
        # so either:
        #
        #   filedata = psycopg2.Binary( f.read() )
        #
        # or
        #
        #   filedata = buffer( f.read() )
        #
        filedata = f.read()
        cursor.execute("INSERT INTO files(id, orig_filename, file_data) VALUES (DEFAULT,%s,%s) RETURNING id", (args['filename'], filedata))
        returned_id = cursor.fetchone()[0]
        f.close()
        connection.commit()
        print("Stored {0} into DB record {1}".format(args['filename'], returned_id))

    elif args['fetch'] is not None:
        # Fetches the file from the DB into memory then writes it out.
        # Same as for store, to avoid that use a large object.
        f = open(args['filename'],'wb')
        cursor.execute("SELECT file_data, orig_filename FROM files WHERE id = %s", (int(args['fetch']),))
        (file_data, orig_filename) = cursor.fetchone()

            # In Python 3 this code works as-is.
            # In Python 2, you must get the str from the returned buffer object.
        f.write(file_data)
        f.close()
        print("Fetched {0} into file {1}; original filename was {2}".format(args['fetch'], args['filename'], orig_filename))

    connection.close()

    if __name__ == '__main__':
        main(sys.argv)

except (Exception, psycopg2.Error) as error :
    print ("Error while connecting to PostgreSQL", error)
finally:
    #closing database connection.
        if(connection):
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed")