问:
Hibernate removes child objects after session.update(parent)
I have a very simple parent-/child relationship between objects of type "Folder", which looks like this:

A folder can have 0-1 parent folders.

A folder can have 0-n child folders
(subfolders).

So, basically, a simplified version of the Java class Folder looks like this:

```<code>public class Folder{
    long id;
    Set<Folder> childFolders;
    Folder parentFolder;
    String path;

    // Getter, setter and other (for this question)
    // not relevant properties omitted

    public boolean equals(Object obj){
            if (obj == null) return false;
            if (obj == this) return true;
            if (obj instanceof Folder){
                    Folder folder = (Folder)obj;
                    return folder.getPath().equals(getPath());
            }
            return false;
    }

    public int hashCode(){
            return getPath().hashCode();
    }

}
</code>```

My simple test hierarchy looks like this:

```<code>  folder1
  folder2
- folder3
   subfolder3-1
</code>```

Using Hibernate, I call:

```<code>session.update(folder1);
session.update(folder2);
session.update(folder3);
</code>```

The first two calls succeed.

The last call for folder3 throws no exception BUT it removes subfolder3-1 from the internal set "childFolders" of folder3.
That means, folder3.childFolders.size() = 0 although it was 1 before the last update call.
Important: In the database, folder "subfolder3-1" still exists!

How can that be?

Here is my mapping file:

```<code><?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="test.Folder" table="FOLDERS">

        <id name="id" type="long" access="field">
            <column name="FOLDER_ID" />
            <generator class="native" />
        </id>

        <set name="childFolders" table="FOLDERS" inverse="true" cascade="save-update">
            <key column="PARENT_FOLDER_ID"></key>
            <one-to-many class="test.Folder" />
        </set>

        <many-to-one name="parentFolder" column="PARENT_FOLDER_ID" />

        <property name="path" column="FOLDER_PATH" />
    </class>
</hibernate-mapping>
</code>```

答: I think that the issue is in the inverse="true" attribute: inverse attributes are not saved.</p>

Body:
I have a very simple parent-/child relationship between objects of type "Folder", which looks like this:

A folder can have 0-1 parent folders.

A folder can have 0-n child folders
(subfolders).

So, basically, a simplified version of the Java class Folder looks like this:

public class Folder{
    long id;
    Set<Folder> childFolders;
    Folder parentFolder;
    String path;

    // Getter, setter and other (for this question)
    // not relevant properties omitted

    public boolean equals(Object obj){
            if (obj == null) return false;
            if (obj == this) return true;
            if (obj instanceof Folder){
                    Folder folder = (Folder)obj;
                    return folder.getPath().equals(getPath());
            }
            return false;
    }

    public int hashCode(){
            return getPath().hashCode();
    }

}

My simple test hierarchy looks like this:

  folder1
  folder2
- folder3
   subfolder3-1

Using Hibernate, I call:

session.update(folder1);
session.update(folder2);
session.update(folder3);

The first two calls succeed.

The last call for folder3 throws no exception BUT it removes subfolder3-1 from the internal set "childFolders" of folder3.
That means, folder3.childFolders.size() = 0 although it was 1 before the last update call.
Important: In the database, folder "subfolder3-1" still exists!

How can that be?

Here is my mapping file:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="test.Folder" table="FOLDERS">

        <id name="id" type="long" access="field">
            <column name="FOLDER_ID" />
            <generator class="native" />
        </id>

        <set name="childFolders" table="FOLDERS" inverse="true" cascade="save-update">
            <key column="PARENT_FOLDER_ID"></key>
            <one-to-many class="test.Folder" />
        </set>

        <many-to-one name="parentFolder" column="PARENT_FOLDER_ID" />

        <property name="path" column="FOLDER_PATH" />
    </class>
</hibernate-mapping>


来源: stackexchange

问:
Python: How to Create chucks of data contain X byte for each time
I am trying to write a simple function that take a data in hex format. However, the idea is I want to use for loop with round() so that each time the loop will print only 2KB (2048) of data (only 2048 byte for each time),

This is what I did, but did not work.

```<code>data = "4d5a90000300000004000000fff........"

def function_x(x):
    for i in range(0,int(round(len(data)/2048))):
        data_chunk = data[i*2047:(i+1)*2047]
        ....
        ....
        ....
        ....
</code>```

UPDATE: To make my question clear for you, I will provide some details. I am using Postgresql, Large objects specifically, However, to update this object or insert any new data on it, you must keep this note in you mind, which is mentioned in their documentation

The amount of data per page is defined to be LOBLKSIZE (which is currently BLCKSZ/4, or typically 2 kB "2048").

so I wrote this simple code to fit with their requirements, just do not know what is the the right numbers must be written instead of (?) marks that i put

for i in range(0,int(round(len(data)/??))):  > to divide the code into x number of pages, each page must contain 2048 byte only > data[i*??:(i+1)*??]

NOTE: if i == 0 because the first page must be updated not inserted according to their docs

here is the full code

```<code>data = "4d5a90000300000004000000fff........"
loid = 14697

def function_x(x):
        for i in range(0,int(round(len(data)/??))):
    data_chunk = data[i*??:(i+1)*??]
    if i == 0:
        sql = "UPDATE PG_LARGEOBJECT SET data=decode('%s', 'hex') where loid=%d and pageno=%d" % (data_chunk, loid, i)
    else:
        sql = "INSERT PG_LARGEOBJECT SET data=decode('%s', 'hex') where loid=%d and pageno=%d" % (data_chunk, loid, i)
        ....
        ....
        ....
        ....
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write a simple function that take a data in hex format. However, the idea is I want to use for loop with round() so that each time the loop will print only 2KB (2048) of data (only 2048 byte for each time),

This is what I did, but did not work.

data = "4d5a90000300000004000000fff........"

def function_x(x):
    for i in range(0,int(round(len(data)/2048))):
        data_chunk = data[i*2047:(i+1)*2047]
        ....
        ....
        ....
        ....

UPDATE: To make my question clear for you, I will provide some details. I am using Postgresql, Large objects specifically, However, to update this object or insert any new data on it, you must keep this note in you mind, which is mentioned in their documentation

The amount of data per page is defined to be LOBLKSIZE (which is currently BLCKSZ/4, or typically 2 kB "2048").

so I wrote this simple code to fit with their requirements, just do not know what is the the right numbers must be written instead of (?) marks that i put

for i in range(0,int(round(len(data)/??))):  > to divide the code into x number of pages, each page must contain 2048 byte only > data[i*??:(i+1)*??]

NOTE: if i == 0 because the first page must be updated not inserted according to their docs

here is the full code

data = "4d5a90000300000004000000fff........"
loid = 14697

def function_x(x):
        for i in range(0,int(round(len(data)/??))):
    data_chunk = data[i*??:(i+1)*??]
    if i == 0:
        sql = "UPDATE PG_LARGEOBJECT SET data=decode('%s', 'hex') where loid=%d and pageno=%d" % (data_chunk, loid, i)
    else:
        sql = "INSERT PG_LARGEOBJECT SET data=decode('%s', 'hex') where loid=%d and pageno=%d" % (data_chunk, loid, i)
        ....
        ....
        ....
        ....

Body:
data = "4d5a90000300000004000000fff........"

def function_x(x):
    while x != "":
        data_chunk = x[0:2048]
        # Do some stuff with data_chunk
        x = x[2048:]
        ...
        ...


问:
Updating Objects To Add New Element With .push
In the snippet below the goal is to check if the addedPlayer already exist in players by checking the .name property

if addedPlayer is already in players : Give the player a point

else update players by adding in addedPlayer with a starting point

```<code>let players = []

let addedPlayer = {

   name: /* The Given Name To Check in players */ ,
   points: 1

}

function addPlayer(playerList, playerToAdd){

   const existingPlayers = playerList.map((playerToAdd) => playerToAdd.name);

   if(existingPlayers.includes(playerToAdd.name)){

       playerToAdd.points++

   } else {

      playerList.push(playerToAdd)

   }
}

addPlayer(players, addedPlayer)

console.log(players)
</code>```

The problem is players only returns addedPlayer. My Goal being that players will store every new player and adds points accordingly

答:
You can achieve that by finding if the newPlayer already exists in the given array by checking against player.name then conditionally incrementing player.point if newPlayer already exists else adding the newPlayer to the array.

Here is an example.

let players = [
    {
        name: 'Player1',
        point: 1
    },
    {
        name: 'Player2',
        point: 2
    }
]

let newPlayer = {
   name: 'Player2',
   points: 1
}

function addPlayer(playerlist, newPlayer) {
    // idx will be -1 if a player does not exist in playerlist by the name
    const idx = playerlist.findIndex(p => p.name === newPlayer.name);

    if (idx === -1) {
        // if you want to mutate the original array you can use playerlist.push(newPlayer) then return immediately from the function and omit the next return line
        return [...playerlist, newPlayer]
    }

    // increment player.point if newPlayer already exists

    playerlist[idx] = {...playerlist[idx], point: playerlist[idx].point + 1}
    // if you want to mutate the original array then omit the next return line
    return [...playerlist]
}

// because newPlayer already exists in players array by name calling the function addPlayer will increment player.point in players array where player.name is 'Player2'
console.log(addPlayer(players, newPlayer))

// calling the function with a player that does not exist in the array
let anotherPlayer = { name: 'Player3', point: 0 };

// anotherPlayer will be added to the returned array
console.log(addPlayer(players, anotherPlayer))```

P.S. - The current solution will return a new array on each call of the addPlayer function if your use case requires you to mutate the array you can use Array.prototype.push and omit the returns from the function. I have included some comments in the snippet for more details.

Body:
In the snippet below the goal is to check if the addedPlayer already exist in players by checking the .name property

if addedPlayer is already in players : Give the player a point

else update players by adding in addedPlayer with a starting point

let players = []

let addedPlayer = {

   name: /* The Given Name To Check in players */ ,
   points: 1

}

function addPlayer(playerList, playerToAdd){

   const existingPlayers = playerList.map((playerToAdd) => playerToAdd.name);

   if(existingPlayers.includes(playerToAdd.name)){

       playerToAdd.points++

   } else {

      playerList.push(playerToAdd)

   }
}

addPlayer(players, addedPlayer)

console.log(players)

The problem is players only returns addedPlayer. My Goal being that players will store every new player and adds points accordingly

Body:
You can achieve that by finding if the newPlayer already exists in the given array by checking against player.name then conditionally incrementing player.point if newPlayer already exists else adding the newPlayer to the array.

Here is an example.

let players = [
    {
        name: 'Player1',
        point: 1
    },
    {
        name: 'Player2',
        point: 2
    }
]

let newPlayer = {
   name: 'Player2',
   points: 1
}

function addPlayer(playerlist, newPlayer) {
    // idx will be -1 if a player does not exist in playerlist by the name
    const idx = playerlist.findIndex(p => p.name === newPlayer.name);

    if (idx === -1) {
        // if you want to mutate the original array you can use playerlist.push(newPlayer) then return immediately from the function and omit the next return line
        return [...playerlist, newPlayer]
    }

    // increment player.point if newPlayer already exists

    playerlist[idx] = {...playerlist[idx], point: playerlist[idx].point + 1}
    // if you want to mutate the original array then omit the next return line
    return [...playerlist]
}

// because newPlayer already exists in players array by name calling the function addPlayer will increment player.point in players array where player.name is 'Player2'
console.log(addPlayer(players, newPlayer))

// calling the function with a player that does not exist in the array
let anotherPlayer = { name: 'Player3', point: 0 };

// anotherPlayer will be added to the returned array
console.log(addPlayer(players, anotherPlayer))

P.S. - The current solution will return a new array on each call of the addPlayer function if your use case requires you to mutate the array you can use Array.prototype.push and omit the returns from the function. I have included some comments in the snippet for more details.


问:
Newtonsoft JSON is not deserializing the nested object in my json file
I have a JSON file that I am trying to deserialize.

```<code>[
  {
    "colorData": [
      255,
      255,
      255
    ],
    "Neighbours": [
      {
        "Item1": 0,
        "Item2": [
          {
            "colorData": [
              255,
              255,
              255
            ],
            "numberOfExamples": 188
          },
          {
            "colorData": [
              255,
              24,
              0
            ],
            "numberOfExamples": 15
          }
        ]
      },
      {
        "Item1": 1,
        "Item2": [
          {
            "colorData": [
              255,
              255,
              255
            ],
            "numberOfExamples": 188
          },
          {
            "colorData": [
              255,
              24,
              0
            ],
            "numberOfExamples": 15
          }
        ]
      },
      {
        "Item1": 2,
        "Item2": [
          {
            "colorData": [
              255,
              255,
              255
            ],
            "numberOfExamples": 188
          },
          {
            "colorData": [
              255,
              24,
              0
            ],
            "numberOfExamples": 15
          }
        ]
      },
      {
        "Item1": 3,
        "Item2": [
          {
            "colorData": [
              255,
              255,
              255
            ],
            "numberOfExamples": 188
          },
          {
            "colorData": [
              255,
              24,
              0
            ],
            "numberOfExamples": 15
          }
        ]
      }
    ]
  }
]
</code>```

This is the object I'm trying to deserialize it into:

```<code>public partial class ImageBrainData_Reader
{
    public int[] colorData { get; set; }
    public List<Neighbour_Reader> neighbours { get; set; }
}

public partial class Neighbour_Reader
{
    public int direction { get; set; }
    public List<NeighbourData_Reader> neighbourData_Reader { get; set; }
}

public partial class NeighbourData_Reader
{
    public int[] colorData { get; set; }
    public int numberOfExamples { get; set; }
}
</code>```

And this is what I'm doing to load it from a file:

```<code> List<ImageBrainData_Reader> dataRead = JsonConvert.DeserializeObject<List<ImageBrainData_Reader>>(File.ReadAllText(fileName + ".json"));
</code>```

The first part (colorData) gets brought in and the correct amount of nested Neighbours, but none of the data from them (Item1 and Item2) are being read. Instead of getting the data, they are defaulting to their default values (0 and null, respectively).

答:
Json.Net doesn't have any way to know that Item1 maps to direction and Item2 maps to neighbourData_Reader unless you tell it.  You either need to add some [JsonProperty] attributes as shown below, or rename your properties to match the JSON.

```<code>public partial class Neighbour_Reader
{
    [JsonProperty("Item1")]
    public int direction { get; set; }
    [JsonProperty("Item2")]
    public List<NeighbourData_Reader> neighbourData_Reader { get; set; }
}
</code>```

Fiddle: https://dotnetfiddle.net/ajE0HD

Body:
I have a JSON file that I am trying to deserialize.

[
  {
    "colorData": [
      255,
      255,
      255
    ],
    "Neighbours": [
      {
        "Item1": 0,
        "Item2": [
          {
            "colorData": [
              255,
              255,
              255
            ],
            "numberOfExamples": 188
          },
          {
            "colorData": [
              255,
              24,
              0
            ],
            "numberOfExamples": 15
          }
        ]
      },
      {
        "Item1": 1,
        "Item2": [
          {
            "colorData": [
              255,
              255,
              255
            ],
            "numberOfExamples": 188
          },
          {
            "colorData": [
              255,
              24,
              0
            ],
            "numberOfExamples": 15
          }
        ]
      },
      {
        "Item1": 2,
        "Item2": [
          {
            "colorData": [
              255,
              255,
              255
            ],
            "numberOfExamples": 188
          },
          {
            "colorData": [
              255,
              24,
              0
            ],
            "numberOfExamples": 15
          }
        ]
      },
      {
        "Item1": 3,
        "Item2": [
          {
            "colorData": [
              255,
              255,
              255
            ],
            "numberOfExamples": 188
          },
          {
            "colorData": [
              255,
              24,
              0
            ],
            "numberOfExamples": 15
          }
        ]
      }
    ]
  }
]

This is the object I'm trying to deserialize it into:

public partial class ImageBrainData_Reader
{
    public int[] colorData { get; set; }
    public List<Neighbour_Reader> neighbours { get; set; }
}

public partial class Neighbour_Reader
{
    public int direction { get; set; }
    public List<NeighbourData_Reader> neighbourData_Reader { get; set; }
}

public partial class NeighbourData_Reader
{
    public int[] colorData { get; set; }
    public int numberOfExamples { get; set; }
}

And this is what I'm doing to load it from a file:

 List<ImageBrainData_Reader> dataRead = JsonConvert.DeserializeObject<List<ImageBrainData_Reader>>(File.ReadAllText(fileName + ".json"));

The first part (colorData) gets brought in and the correct amount of nested Neighbours, but none of the data from them (Item1 and Item2) are being read. Instead of getting the data, they are defaulting to their default values (0 and null, respectively).

Body:
Json.Net doesn't have any way to know that Item1 maps to direction and Item2 maps to neighbourData_Reader unless you tell it.  You either need to add some [JsonProperty] attributes as shown below, or rename your properties to match the JSON.

public partial class Neighbour_Reader
{
    [JsonProperty("Item1")]
    public int direction { get; set; }
    [JsonProperty("Item2")]
    public List<NeighbourData_Reader> neighbourData_Reader { get; set; }
}

Fiddle: https://dotnetfiddle.net/ajE0HD


问:
What is the difference between mysqli_connect queries
what is the difference between

$link = mysqli_connect($dbhost, $dbuser, $dbpass);

$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die(mysqli_error($link));

答:
The only difference between these two lines is that if you have mysqli error reporting switched off and the connection cannot be established, then the first mysqli_connect will return null and continue as if nothing happened, whereas the second one will kill the script and leak your sensitive credentials.

Do not use either one. The proper way to connect via mysqli class is this:

```<code>mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = new mysqli('localhost', 'user', 'pass', 'db');
$link->set_charset('utf8mb4'); // always set the charset
</code>```

Three lines only, and no die or if statements.

First, you need to enable error reporting for mysqli, then you create the instance of this class, and lastly you set the correct charset.

ContentLicense: CC BY-SA 3.0

Body:
The only difference between these two lines is that if you have mysqli error reporting switched off and the connection cannot be established, then the first mysqli_connect will return null and continue as if nothing happened, whereas the second one will kill the script and leak your sensitive credentials.

Do not use either one. The proper way to connect via mysqli class is this:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = new mysqli('localhost', 'user', 'pass', 'db');
$link->set_charset('utf8mb4'); // always set the charset

Three lines only, and no die or if statements.

First, you need to enable error reporting for mysqli, then you create the instance of this class, and lastly you set the correct charset.


问:
Why string str = new string("abc") doesn't pass compiler?
Given public String(char*) why we cannot use the following statement?

```<code>string str = new string("aaa");
</code>```

Error   1

The best overloaded method match for
  'string.String(char*)' has some
  invalid
  arguments C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  26  ConsoleApplication2

Error   2

Argument 1: cannot convert from
  'string' to
  'char*'   C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  37  ConsoleApplication2

答: The type char* is for an unsafe pointer -- to an object not part of the .Net managed framework.  When you place the literal string "aaa" in your code, that's a managed object.  string is not char* in C#.

Body:
Given public String(char*) why we cannot use the following statement?

string str = new string("aaa");

Error   1

The best overloaded method match for
  'string.String(char*)' has some
  invalid
  arguments C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  26  ConsoleApplication2

Error   2

Argument 1: cannot convert from
  'string' to
  'char*'   C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  37  ConsoleApplication2


问:
ReactJS - Get Height of an element
How can I get the Height of an element after React renders that element?

HTML

```<code><div id="container">
<!-- This element's contents will be replaced with your component. -->
<p>
jnknwqkjnkj<br>
jhiwhiw (this is 36px height)
</p>
</div>
</code>```

ReactJS

```<code>var DivSize = React.createClass({

  render: function() {
    let elHeight = document.getElementById('container').clientHeight
    return <div className="test">Size: <b>{elHeight}px</b> but it should be 18px after the render</div>;
  }
});

ReactDOM.render(
  <DivSize />,
  document.getElementById('container')
);
</code>```

RESULT

```<code>Size: 36px but it should be 18px after the render
</code>```

It's calculating the container height before the render (36px). I want to get the height after the render. The right result should be 18px in this case. jsfiddle

答:
An alternative solution, in case you want to retrieve the size of a React element synchronously without having to visibly render the element, you can use ReactDOMServer and DOMParser.

I use this function to get the height of a my list item renderer when using react-window (react-virtualized) instead of having to hardcode the required itemSize prop for a FixedSizeList.

utilities.js:

```<code>/**
 * @description Common and reusable functions
 *
 * @requires react-dom/server
 *
 * @public
 * @module
 *
 */
import ReactDOMServer from "react-dom/server";

/**
 * @description Retrieve the width and/or heigh of a React element without rendering and committing the element to the DOM.
 *
 * @param {object} elementJSX - The target React element written in JSX.
 * @return {object}
 * @public
 * @function
 *
 * @example
 *
 * const { width, height } = getReactElementSize( <div style={{ width: "20px", height: "40px" }} ...props /> );
 * console.log(`W: ${width}, H: ${height});  // W: 20, H: 40
 *
 */
const getReactElementSize = (elementJSX) => {

    const elementString = ReactDOMServer.renderToStaticMarkup(elementJSX);
    const elementDocument = new DOMParser().parseFromString(elementString, "text/html");
    const elementNode = elementDocument.getRootNode().body.firstChild;

    const container = document.createElement("div");
    const containerStyle = {

        display: "block",
        position: "absolute",
        boxSizing: "border-box",
        margin: "0",
        padding: "0",
        visibility: "hidden"
    };

    Object.assign(container.style, containerStyle);

    container.appendChild(elementNode);
    document.body.appendChild(container);

    const width = container.clientWidth;
    const height = container.clientHeight;

    container.removeChild(elementNode);
    document.body.removeChild(container);

    return {

        width,
        height
    };
};

/**
 * Export module
 *
 */
export {

    getReactElementSize
};
</code>```

Title: ReactJS - Get Height of an element

Body:
How can I get the Height of an element after React renders that element?

HTML

jnknwqkjnkj

jhiwhiw (this is 36px height)

ReactJS

var DivSize = React.createClass({

  render: function() {
    let elHeight = document.getElementById('container').clientHeight
    return
Size: {elHeight}px but it should be 18px after the render
;
  }
});

ReactDOM.render(
  <DivSize />,
  document.getElementById('container')
);

RESULT

Size: 36px but it should be 18px after the render

It's calculating the container height before the render (36px). I want to get the height after the render. The right result should be 18px in this case. jsfiddle

Body:
An alternative solution, in case you want to retrieve the size of a React element synchronously without having to visibly render the element, you can use ReactDOMServer and DOMParser.

I use this function to get the height of a my list item renderer when using react-window (react-virtualized) instead of having to hardcode the required itemSize prop for a FixedSizeList.

utilities.js:

/**
 * @description Common and reusable functions
 *
 * @requires react-dom/server
 *
 * @public
 * @module
 *
 */
import ReactDOMServer from "react-dom/server";

/**
 * @description Retrieve the width and/or heigh of a React element without rendering and committing the element to the DOM.
 *
 * @param {object} elementJSX - The target React element written in JSX.
 * @return {object}
 * @public
 * @function
 *
 * @example
 *
 * const { width, height } = getReactElementSize( <div style={{ width: "20px", height: "40px" }} ...props /> );
 * console.log(`W: ${width}, H: ${height});  // W: 20, H: 40
 *
 */
const getReactElementSize = (elementJSX) => {

    const elementString = ReactDOMServer.renderToStaticMarkup(elementJSX);
    const elementDocument = new DOMParser().parseFromString(elementString, "text/html");
    const elementNode = elementDocument.getRootNode().body.firstChild;

    const container = document.createElement("div");
    const containerStyle = {

        display: "block",
        position: "absolute",
        boxSizing: "border-box",
        margin: "0",
        padding: "0",
        visibility: "hidden"
    };

    Object.assign(container.style, containerStyle);

    container.appendChild(elementNode);
    document.body.appendChild(container);

    const width = container.clientWidth;
    const height = container.clientHeight;

    container.removeChild(elementNode);
    document.body.removeChild(container);

    return {

        width,
        height
    };
};

/**
 * Export module
 *
 */
export {

    getReactElementSize
};


问:
How to fill form with JSON?
I get ajax response as JSON and need to fill a form with it. How to do that in jQuery or something else ? Is something better than using $(json).each() ?

JSON:

```<code>{
  "id" : 12,
  "name": "Jack",
  "description": "Description"
}
</code>```

Form to fill

```<code><form>
  <input type="text" name="id"/>
  <input type="text" name="name"/>
  <input type="text" name="description"/>
</form>
</code>```

答:
Came here searching for a solution that didn't involve jQuery or a brunch of DOM scaning, but didn't find one... so here is my vanilla js solution brought to you other guys that probably ditched jQuery long ago.

const data = {
  "id" : 12,
  "name": "Jack",
  "description": "Description",
  "nonExisting": "works too"
}

const { elements } = document.querySelector('form')

for (const [ key, value ] of Object.entries(data) ) {
  const field = elements.namedItem(key)
  field && (field.value = value)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <input type="text" name="id"/>
  <input type="text" name="name"/>
  <input type="text" name="description"/>
</form></code>```

Title: How to fill form with JSON?

Body:
I get ajax response as JSON and need to fill a form with it. How to do that in jQuery or something else ? Is something better than using $(json).each() ?

JSON:

{
  "id" : 12,
  "name": "Jack",
  "description": "Description"
}

Form to fill

<form>
  <input type="text" name="id"/>
  <input type="text" name="name"/>
  <input type="text" name="description"/>
</form>

Body:
Came here searching for a solution that didn't involve jQuery or a brunch of DOM scaning, but didn't find one... so here is my vanilla js solution brought to you other guys that probably ditched jQuery long ago.

const data = {
  "id" : 12,
  "name": "Jack",
  "description": "Description",
  "nonExisting": "works too"
}

const { elements } = document.querySelector('form')

for (const [ key, value ] of Object.entries(data) ) {
  const field = elements.namedItem(key)
  field && (field.value = value)
}

<form>
  <input type="text" name="id"/>
  <input type="text" name="name"/>
  <input type="text" name="description"/>
</form>


问:
How do I mock a function which is imported with an alias?
Below I have added some dummy code which exactly represent what I am trying to do.

I am importing a function from a class with an alias, I am doing this since the class is running the aliased version itself.

Things I have tried:

http://bhfsteve.blogspot.com/2012/06/patching-tip-using-mocks-in-python-unit.html This does not give a specific solution to the problem.

patched a.dummy.class.function.alias as a.dummy.class.function this allows execution but will not run the alias_function_mocker() as in the class the function is called as alias() and not function()

I tried running as a.dummy.class.function.alias but this results in an attribute error as alias isn't actually an attribute of class(because function() is)

```<code>from a.dummy.class import function as alias

def alias_function_mocker():
    return 0

@patch("a.dummy.class.function.alias", side_effect=alias_function_mocker):
def test_function(mocked_function):
    function_calling_alias()
    return 0

</code>```

What I think the problem roots from is that the class file is calling function using alias and there doesn't seem to be a way to patch aliased function calls. The simple and most naive solution I can think of is just do not use an alias.

答:
You need to mock the object where it is. If you imported the module/function to file.py, you need to mock the object of this file.

If you are using the test in the same file of the method, this could be the solution:

```<code>from os.path import isdir as is_it_a_dir
from unittest.mock import patch

def check(path):
    return is_it_a_dir(path)

with patch('__main__.is_it_a_dir') as mock_isitadir:
    mock_isitadir.return_value = True
    assert check('/any/invalid/path') == True
</code>```

If your test is in another file, than your approch should work.

Body:
Below I have added some dummy code which exactly represent what I am trying to do.

I am importing a function from a class with an alias, I am doing this since the class is running the aliased version itself.

Things I have tried:

http://bhfsteve.blogspot.com/2012/06/patching-tip-using-mocks-in-python-unit.html This does not give a specific solution to the problem.

patched a.dummy.class.function.alias as a.dummy.class.function this allows execution but will not run the alias_function_mocker() as in the class the function is called as alias() and not function()

I tried running as a.dummy.class.function.alias but this results in an attribute error as alias isn't actually an attribute of class(because function() is)

from a.dummy.class import function as alias

def alias_function_mocker():
    return 0

@patch("a.dummy.class.function.alias", side_effect=alias_function_mocker):
def test_function(mocked_function):
    function_calling_alias()
    return 0

What I think the problem roots from is that the class file is calling function using alias and there doesn't seem to be a way to patch aliased function calls. The simple and most naive solution I can think of is just do not use an alias.

Body:
You need to mock the object where it is. If you imported the module/function to file.py, you need to mock the object of this file.

If you are using the test in the same file of the method, this could be the solution:

from os.path import isdir as is_it_a_dir
from unittest.mock import patch

def check(path):
    return is_it_a_dir(path)

with patch('__main__.is_it_a_dir') as mock_isitadir:
    mock_isitadir.return_value = True
    assert check('/any/invalid/path') == True

If your test is in another file, than your approch should work.


问:
Checking if all strings have equal length in a String array in Java
I am trying to solve a question in which I am given a String array of words and I have to check whether they have all same length or not. For instance if am given the array {"apple","purple","lemon"} then my method should return true, and when I am given the array {"red","blue"}, it should return false.

This is what I did so far but it is not working. I appreciate any help.

```<code>public static boolean allEqualLength(String[] myArray){
    int i;
    for(i=0;i<myArray.length;i++){
        if(myArray[i]!=myArray[i+1])
            return false;
        }
    return true,
}
</code>```

答:
If performance is not an issue and you will not use it in 1 million strings or something, in addition to all these answers, here is an one liner:

```<code>boolean allStringsEqualLength = Stream.of(array)
        .map(String::length).distinct().count() == 1;
</code>```

The idea is to map each string to its length. So if distinct() stream contains only one value, that means all strings had the same length.

Body:
I am trying to solve a question in which I am given a String array of words and I have to check whether they have all same length or not. For instance if am given the array {"apple","purple","lemon"} then my method should return true, and when I am given the array {"red","blue"}, it should return false.

This is what I did so far but it is not working. I appreciate any help.

public static boolean allEqualLength(String[] myArray){
    int i;
    for(i=0;i<myArray.length;i++){
        if(myArray[i]!=myArray[i+1])
            return false;
        }
    return true,
}

Body:
If performance is not an issue and you will not use it in 1 million strings or something, in addition to all these answers, here is an one liner:

boolean allStringsEqualLength = Stream.of(array)
        .map(String::length).distinct().count() == 1;

The idea is to map each string to its length. So if distinct() stream contains only one value, that means all strings had the same length.


问:
malformed UTF-8 character when calling rindex() on string containing trademark symbol
I’m having a hard time figuring out why rindex() is raising an exception on the trademark character in my Rails3.0.7 app (ruby 1.8.7):

```<code>irb(main):007:0> "™ foo™".mb_chars.rindex(/\W/)
ActiveSupport::Multibyte::EncodingError: malformed UTF-8 character
from /opt/local/lib/ruby/gems/1.8/gems/activesupport-3.0.7/lib/active_support/multibyte/unicode.rb:72:in `u_unpack'
from /opt/local/lib/ruby/gems/1.8/gems/activesupport-3.0.7/lib/active_support/multibyte/chars.rb:167:in `rindex'
from (irb):7
irb(main):008:0> "™ foo™".mb_chars.index(/\W/)
=> 1
</code>```

But this works fine.

```<code>irb(main):009:0> "® foo®".mb_chars.rindex(/\W/)
=> 1
irb(main):010:0> "® foo®".mb_chars.index(/\W/)
=> 1
</code>```

答: I suspect that your source code encoding could be the cause. Check to see exactly what this string contains at runtime. This may help you http://ruby-unicode.rubyforge.org/doc/</p>

Body:
I’m having a hard time figuring out why rindex() is raising an exception on the trademark character in my Rails3.0.7 app (ruby 1.8.7):

irb(main):007:0> "™ foo™".mb_chars.rindex(/\W/)
ActiveSupport::Multibyte::EncodingError: malformed UTF-8 character
from /opt/local/lib/ruby/gems/1.8/gems/activesupport-3.0.7/lib/active_support/multibyte/unicode.rb:72:in `u_unpack'
from /opt/local/lib/ruby/gems/1.8/gems/activesupport-3.0.7/lib/active_support/multibyte/chars.rb:167:in `rindex'
from (irb):7
irb(main):008:0> "™ foo™".mb_chars.index(/\W/)
=> 1

But this works fine.

irb(main):009:0> "® foo®".mb_chars.rindex(/\W/)
=> 1
irb(main):010:0> "® foo®".mb_chars.index(/\W/)
=> 1


问:
how to solve this Expected an assignment or function call and instead saw an expression no-unused-expressions
problem :

./src/components/main.js
  Line 7:  Expected an assignment or function call and instead saw an expression  no-unused-expressions

Search for the keywords to learn more about each error.

```<code>import React from 'react';
import { Switch, Route } from 'react-router-dom';
import LandingPage from './landingpage'

const Main = () => {
   <Switch>
      <Route exact path="/" component={LandingPage}/>
   </Switch>
}

export default Main;
</code>```

how can i solve this, please help me

答:
Just Change Bracket Braces To parenthesis.
when you write JSX inside the function you need to use parenthesis not Bracket because your function has JSX.
{}=>()</p>

```<code>import React from 'react';
import { Switch, Route } from 'react-router-dom';
import LandingPage from './landingpage'

const Main = () => (
   <Switch>
      <Route exact path="/" component={LandingPage}/>
   </Switch>
)

export default Main
</code>```

Body:
problem :

./src/components/main.js
  Line 7:  Expected an assignment or function call and instead saw an expression  no-unused-expressions

Search for the keywords to learn more about each error.

import React from 'react';
import { Switch, Route } from 'react-router-dom';
import LandingPage from './landingpage'

const Main = () => {
   <Switch>
      <Route exact path="/" component={LandingPage}/>
   </Switch>
}

export default Main;

how can i solve this, please help me

Body:
Just Change Bracket Braces To parenthesis.
when you write JSX inside the function you need to use parenthesis not Bracket because your function has JSX.
{}=>()

import React from 'react';
import { Switch, Route } from 'react-router-dom';
import LandingPage from './landingpage'

const Main = () => (
   <Switch>
      <Route exact path="/" component={LandingPage}/>
   </Switch>
)

export default Main


问:
Kernel Error using Julia on Jupyter Notebook
Hi so I'm quite new with using Julia and Notebook. When I first downloaded Julia, everything worked great, but then suddenly the kernel said it was dead and I couldn't get it to work again (restarted and tried reinstalling)

I ended up downloading a newer version of Julia (1.4.1 to 1.4.2), but that didn't seem to help. Now however, instead of the kernel being dead, there is an error, and I unfortunately have no idea what it means or how to fix it.

I want to preface this by saying that I accidentally deleted the conda folder in my C drive that notebook needed without realizing what it was, but I had thought it reinstalled through Julia, I dont know if that makes a difference or not. Additionally, I had to use python for my school, but deleted it since I don't need it anymore, so I'm unsure of if that has an effect (since I'm aware that notebook uses python stuff)

The error is as follows:

```<code>Traceback (most recent call last):

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\tornado\web.py", line 1703, in _execute
    result = await result

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\tornado\gen.py", line 742, in run
    yielded = self.gen.throw(*exc_info)  # type: ignore

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\notebook\services\sessions\handlers.py", line 72, in post
    type=mtype))

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\tornado\gen.py", line 735, in run
    value = future.result()

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\tornado\gen.py", line 742, in run
    yielded = self.gen.throw(*exc_info)  # type: ignore

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 88, in create_session
    kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name)

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\tornado\gen.py", line 735, in run
    value = future.result()

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\tornado\gen.py", line 742, in run
    yielded = self.gen.throw(*exc_info)  # type: ignore

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 101, in start_kernel_for_session
    self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_name)

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\tornado\gen.py", line 735, in run
    value = future.result()

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\tornado\gen.py", line 209, in wrapper
    yielded = next(result)

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\notebook\services\kernels\kernelmanager.py", line 168, in start_kernel
    super(MappingKernelManager, self).start_kernel(**kwargs)

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\jupyter_client\multikernelmanager.py", line 158, in start_kernel
    km.start_kernel(**kwargs)

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\jupyter_client\manager.py", line 305, in start_kernel
    self.kernel = self._launch_kernel(kernel_cmd, **kw)

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\jupyter_client\manager.py", line 212, in _launch_kernel
    return launch_kernel(kernel_cmd, **kw)

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\jupyter_client\launcher.py", line 135, in launch_kernel
    proc = Popen(cmd, **kwargs)

File "C:\Users\Adam\.julia\conda\3\lib\subprocess.py", line 800, in __init__
    restore_signals, start_new_session)

File "C:\Users\Adam\.julia\conda\3\lib\subprocess.py", line 1207, in _execute_child
    startupinfo)

FileNotFoundError: [WinError 2] The system cannot find the file specified
</code>```

Thank you in advance to anyone who can help me.

答:
By default, IJulia should install its own Miniconda, so you fiddling with a separate Python installation shouldn't hurt.

The first port of call when you can't get the notebook server to run is always to re-run the build script, which is run when you first install IJulia. Enter the REPL package mode by pressing ] and run build IJulia. This should reinstall dependencies as necessary, and re-register the kernel of the Julia version you're in with Jupyter.

Body:
Hi so I'm quite new with using Julia and Notebook. When I first downloaded Julia, everything worked great, but then suddenly the kernel said it was dead and I couldn't get it to work again (restarted and tried reinstalling)

I ended up downloading a newer version of Julia (1.4.1 to 1.4.2), but that didn't seem to help. Now however, instead of the kernel being dead, there is an error, and I unfortunately have no idea what it means or how to fix it.

I want to preface this by saying that I accidentally deleted the conda folder in my C drive that notebook needed without realizing what it was, but I had thought it reinstalled through Julia, I dont know if that makes a difference or not. Additionally, I had to use python for my school, but deleted it since I don't need it anymore, so I'm unsure of if that has an effect (since I'm aware that notebook uses python stuff)

The error is as follows:

Traceback (most recent call last):

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\tornado\web.py", line 1703, in _execute
    result = await result

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\tornado\gen.py", line 742, in run
    yielded = self.gen.throw(*exc_info)  # type: ignore

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\notebook\services\sessions\handlers.py", line 72, in post
    type=mtype))

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\tornado\gen.py", line 735, in run
    value = future.result()

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\tornado\gen.py", line 742, in run
    yielded = self.gen.throw(*exc_info)  # type: ignore

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 88, in create_session
    kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name)

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\tornado\gen.py", line 735, in run
    value = future.result()

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\tornado\gen.py", line 742, in run
    yielded = self.gen.throw(*exc_info)  # type: ignore

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 101, in start_kernel_for_session
    self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_name)

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\tornado\gen.py", line 735, in run
    value = future.result()

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\tornado\gen.py", line 209, in wrapper
    yielded = next(result)

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\notebook\services\kernels\kernelmanager.py", line 168, in start_kernel
    super(MappingKernelManager, self).start_kernel(**kwargs)

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\jupyter_client\multikernelmanager.py", line 158, in start_kernel
    km.start_kernel(**kwargs)

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\jupyter_client\manager.py", line 305, in start_kernel
    self.kernel = self._launch_kernel(kernel_cmd, **kw)

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\jupyter_client\manager.py", line 212, in _launch_kernel
    return launch_kernel(kernel_cmd, **kw)

File "C:\Users\Adam\.julia\conda\3\lib\site-packages\jupyter_client\launcher.py", line 135, in launch_kernel
    proc = Popen(cmd, **kwargs)

File "C:\Users\Adam\.julia\conda\3\lib\subprocess.py", line 800, in __init__
    restore_signals, start_new_session)

File "C:\Users\Adam\.julia\conda\3\lib\subprocess.py", line 1207, in _execute_child
    startupinfo)

FileNotFoundError: [WinError 2] The system cannot find the file specified

Thank you in advance to anyone who can help me.


问:
Is it possible to use the capture groups from the regex of an express route?
I'm working on a fairly large node/express app using the GOV.UK Prototyping Kit. I have separated multiple instances of the prototype into standalone versions for archival purposes e.g. this isn't a build it once 'DRY' approach but rather there's quite a bit of duplication as the prototypes evolve (sometimes significantly). The crucial thing is that each version e.g. /phase/release/ is suitably separated.

I've separated the routes quite nicely but the final thing that would help would be to have a dynamic route.use -> require so that I don't have to manually update the top-level routes.js file for each version release.

I use regex matching in my routes quite a lot so I'm fairly familiar with that, but what I'm wondering is how I can use the details of the match to dynamically build the require. Or perhaps use something in req.params - but I don't think that's available outside of a route.

Here's an outline of my code. The static route (R1) works fine but neither of the dynamic routes (R2/R3) work (when uncommented):

```<code>const express = require('express')
const router = express.Router()

router.use('/:phase/:release', function (req, res, next) {

  // Make phase and release available in subsequent routes
  let prototype = {}
  prototype.phase = req.params.phase
  prototype.release = req.params.release
  req.session.data.prototype = prototype

  next()

})

// Phase/release specific routes
// -----------------------------

// R1. This works
router.use('/test/a/', require('./views/test/a/_routes.js'));

// R2. But a dynamic version world be better?...
// router.use(/(alpha|beta|test)\/([abc])\//, require('./views/' + \1 + '/' + \2 '/_routes.js'));
// R3. ...or...
// router.use('/:phase/:release/', require('./views/' + req.params.phase + '/' + req.params.release '/_routes.js'));
</code>```

Ultimately I think my approach is wrong and that it's not possible to reference the regex capture groups this way, but equally I don't think I can access the req object (and therefore req.params) as part of the require path.

I would expect there to be a way to use information known prior to making the require within the constructed require path but I just can't work out how.

Any input/help much appreciated.

答:
Express documentation for router.get documents in the last exemple that when you use a regex for the route parameter, the captured groups are available in req.params by position (tested on Express 4.17). This also works with a required router handler instead of a function (as you do), of course.

```<code>router.use(/(alpha|beta|test)\/([abc])\//, (req, res) => {
  console(req.params[0]); // will show the first captured group: alpha, beta or test
  console(req.params[1]); // will show the 2nd captured group
});
</code>```

Body:
I'm working on a fairly large node/express app using the GOV.UK Prototyping Kit. I have separated multiple instances of the prototype into standalone versions for archival purposes e.g. this isn't a build it once 'DRY' approach but rather there's quite a bit of duplication as the prototypes evolve (sometimes significantly). The crucial thing is that each version e.g. /phase/release/ is suitably separated.

I've separated the routes quite nicely but the final thing that would help would be to have a dynamic route.use -> require so that I don't have to manually update the top-level routes.js file for each version release.

I use regex matching in my routes quite a lot so I'm fairly familiar with that, but what I'm wondering is how I can use the details of the match to dynamically build the require. Or perhaps use something in req.params - but I don't think that's available outside of a route.

Here's an outline of my code. The static route (R1) works fine but neither of the dynamic routes (R2/R3) work (when uncommented):

const express = require('express')
const router = express.Router()

router.use('/:phase/:release', function (req, res, next) {

  // Make phase and release available in subsequent routes
  let prototype = {}
  prototype.phase = req.params.phase
  prototype.release = req.params.release
  req.session.data.prototype = prototype

  next()

})

// Phase/release specific routes
// -----------------------------

// R1. This works
router.use('/test/a/', require('./views/test/a/_routes.js'));

// R2. But a dynamic version world be better?...
// router.use(/(alpha|beta|test)\/([abc])\//, require('./views/' + \1 + '/' + \2 '/_routes.js'));
// R3. ...or...
// router.use('/:phase/:release/', require('./views/' + req.params.phase + '/' + req.params.release '/_routes.js'));

Ultimately I think my approach is wrong and that it's not possible to reference the regex capture groups this way, but equally I don't think I can access the req object (and therefore req.params) as part of the require path.

I would expect there to be a way to use information known prior to making the require within the constructed require path but I just can't work out how.

Any input/help much appreciated.

Body:
Express documentation for router.get documents in the last exemple that when you use a regex for the route parameter, the captured groups are available in req.params by position (tested on Express 4.17). This also works with a required router handler instead of a function (as you do), of course.

router.use(/(alpha|beta|test)\/([abc])\//, (req, res) => {
  console(req.params[0]); // will show the first captured group: alpha, beta or test
  console(req.params[1]); // will show the 2nd captured group
});


问:
Convert a dictionary of strings to a dictionary of numpy arrays
I have a dictionary structured similar to below.

```<code>test_dict = {1: 'I run fast', 2: 'She runs', 3: 'How are you?'}
</code>```

What I'm trying to do is convert all the strings to 4x4 numpy arrays where each word is in it's own row and each letter occupies one cell of the array, populated with blanks for lines that wouldn't fill the entire row a whole row of blanks for sentences that are less than 4 words long. I also need to be able to tie it back to the ID, so the result needs to be in some format that can allow for referencing each array by it's ID later on.

I don't know of any pre built functions that can handle something like this, but I would be happy to be wrong. For now I've been trying to write a loop to handle it. Below is obviously incomplete because I'm stuck at the point of creating an array in the structure I would like.

```<code>for k in test_dict.keys():
    sentence = test_dict.getvalues(k)
    sentence_ascii = [ord(c) for c in sentence]
    sentence_array = np.array(sentence_ascii)
</code>```

Body:
I have a dictionary structured similar to below.

test_dict = {1: 'I run fast', 2: 'She runs', 3: 'How are you?'}

What I'm trying to do is convert all the strings to 4x4 numpy arrays where each word is in it's own row and each letter occupies one cell of the array, populated with blanks for lines that wouldn't fill the entire row a whole row of blanks for sentences that are less than 4 words long. I also need to be able to tie it back to the ID, so the result needs to be in some format that can allow for referencing each array by it's ID later on.

I don't know of any pre built functions that can handle something like this, but I would be happy to be wrong. For now I've been trying to write a loop to handle it. Below is obviously incomplete because I'm stuck at the point of creating an array in the structure I would like.

for k in test_dict.keys():
    sentence = test_dict.getvalues(k)
    sentence_ascii = [ord(c) for c in sentence]
    sentence_array = np.array(sentence_ascii)

Body:
Is this what you mean?

{
    key: np.array([list(word.ljust(4)) for word in val.split()])
    for key, val in test_dict.items()
}

output:

{1: array([['I', ' ', ' ', ' '],
           ['r', 'u', 'n', ' '],
           ['f', 'a', 's', 't']], dtype='<U1'),
 2: array([['S', 'h', 'e', ' '],
           ['r', 'u', 'n', 's']], dtype='<U1'),
 3: array([['H', 'o', 'w', ' '],
           ['a', 'r', 'e', ' '],
           ['y', 'o', 'u', '?']], dtype='<U1')}


问:
VueJs SPA execute function on click button
I need to run refreshMailList function from mail-list tag catching the click event from mail-list component.

I have this vue instance with this component:

```<code>Vue.component('mail-list', {
  props: ['inboxmail'],
  template:
  `
  <div>
    <h4>{{inboxmail}}</h4>
    <button>Refresh</button>
  </div>
  `
  });

//Creating the Vue object.
let options = {
  el: "#app",
  data: {
    pollingId: null,
    inbox: ''
  },

  created: function() {
    this.refreshMailList()
  },
methods:{
    refreshMailList: function(){
      fetch('/inbox')
      .then(response => response.json())
      .then(aJson => {
        this.inbox = aJson;
      })
    },

  } //end methods
} //end options

//ViewModel (vm)
let vm = new Vue(options);
</code>```

And I have this index.html:

```<code>      <div id="app">
        <mail-list v-bind:inboxmail="inbox" @refresh='refreshMailList'></mail-list>
      </div>
</code>```

答:
You need to emit the event from inside the mail-list component.

Try this snippet:

```<code> Vue.component('mail-list', {
  props: ['inboxmail'],
  methods: {
    refresh: function() {
      this.$emit('refresh');
    },
  },
  template:
  `
  <div>
    <h4>{{inboxmail}}</h4>
    <button @click="refresh">Refresh</button>
  </div>
  `
  });
</code>```

Body:
I need to run refreshMailList function from mail-list tag catching the click event from mail-list component.

I have this vue instance with this component:

Vue.component('mail-list', {
  props: ['inboxmail'],
  template:
  `

{{inboxmail}}

    <button>Refresh</button>

  `
  });

//Creating the Vue object.
let options = {
  el: "#app",
  data: {
    pollingId: null,
    inbox: ''
  },

  created: function() {
    this.refreshMailList()
  },
methods:{
    refreshMailList: function(){
      fetch('/inbox')
      .then(response => response.json())
      .then(aJson => {
        this.inbox = aJson;
      })
    },

  } //end methods
} //end options

//ViewModel (vm)
let vm = new Vue(options);

And I have this index.html:

        <mail-list v-bind:inboxmail="inbox" @refresh='refreshMailList'></mail-list>

Body:
You need to emit the event from inside the mail-list component.

Try this snippet:

 Vue.component('mail-list', {
  props: ['inboxmail'],
  methods: {
    refresh: function() {
      this.$emit('refresh');
    },
  },
  template:
  `
  <div>
    <h4>{{inboxmail}}</h4>
    <button @click="refresh">Refresh</button>
  </div>
  `
  });


问:
Python3: Why is my else statement activating regardless of multiple if statements being true
```<code>tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

if len(tweet) <= 160:
    if 'LOL' in tweet:
        print('Laugh out loud')
    if 'BFN' in tweet:
        print('Bye for now')
    if 'BRB' in tweet:
        print('Be right back')
    if 'IRL' in tweet:
        print('In real life')
    if 'FTW' in tweet:
        print('For the win')
    if 'LMFAO' in tweet:
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        print('Laugh my a** off')
    else:
        print('You didn\'t use any abbreviations')
elif len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')
</code>```

So, for example if I run this program and input:
LOL BRB

The output is:
Laugh out loud
Be right back
You didn't use any abbreviations

Whereas the output I want for that input is:
Laugh out loud
Be right back

As far as I can tell the indentation is correct. Also we haven't gone over the 'break' or 'enumerate' functions, so we are not expected to use these to attain the desired result.

Thank you for the help!!

This is the code in working order after everyone's help:

```<code>tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

tweet_abbrev = False

if len(tweet) <= 160:
    if 'LOL' in tweet:
        tweet_abbrev = True
        print('Laugh out loud')
    if 'BFN' in tweet:
        tweet_abbrev = True
        print('Bye for now')
    if 'BRB' in tweet:
        tweet_abbrev = True
        print('Be right back')
    if 'IRL' in tweet:
        tweet_abbrev = True
        print('In real life')
    if 'FTW' in tweet:
        tweet_abbrev = True
        print('For the win')
    if 'LMFAO' in tweet:
        tweet_abbrev = True
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        tweet_abbrev = True
        print('Laugh my a** off')
    if not tweet_abbrev:
        print('You didn\'t use any abbreviations')
if len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')
</code>```

Thank you everyone for the quick responses!!!

答:
Keep track of how many if conditions were satisfied and at the end, instead of using else, check if that number of satisfied conditions is greater than 0. If not, you didn't use any abbreviations.

Alternatively, you could use a boolean or something, that's up to you.

Edit: the uncommented code is for boolean, and the comments show how you could do the same thing with a counter.

x = input("enter numbers")

# number_of_numbers = 0
valid_number = False

if "1" in x:
    valid_number = True
    # number_of_numbers += 1
    print("1")
if "2" in x:
    valid_number = True
    # number_of_numbers += 1
    print("2")
...

# if not number_of_numbers:
if not valid_number:
    print("You didn't use any numbers")
```

Body:
tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

if len(tweet) <= 160:
    if 'LOL' in tweet:
        print('Laugh out loud')
    if 'BFN' in tweet:
        print('Bye for now')
    if 'BRB' in tweet:
        print('Be right back')
    if 'IRL' in tweet:
        print('In real life')
    if 'FTW' in tweet:
        print('For the win')
    if 'LMFAO' in tweet:
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        print('Laugh my a** off')
    else:
        print('You didn\'t use any abbreviations')
elif len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')

So, for example if I run this program and input:
LOL BRB

The output is:
Laugh out loud
Be right back
You didn't use any abbreviations

Whereas the output I want for that input is:
Laugh out loud
Be right back

As far as I can tell the indentation is correct. Also we haven't gone over the 'break' or 'enumerate' functions, so we are not expected to use these to attain the desired result.

Thank you for the help!!

This is the code in working order after everyone's help:

tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

tweet_abbrev = False

if len(tweet) <= 160:
    if 'LOL' in tweet:
        tweet_abbrev = True
        print('Laugh out loud')
    if 'BFN' in tweet:
        tweet_abbrev = True
        print('Bye for now')
    if 'BRB' in tweet:
        tweet_abbrev = True
        print('Be right back')
    if 'IRL' in tweet:
        tweet_abbrev = True
        print('In real life')
    if 'FTW' in tweet:
        tweet_abbrev = True
        print('For the win')
    if 'LMFAO' in tweet:
        tweet_abbrev = True
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        tweet_abbrev = True
        print('Laugh my a** off')
    if not tweet_abbrev:
        print('You didn\'t use any abbreviations')
if len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')

Thank you everyone for the quick responses!!!


问:
Graph disconnected: cannot obtain value for tensor Tensor("input_1:0", shape=(None, 299, 299, 3), dtype=float32) at layer "input_1"
I am trying to use heatmaps for Xception model (with modified top layer):

import tensorflow as to
import cv2
import numpy as np
label = 1
IMAGE_PATH = '/home/piyush/Desktop/HV/hv_2/deep-viz-keras/images/doberman.png'

img = tf.keras.preprocessing.image.load_img(IMAGE_PATH, target_size=(299, 299))
img = tf.keras.preprocessing.image.img_to_array(img)

model_path = '/home/piyush/Desktop/temp/model.h5'
model = tf.keras.models.load_model(model_path)
inputs = tf.keras.Input(shape=(299,299,3))
#print(model.summary())
#print([layer.shape for layer in model.get_layer('xception').layers])
final = tf.keras.Model(inputs=model.inputs, outputs=model.output)
print(model.inputs)
#extractor = tf.keras.Model(inputs=inputs, outputs=[layer.output for layer in model.layers])
conv_layer = tf.keras.Model(inputs=inputs,outputs=model.get_layer('xception').get_layer('block14_sepconv2_act').output)
```

<p>If I run this, I got the following error:</p>

```        conv_layer = tf.keras.Model(inputs=inputs, outputs=model.get_layer('xception').get_layer('block14_sepconv2_act').output)

ValueError: Graph disconnected: cannot obtain value for tensor Tensor("input_1:0", shape=(None, 299, 299, 3), dtype=float32) at layer "input_1". The following previous layers were accessed without issue: []
```

答:
You define

```<code>inputs = tf.keras.Input(shape=(299,299,3))
</code>```

but then never use this variable in the model. You probably simply want

```<code>inputs = model.inputs
</code>```

since you are loading an existing model, not creating a new one.

Body:
I am trying to use heatmaps for Xception model (with modified top layer):

import tensorflow as to
import cv2
import numpy as np
label = 1
IMAGE_PATH = '/home/piyush/Desktop/HV/hv_2/deep-viz-keras/images/doberman.png'

img = tf.keras.preprocessing.image.load_img(IMAGE_PATH, target_size=(299, 299))
img = tf.keras.preprocessing.image.img_to_array(img)

model_path = '/home/piyush/Desktop/temp/model.h5'
model = tf.keras.models.load_model(model_path)
inputs = tf.keras.Input(shape=(299,299,3))
#print(model.summary())
#print([layer.shape for layer in model.get_layer('xception').layers])
final = tf.keras.Model(inputs=model.inputs, outputs=model.output)
print(model.inputs)
#extractor = tf.keras.Model(inputs=inputs, outputs=[layer.output for layer in model.layers])
conv_layer = tf.keras.Model(inputs=inputs,outputs=model.get_layer('xception').get_layer('block14_sepconv2_act').output)

If I run this, I got the following error:

        conv_layer = tf.keras.Model(inputs=inputs, outputs=model.get_layer('xception').get_layer('block14_sepconv2_act').output)

ValueError: Graph disconnected: cannot obtain value for tensor Tensor("input_1:0", shape=(None, 299, 299, 3), dtype=float32) at layer "input_1". The following previous layers were accessed without issue: []

Body:
You define

inputs = tf.keras.Input(shape=(299,299,3))

but then never use this variable in the model. You probably simply want

inputs = model.inputs

since you are loading an existing model, not creating a new one.


问:
Calculating percentages with GROUP BY query
I have a table with 3 columns which looks like this:

```<code>File    User     Rating (1-5)
------------------------------
00001    1        3
00002    1        4
00003    2        2
00004    3        5
00005    4        3
00005    3        2
00006    2        3
Etc.
</code>```

I want to generate a query that outputs the following (for each user and rating, display the number of files as well as percentage of files):

```<code>User    Rating   Count   Percentage
-----------------------------------
1       1         3      .18
1       2         6      .35
1       3         8      .47
2       5         12     .75
2       3         4      .25
</code>```

With Postgresql, I know how to create a query that includes the first 3 columns using the following query, but I can't figure out how to calculate percentage within the GROUP BY:

```<code>SELECT
    User,
    Rating,
    Count(*)
FROM
    Results
GROUP BY
    User, Rating
ORDER BY
    User, Rating
</code>```

Here I want the percentage calculation to apply to each user/rating group.

答: The best way to do this would be with window functions.</p>

Body:
I have a table with 3 columns which looks like this:

File    User     Rating (1-5)
------------------------------
00001    1        3
00002    1        4
00003    2        2
00004    3        5
00005    4        3
00005    3        2
00006    2        3
Etc.

I want to generate a query that outputs the following (for each user and rating, display the number of files as well as percentage of files):

User    Rating   Count   Percentage
-----------------------------------
1       1         3      .18
1       2         6      .35
1       3         8      .47
2       5         12     .75
2       3         4      .25

With Postgresql, I know how to create a query that includes the first 3 columns using the following query, but I can't figure out how to calculate percentage within the GROUP BY:

SELECT
    User,
    Rating,
    Count(*)
FROM
    Results
GROUP BY
    User, Rating
ORDER BY
    User, Rating

Here I want the percentage calculation to apply to each user/rating group.


问:
How do I check if the Flutter application is in the foreground or not?
I don't want to show notification when the app is in foreground.
How can I check live state of my app?</p>

答:
To extend on @CopsOnRoad's answer, you can use a switch statement to make it nice and neat:

```<code>@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        print("app in resumed");
        break;
      case AppLifecycleState.inactive:
        print("app in inactive");
        break;
      case AppLifecycleState.paused:
        print("app in paused");
        break;
      case AppLifecycleState.detached:
        print("app in detached");
        break;
    }
}
</code>```

Body:
To extend on @CopsOnRoad's answer, you can use a switch statement to make it nice and neat:

@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        print("app in resumed");
        break;
      case AppLifecycleState.inactive:
        print("app in inactive");
        break;
      case AppLifecycleState.paused:
        print("app in paused");
        break;
      case AppLifecycleState.detached:
        print("app in detached");
        break;
    }
}


问:
Middleware implementation not working for some routes
In my project, I have 2 different functions serving as middleware, which are in a separate file in a separate directory, and I have imported them in my route files.
However, one of the functions executes properly while the other throws and error

The first middleware function (which is functioning properly) is :-

```<code>isLoggedIn : function(req,res,next){
        if(req.isAuthenticated()){
            return next();
        }
        res.redirect("/login");
    },
</code>```

The other function (not working) is :-

```<code>checkCampgroundOwnership : function(req,res,next){
        if(req.isAuthenticated()){
                Campground.findById(req.params.id, function(err,foundCamp){
                    if(err){
                        res.redirect("back");
                    }
                    else{
                        if(foundCamp.author.id.equals(req.user._id)){
                            return next();
                        }
                        else{
                            res.redirect("back");
                        }
                    }
                })
            }
            else{
                res.redirect("back");
            }
        }
</code>```

I'm implementing them in my routes as follows :-

```<code>router.post("/", middleware.isLoggedIn, function(req,res){
    req.body.description = req.sanitize(req.body.description);
    Campground.create(req.body.camp, function(err,created){
        if(err){
            console.log(err);
        }
        else{
            created.author.id = req.user.id;
            created.author.username = req.user.username;
            created.save();
            res.redirect("/campgrounds");
        }
    })
})

router.put("/:id", middleware.checkCampgroundOwenership, function(req,res){
    Campground.findByIdAndUpdate(req.params.id, req.body.camp, function(err,result){
        if(err){
            console.log(err)
        }
        else{
            res.redirect("/campgrounds/"+ req.params.id);
        }
    })
})
</code>```

The error which is generated is as follows :-

Error: Route.get() requires a callback function but got a [object
  Undefined]

What is the problem and how to solve it

答:
You have to declare your isLoggedIn and checkCampgroundOwnership as follow:

```<code>exports.isLoggedIn = (req, res, next) => {
   //your code...
};
</code>```

So you can import in your routes file.

Body:
In my project, I have 2 different functions serving as middleware, which are in a separate file in a separate directory, and I have imported them in my route files.
However, one of the functions executes properly while the other throws and error

The first middleware function (which is functioning properly) is :-

isLoggedIn : function(req,res,next){
        if(req.isAuthenticated()){
            return next();
        }
        res.redirect("/login");
    },

The other function (not working) is :-

checkCampgroundOwnership : function(req,res,next){
        if(req.isAuthenticated()){
                Campground.findById(req.params.id, function(err,foundCamp){
                    if(err){
                        res.redirect("back");
                    }
                    else{
                        if(foundCamp.author.id.equals(req.user._id)){
                            return next();
                        }
                        else{
                            res.redirect("back");
                        }
                    }
                })
            }
            else{
                res.redirect("back");
            }
        }

I'm implementing them in my routes as follows :-

router.post("/", middleware.isLoggedIn, function(req,res){
    req.body.description = req.sanitize(req.body.description);
    Campground.create(req.body.camp, function(err,created){
        if(err){
            console.log(err);
        }
        else{
            created.author.id = req.user.id;
            created.author.username = req.user.username;
            created.save();
            res.redirect("/campgrounds");
        }
    })
})

router.put("/:id", middleware.checkCampgroundOwenership, function(req,res){
    Campground.findByIdAndUpdate(req.params.id, req.body.camp, function(err,result){
        if(err){
            console.log(err)
        }
        else{
            res.redirect("/campgrounds/"+ req.params.id);
        }
    })
})

The error which is generated is as follows :-

Error: Route.get() requires a callback function but got a [object
  Undefined]

What is the problem and how to solve it

Body:
You have to declare your isLoggedIn and checkCampgroundOwnership as follow:

exports.isLoggedIn = (req, res, next) => {
   //your code...
};

So you can import in your routes file.


问:
How to pass item id to Swipeable to delete or edit item with this id
Im using: react-native, expo,

react-native-gesture-handler/Swipeable

here is a code of screen https://github.com/ArturScwaiberov/react-native-dental-app/blob/master/screens/HomeScreen.js

In my app there is list of appointments rendered by SectionList.

In renderItem I created two buttons, one of them is to delete item.

So, I cant understand how should I pass appointment ID to renderRightActions to delete or edit this current appointment.. please help me find out the solution!

Here is my HomeScreen code review:

```<code>const HomeScreen = ({ navigation }) => {
    const [data, setData] = useState(null)
    const [refreshing, setRefreshing] = useState(false)

    const fetchAppointments = () => {
        setRefreshing(true)
        appointmentsApi
            .get()
            .then(({ data }) => {
                setData(data.message)
                setRefreshing(false)
            })
            .catch((e) => {
                setRefreshing(false)
                console.log(e)
            })
    }

    useEffect(fetchAppointments, [])

    const removeAppointment = (id) => {
        console.log(id)
        const result = data.map((group) => {
            group.data = group.data.filter((item) => item._id !== id)
            return group
        })
        setData(result)
        //appointmentsApi.remove(id)
    }

    renderRightAction = (text, color, x, progress) => {
        const trans = progress.interpolate({
            inputRange: [0, 1],
            outputRange: [x, 0],
        })

        const pressHandler = () => {
            if (text === 'pencil') {
                alert('hey')
            } else {
                //but how to get over here the ID of item from SectionList?
                removeAppointment(id)
            }
        }

        return (
            <Animated.View style={{ flex: 1, transform: [{ translateX: trans }] }}>
                <RectButton
                    style={{
                        alignItems: 'center',
                        flex: 1,
                        justifyContent: 'center',
                        backgroundColor: color,
                    }}
                    onPress={pressHandler}
                >
                    <ActionText>
                        <Octicons name={text} size={24} color='white' />
                    </ActionText>
                </RectButton>
            </Animated.View>
        )
    }

    renderRightActions = (progress) => (
        <RightButtonsHandler>
            {renderRightAction('pencil', '#B4C1CB', 160, progress)}
            {renderRightAction('trashcan', '#F85A5A', 80, progress)}
        </RightButtonsHandler>
    )

    return (
        <Container>
            <SectionList
                style={{ paddingLeft: 20, paddingRight: 20 }}
                sections={data}
                keyExtractor={(item, index) => item + index}
                renderItem={({ item }) => (
                    <Swipeable renderRightActions={renderRightActions} friction={2}>
                        <Appointment navigation={navigation} item={item} />
                    </Swipeable>
                )}
                renderSectionHeader={({ section: { title } }) => <SectionTitle>{title}</SectionTitle>}
                refreshControl={<RefreshControl refreshing={refreshing} onRefresh={fetchAppointments} />}
            />
            <PluseButton
                style={{
                    shadowColor: '#2A86FF',
                    shadowOffset: {
                        width: 0,
                        height: 4,
                    },
                    shadowOpacity: 0.3,
                    shadowRadius: 4.65,
                    elevation: 8,
                }}
                onPress={() => navigation.navigate('AddPatient')}
            >
                <Ionicons name='ios-add' size={32} color='white' />
            </PluseButton>
        </Container>
    )
}
</code>```

答:
You only need to pass the item id as a function param.

```<code>renderRightActions={(progress) => renderRightActions(progress, item.id)}
</code>```

I made all changes. Try this code:

const HomeScreen = ({ navigation }) => {
    const [data, setData] = useState(null)
    const [refreshing, setRefreshing] = useState(false)

    const fetchAppointments = () => {
        setRefreshing(true)
        appointmentsApi
            .get()
            .then(({ data }) => {
                setData(data.message)
                setRefreshing(false)
            })
            .catch((e) => {
                setRefreshing(false)
                console.log(e)
            })
    }

    useEffect(fetchAppointments, [])

    const removeAppointment = (id) => {
        console.log(id)
        const result = data.map((group) => {
            group.data = group.data.filter((item) => item._id !== id)
            return group
        })
        setData(result)
        //appointmentsApi.remove(id)
    }

    renderRightAction = (text, color, x, progress, id) => {
        const trans = progress.interpolate({
            inputRange: [0, 1],
            outputRange: [x, 0],
        })

        const pressHandler = () => {
            if (text === 'pencil') {
                alert('hey')
            } else {
                // but how to get over here the ID of item from SectionList?
                removeAppointment(id) // its simple! :)
            }
        }

        return (
            <Animated.View style={{ flex: 1, transform: [{ translateX: trans }] }}>
                <RectButton
                    style={{
                        alignItems: 'center',
                        flex: 1,
                        justifyContent: 'center',
                        backgroundColor: color,
                    }}
                    onPress={pressHandler}
                >
                    <ActionText>
                        <Octicons name={text} size={24} color='white' />
                    </ActionText>
                </RectButton>
            </Animated.View>
        )
    }

    renderRightActions = (progress, id) => (
        <RightButtonsHandler>
            {renderRightAction('pencil', '#B4C1CB', 160, progress, id)}
            {renderRightAction('trashcan', '#F85A5A', 80, progress, id)}
        </RightButtonsHandler>
    )

    return (
        <Container>
            <SectionList
                style={{ paddingLeft: 20, paddingRight: 20 }}
                sections={data}
                keyExtractor={(item, index) => item + index}
                renderItem={({ item }) => (
                    <Swipeable renderRightActions={(progress) => renderRightActions(progress, item.id)} friction={2}>
                        <Appointment navigation={navigation} item={item} />
                    </Swipeable>
                )}
                renderSectionHeader={({ section: { title } }) => <SectionTitle>{title}</SectionTitle>}
                refreshControl={<RefreshControl refreshing={refreshing} onRefresh={fetchAppointments} />}
            />
            <PluseButton
                style={{
                    shadowColor: '#2A86FF',
                    shadowOffset: {
                        width: 0,
                        height: 4,
                    },
                    shadowOpacity: 0.3,
                    shadowRadius: 4.65,
                    elevation: 8,
                }}
                onPress={() => navigation.navigate('AddPatient')}
            >
                <Ionicons name='ios-add' size={32} color='white' />
            </PluseButton>
        </Container>
    )
}
```

Body:
Im using: react-native, expo,

react-native-gesture-handler/Swipeable

here is a code of screen https://github.com/ArturScwaiberov/react-native-dental-app/blob/master/screens/HomeScreen.js

In my app there is list of appointments rendered by SectionList.

In renderItem I created two buttons, one of them is to delete item.

So, I cant understand how should I pass appointment ID to renderRightActions to delete or edit this current appointment.. please help me find out the solution!

Here is my HomeScreen code review:

const HomeScreen = ({ navigation }) => {
    const [data, setData] = useState(null)
    const [refreshing, setRefreshing] = useState(false)

    const fetchAppointments = () => {
        setRefreshing(true)
        appointmentsApi
            .get()
            .then(({ data }) => {
                setData(data.message)
                setRefreshing(false)
            })
            .catch((e) => {
                setRefreshing(false)
                console.log(e)
            })
    }

    useEffect(fetchAppointments, [])

    const removeAppointment = (id) => {
        console.log(id)
        const result = data.map((group) => {
            group.data = group.data.filter((item) => item._id !== id)
            return group
        })
        setData(result)
        //appointmentsApi.remove(id)
    }

    renderRightAction = (text, color, x, progress) => {
        const trans = progress.interpolate({
            inputRange: [0, 1],
            outputRange: [x, 0],
        })

        const pressHandler = () => {
            if (text === 'pencil') {
                alert('hey')
            } else {
                //but how to get over here the ID of item from SectionList?
                removeAppointment(id)
            }
        }

        return (
            <Animated.View style={{ flex: 1, transform: [{ translateX: trans }] }}>
                <RectButton
                    style={{
                        alignItems: 'center',
                        flex: 1,
                        justifyContent: 'center',
                        backgroundColor: color,
                    }}
                    onPress={pressHandler}
                >
                    <ActionText>
                        <Octicons name={text} size={24} color='white' />
                    </ActionText>
                </RectButton>
            </Animated.View>
        )
    }

    renderRightActions = (progress) => (
        <RightButtonsHandler>
            {renderRightAction('pencil', '#B4C1CB', 160, progress)}
            {renderRightAction('trashcan', '#F85A5A', 80, progress)}
        </RightButtonsHandler>
    )

    return (
        <Container>
            <SectionList
                style={{ paddingLeft: 20, paddingRight: 20 }}
                sections={data}
                keyExtractor={(item, index) => item + index}
                renderItem={({ item }) => (
                    <Swipeable renderRightActions={renderRightActions} friction={2}>
                        <Appointment navigation={navigation} item={item} />
                    </Swipeable>
                )}
                renderSectionHeader={({ section: { title } }) => <SectionTitle>{title}</SectionTitle>}
                refreshControl={<RefreshControl refreshing={refreshing} onRefresh={fetchAppointments} />}
            />
            <PluseButton
                style={{
                    shadowColor: '#2A86FF',
                    shadowOffset: {
                        width: 0,
                        height: 4,
                    },
                    shadowOpacity: 0.3,
                    shadowRadius: 4.65,
                    elevation: 8,
                }}
                onPress={() => navigation.navigate('AddPatient')}
            >
                <Ionicons name='ios-add' size={32} color='white' />
            </PluseButton>
        </Container>
    )
}

Body:
You only need to pass the item id as a function param.

renderRightActions={(progress) => renderRightActions(progress, item.id)}

I made all changes. Try this code:

const HomeScreen = ({ navigation }) => {
    const [data, setData] = useState(null)
    const [refreshing, setRefreshing] = useState(false)

    const fetchAppointments = () => {
        setRefreshing(true)
        appointmentsApi
            .get()
            .then(({ data }) => {
                setData(data.message)
                setRefreshing(false)
            })
            .catch((e) => {
                setRefreshing(false)
                console.log(e)
            })
    }

    useEffect(fetchAppointments, [])

    const removeAppointment = (id) => {
        console.log(id)
        const result = data.map((group) => {
            group.data = group.data.filter((item) => item._id !== id)
            return group
        })
        setData(result)
        //appointmentsApi.remove(id)
    }

    renderRightAction = (text, color, x, progress, id) => {
        const trans = progress.interpolate({
            inputRange: [0, 1],
            outputRange: [x, 0],
        })

        const pressHandler = () => {
            if (text === 'pencil') {
                alert('hey')
            } else {
                // but how to get over here the ID of item from SectionList?
                removeAppointment(id) // its simple! :)
            }
        }

        return (
            <Animated.View style={{ flex: 1, transform: [{ translateX: trans }] }}>
                <RectButton
                    style={{
                        alignItems: 'center',
                        flex: 1,
                        justifyContent: 'center',
                        backgroundColor: color,
                    }}
                    onPress={pressHandler}
                >
                    <ActionText>
                        <Octicons name={text} size={24} color='white' />
                    </ActionText>
                </RectButton>
            </Animated.View>
        )
    }

    renderRightActions = (progress, id) => (
        <RightButtonsHandler>
            {renderRightAction('pencil', '#B4C1CB', 160, progress, id)}
            {renderRightAction('trashcan', '#F85A5A', 80, progress, id)}
        </RightButtonsHandler>
    )

    return (
        <Container>
            <SectionList
                style={{ paddingLeft: 20, paddingRight: 20 }}
                sections={data}
                keyExtractor={(item, index) => item + index}
                renderItem={({ item }) => (
                    <Swipeable renderRightActions={(progress) => renderRightActions(progress, item.id)} friction={2}>
                        <Appointment navigation={navigation} item={item} />
                    </Swipeable>
                )}
                renderSectionHeader={({ section: { title } }) => <SectionTitle>{title}</SectionTitle>}
                refreshControl={<RefreshControl refreshing={refreshing} onRefresh={fetchAppointments} />}
            />
            <PluseButton
                style={{
                    shadowColor: '#2A86FF',
                    shadowOffset: {
                        width: 0,
                        height: 4,
                    },
                    shadowOpacity: 0.3,
                    shadowRadius: 4.65,
                    elevation: 8,
                }}
                onPress={() => navigation.navigate('AddPatient')}
            >
                <Ionicons name='ios-add' size={32} color='white' />
            </PluseButton>
        </Container>
    )
}


问:
Docker vs Kubernetes
I have docker and kubernetes (enable kubernetes checked on docker settings) installed on my local macbook. I create containers using docker and after my machine restarts, these exactly same containers are still present. However, if I create containers within pods using kubernetes and machine is restarted, then I do see the containers but those are like freshly created containers and not the same containers prior to restart.
What changes do I need to make so that even after machine restart my containers within the pods remain the same same before restart.</p>

答:
Even at runtime, Kubernetes may move Pods at will (e.g. during scaling, cluster upgrades, adding and removing nodes, etc.).

It is a good idea to try to treat containers as 'cattle, not pets', i.e. don't expect them to be long-lived.

If you need a container to be 'the same' after restart, consider using Persisent Volumes to store their state. Depending on your requirements, StatefulSets may also be worth considering.

Or consider having them reload / recompute any additional data they need after startup. The mechanism for this will depend on your code.

Title: Docker vs Kubernetes


问:
R - How to create an ascending/descending number line around a specific element in a vector
I have a series of the following vectors, each with a unique location of "0" surrounded by NAs:

```<code>NA NA NA NA NA 0 NA NA NA NA NA NA NA NA NA NA NA
</code>```

Is there a way to generate the following for each vector, i.e. a number line centered at the location of the 0, for the length of each vector?:

```<code>-5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 11
</code>```

Thanks so much for any guidance.

答:
Another option

```<code>seq(length(x)) - which(!x)
</code>```

Or with which.max

```<code>seq_along(x) - which.max(x)
</code>```

Body:
I have a series of the following vectors, each with a unique location of "0" surrounded by NAs:

NA NA NA NA NA 0 NA NA NA NA NA NA NA NA NA NA NA

Is there a way to generate the following for each vector, i.e. a number line centered at the location of the 0, for the length of each vector?:

-5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 11

Thanks so much for any guidance.

Body:
Another option

seq(length(x)) - which(!x)

Or with which.max

seq_along(x) - which.max(x)


答:
This else consider only last if statement. If you want it to consider all, use elif instead.

EDIT: in this case your program will end after first true statement. If you want to check it for all words in tweet, use

```<code>words = tweet.split()
</code>```

And execute the code (with elifs) for every word in a for loop.

Title: Python3: Why is my else statement activating regardless of multiple if statements being true

Body:
This else consider only last if statement. If you want it to consider all, use elif instead.

EDIT: in this case your program will end after first true statement. If you want to check it for all words in tweet, use

words = tweet.split()

And execute the code (with elifs) for every word in a for loop.


问:
Perform real time FFT from Apple Watch microphone
I'm developing an app that would be listening waiting for a certain frequency to be detected by the microphone. As far as I researched, I think the best way to do this is by performing a Fast Fourier Transform to the real time audio signal (if anyone think there's a better way to do it, I would love to hear from you). It works fine on iOS but I can't find a way to make it work on watchOS

I implemented the famous tempi-fft with no problems on iOS and Swift 5, the problems comes with different libraries not present or limited on watchOS SDK, as I can't use AudioUnit, AURenderCallback to detect new data on buffer, can't adjust the preferred buffer duration and sample rate to the AudioSession on WatchOS, etc. I'm not an expert at all with the 'audio engineering' side, so I don't know how to approach this. I researched a lot but i didn't find implementations on watchOS for this.

I only found this project AccelerateWatch, but this was uploaded years ago when Accelerate framework was not available on watchOS yet.

Any help on this would be greatly appreciated.

答:
I have a chromatic tuner app for the Apple Watch in the iOS App Store that does exactly this, running completely inside the Apple Watch component.

Both the iOS app and the watchOS Watch app component use an AVAudioInputNode installTapOnBus to acquire AVAudioPCMBuffer microphone sample buffers in near real-time.  Then the apps feed blocks of the audio sample data to either Goertzel routines or Accelerate framework vDSP FFT functions for further frequency analysis.  Then the app does further processing on the FFT frequency data to detect and estimate audio pitch (which is often very different from the FFT frequency magnitude peak).  The watchOS display is then animated at frame rate using SpriteKit to output the results.


问:
Trying to know how many rows I have from the different fleets in django
I'm working with a project that has 3 models.

Devices: All the devices involved in the project.

Fleets: Each device is in one fleet.

Data: The data that the devices send.

Now I want to know how much data have come me today.

In my view I have this,

```<code>def dataPlots(request):
    today = datetime.date(2020, 5, 18)
    data = DevData.objects.filter(data_timestamp__date=today)
    data  = loads(serializers.serialize('json', data))
</code>```

If I use len() I can now the total value. But how can I know how much data do I have for each fleet?

I have come to create this loop that would tell me for each device, but what I need is the value for each fleet and furthermore I think I am getting complicated.

```<code>data_dict = {}
for d in data:
    if d['fields']['dev_eui'] in data_dict:
        data_dict[d['fields']['dev_eui']] = data_dict[d['fields']['dev_eui']] + 1
    else:
        data_dict[d['fields']['dev_eui']] = 1

print(data_dict)
</code>```

The models are:

```<code>class Fleet(models.Model):
    fleet_id = models.IntegerField(primary_key=True, unique=True)
    fleet_name = models.CharField(max_length=20, unique=True)

class Device(models.Model):
    dev_eui = models.CharField(max_length=16, primary_key=True, unique=True)
    dev_name = models.CharField(max_length=20, unique=True)

    fleet_id = models.ForeignKey(Fleet, on_delete=models.CASCADE)

    def __str__(self):
        return self.dev_eui

class DevData(models.Model):
    data_uuid = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False)
    data_timestamp = models.DateTimeField()
    data = models.FloatField()

    dev_eui = models.ForeignKey(Device, on_delete=models.CASCADE)

    def __str__(self):
        return self.dev_eui
</code>```

Can somebody help me? I imagine that combining two models and some filter should suffice, but I don't know how to do it.

答:
You can annotate the Fleets with the given amount of data, for example:

```<code>from django.db.models import Count

Fleet.objects.filter(
    device__devdata__data_timestamp__date=today
).annotate(
    total_data=Count('device__devdata')
)</code>```

The Fleet objects that arise from this queryset will have an extra attribute .total_data that contains the total amount of data for today.

Body:
I'm working with a project that has 3 models.

Devices: All the devices involved in the project.

Fleets: Each device is in one fleet.

Data: The data that the devices send.

Now I want to know how much data have come me today.

In my view I have this,

def dataPlots(request):
    today = datetime.date(2020, 5, 18)
    data = DevData.objects.filter(data_timestamp__date=today)
    data  = loads(serializers.serialize('json', data))

If I use len() I can now the total value. But how can I know how much data do I have for each fleet?

I have come to create this loop that would tell me for each device, but what I need is the value for each fleet and furthermore I think I am getting complicated.

data_dict = {}
for d in data:
    if d['fields']['dev_eui'] in data_dict:
        data_dict[d['fields']['dev_eui']] = data_dict[d['fields']['dev_eui']] + 1
    else:
        data_dict[d['fields']['dev_eui']] = 1

print(data_dict)

The models are:

class Fleet(models.Model):
    fleet_id = models.IntegerField(primary_key=True, unique=True)
    fleet_name = models.CharField(max_length=20, unique=True)

class Device(models.Model):
    dev_eui = models.CharField(max_length=16, primary_key=True, unique=True)
    dev_name = models.CharField(max_length=20, unique=True)

    fleet_id = models.ForeignKey(Fleet, on_delete=models.CASCADE)

    def __str__(self):
        return self.dev_eui

class DevData(models.Model):
    data_uuid = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False)
    data_timestamp = models.DateTimeField()
    data = models.FloatField()

    dev_eui = models.ForeignKey(Device, on_delete=models.CASCADE)

    def __str__(self):
        return self.dev_eui

Can somebody help me? I imagine that combining two models and some filter should suffice, but I don't know how to do it.

Body:
You can annotate the Fleets with the given amount of data, for example:

from django.db.models import Count

Fleet.objects.filter(
    device__devdata__data_timestamp__date=today
).annotate(
    total_data=Count('device__devdata')
)

The Fleet objects that arise from this queryset will have an extra attribute .total_data that contains the total amount of data for today.