问:
React.js Pass input value from child to Parent
Hi I'm trying to pass and render input values from AddHamster (child) component to HamsterCard Component (parent). I'm getting the error message:
Error: Objects are not valid as a React child (found: object with keys {name, age, render}). If you meant to render a collection of children, use an array instead.

Any clue on how I could solve this?

import React, {useState} from "react";

const AddHamster  = () => {
    const [name, setName] = useState( '')
    const [age, setAge] = useState('')

    async function postHamster(){
        const newHamster = {
            name: name,
            age: Number(age),
        }

        const response = await fetch('/hamsters ', {method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(newHamster)
        })
        const data = await response.json()
        console.log(data, "this is data id");
        console.log(newHamster)
    }

    return   {
        name,
        age,
        render: (

        <form onSubmit={e => { e.preventDefault(); }}>
        Name

        <input value={name}
          type="text"
          onChange={(e) =>setName(e.target.value)}
          id="addhamster" />
         Age

        <input value={age}
         type="text"
         onChange={(e) =>setAge(e.target.value)}
         id="addhamster" />
     </form>

     <button onClick={e => postHamster()}>Add Hamster</button>

    )}

 }

export default AddHamster;```
</div>
</div>
</p>
<p>AddHamster.jsx `</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, {useState, useEffect} from "react";
import './HamsterCard.css';
import Hamster from  './Hamster';
import AddHamster from './AddHamster.jsx';

const HamsterCard = () => {
    const {render, name, age} = AddHamster();
    const [hamsters, setHamsters] = useState([])

    useEffect(() => {
        async function get(){
        const response = await fetch('/hamsters', {method: 'GET',})
        //fetchar och tar emot data i reponsens
        const data = await response.json() //Data
        setHamsters(data)
        console.log(data)

        }
       get()
    }, []  );

    return (
      //pass the id inside of the delete function to which id to delete
        <div className="container">
            <div className="hamster-card">
            {hamsters.map((hamster) => (
            <Hamster hamster={hamster}
            key={hamster.id} {...{name, age}}/>
            ))
            }
            {render}
            </div>
        </div>

    )
}

export default HamsterCard;</code>```

HamsterCard.jsx

import React, {useState} from "react";
const Hamster = (props) => {

   const [hamsterDeleted, setHamsterDeleted] = useState(false)
    async function deleteHamster(id) {
        const response = await fetch(`/hamsters/${id}`, { method: "DELETE" });
        setHamsterDeleted(true)

        }

         return (
                hamsterDeleted ? null : (

                <button onClick={() => deleteHamster(props.hamster.id)}>Delete</button>

{props.hamster.name}

Ålder:{props.hamster.age}

Favorit mat:{props.hamster.favFood}

Matcher:{props.hamster.games}

                 )

              ))
        }

export default Hamster;```
</div>
</div>
</p>
```import React, {useState} from "react";

const AddHamster  = () => {
    const [name, setName] = useState( '')
    const [age, setAge] = useState('')

    async function postHamster(){
        const newHamster = {
            name: name,
            age: Number(age),
        }

        const response = await fetch('/hamsters ', {method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(newHamster)
        })
        const data = await response.json()
        console.log(data, "this is data id");
        console.log(newHamster)
    }

    return   {
        name,
        age,
        render: (

        <form onSubmit={e => { e.preventDefault(); }}>
        Name

        <input value={name}
          type="text"
          onChange={(e) =>setName(e.target.value)}
          id="addhamster" />
         Age

        <input value={age}
         type="text"
         onChange={(e) =>setAge(e.target.value)}
         id="addhamster" />
     </form>

     <button onClick={e => postHamster()}>Add Hamster</button>

    )}

 }

export default AddHamster;
```
<pre class="lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
</code>```

答:
You are exporting a object from AddHamster component.

Error: Objects are not valid as a React child (found: object with keys {name, age, render})

As your  error message says Objects are not valid as React Child, you cannot export object from React component and render is a method used in class components.

If you want to access the child data from parent, lift the name  and  age state from AddHamster  (I have combined both the name and age into a single object) to HamsterCard and invoke the AddHamster as <AddHamster/> inside the return of a function.

AddHamster

```<code>const AddHamster = ({onChange,value}) => {
  async function postHamster() {
    const newHamster = {
      name: value.name,
      age: Number(value.age)
    };

    const response = await fetch("/hamsters ", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(newHamster)
    });
    const data = await response.json();
    console.log(data, "this is data id");
    console.log(newHamster);
  }
  return (
    <div className="add-hamster">
      <form
        onSubmit={(e) => {
          e.preventDefault();
        }}
      >
        <label>Name</label>

        <input
          value={value.name}
          type="text"
          name="name"
          onChange={onChange}
          id="addhamster"
        />
        <label>Age</label>

        <input
          value={value.age}
          type="text"
          name="age"
          onChange={onChange}
          id="addhamster"
        />
      </form>

      <button onClick={(e) => postHamster()}>Add Hamster</button>
    </div>
  );
};
</code>```

HamsterCard

```<code>const HamsterCard = () => {
    const [hamsters, setHamsters] = useState([])
    const [value,setValue] = useState({name:'',age:''})

    useEffect(() => {
        async function get(){
        const response = await fetch('/hamsters', {method: 'GET',})
        //fetchar och tar emot data i reponsens
        const data = await response.json() //Data
        setHamsters(data)
        console.log(data)

        }
       get()
    }, []  );

    const onChange = (e) => {
      setValue(currValue => ({...currValue,[e.target.name]: e.target.value}))
    }

    return (
      //pass the id inside of the delete function to which id to delete
        <div className="container">
            <div className="hamster-card">
            {hamsters.map((hamster) => (
            <Hamster hamster={hamster}
            key={hamster.id} {...value}/>
            ))
            }
            <AddHamster onChange={onChange} value={value}/>
            </div>
        </div>

    )
}
</code>```

Body:
Hi I'm trying to pass and render input values from AddHamster (child) component to HamsterCard Component (parent). I'm getting the error message:
Error: Objects are not valid as a React child (found: object with keys {name, age, render}). If you meant to render a collection of children, use an array instead.

Any clue on how I could solve this?

import React, {useState} from "react";

const AddHamster  = () => {
    const [name, setName] = useState( '')
    const [age, setAge] = useState('')

    async function postHamster(){
        const newHamster = {
            name: name,
            age: Number(age),
        }

        const response = await fetch('/hamsters ', {method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(newHamster)
        })
        const data = await response.json()
        console.log(data, "this is data id");
        console.log(newHamster)
    }

    return   {
        name,
        age,
        render: (

        <form onSubmit={e => { e.preventDefault(); }}>
        Name

        <input value={name}
          type="text"
          onChange={(e) =>setName(e.target.value)}
          id="addhamster" />
         Age

        <input value={age}
         type="text"
         onChange={(e) =>setAge(e.target.value)}
         id="addhamster" />
     </form>

     <button onClick={e => postHamster()}>Add Hamster</button>

    )}

 }

export default AddHamster;

AddHamster.jsx `

import React, {useState, useEffect} from "react";
import './HamsterCard.css';
import Hamster from  './Hamster';
import AddHamster from './AddHamster.jsx';

const HamsterCard = () => {
    const {render, name, age} = AddHamster();
    const [hamsters, setHamsters] = useState([])

    useEffect(() => {
        async function get(){
        const response = await fetch('/hamsters', {method: 'GET',})
        //fetchar och tar emot data i reponsens
        const data = await response.json() //Data
        setHamsters(data)
        console.log(data)

        }
       get()
    }, []  );

    return (
      //pass the id inside of the delete function to which id to delete

            {hamsters.map((hamster) => (
            <Hamster hamster={hamster}
            key={hamster.id} {...{name, age}}/>
            ))
            }
            {render}

    )
}

export default HamsterCard;

HamsterCard.jsx

import React, {useState} from "react";
const Hamster = (props) => {

   const [hamsterDeleted, setHamsterDeleted] = useState(false)
    async function deleteHamster(id) {
        const response = await fetch(`/hamsters/${id}`, { method: "DELETE" });
        setHamsterDeleted(true)

        }

         return (
                hamsterDeleted ? null : (

                <button onClick={() => deleteHamster(props.hamster.id)}>Delete</button>

{props.hamster.name}

Ålder:{props.hamster.age}

Favorit mat:{props.hamster.favFood}

Matcher:{props.hamster.games}

                 )

              ))
        }

export default Hamster;

import React, {useState} from "react";

const AddHamster  = () => {
    const [name, setName] = useState( '')
    const [age, setAge] = useState('')

    async function postHamster(){
        const newHamster = {
            name: name,
            age: Number(age),
        }

        const response = await fetch('/hamsters ', {method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(newHamster)
        })
        const data = await response.json()
        console.log(data, "this is data id");
        console.log(newHamster)
    }

    return   {
        name,
        age,
        render: (

        <form onSubmit={e => { e.preventDefault(); }}>
        Name

        <input value={name}
          type="text"
          onChange={(e) =>setName(e.target.value)}
          id="addhamster" />
         Age

        <input value={age}
         type="text"
         onChange={(e) =>setAge(e.target.value)}
         id="addhamster" />
     </form>

     <button onClick={e => postHamster()}>Add Hamster</button>

    )}

 }

export default AddHamster;

Body:
You are exporting a object from AddHamster component.

Error: Objects are not valid as a React child (found: object with keys {name, age, render})

As your  error message says Objects are not valid as React Child, you cannot export object from React component and render is a method used in class components.

If you want to access the child data from parent, lift the name  and  age state from AddHamster  (I have combined both the name and age into a single object) to HamsterCard and invoke the AddHamster as <AddHamster/> inside the return of a function.

AddHamster

const AddHamster = ({onChange,value}) => {
  async function postHamster() {
    const newHamster = {
      name: value.name,
      age: Number(value.age)
    };

    const response = await fetch("/hamsters ", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(newHamster)
    });
    const data = await response.json();
    console.log(data, "this is data id");
    console.log(newHamster);
  }
  return (
    <div className="add-hamster">
      <form
        onSubmit={(e) => {
          e.preventDefault();
        }}
      >
        <label>Name</label>

        <input
          value={value.name}
          type="text"
          name="name"
          onChange={onChange}
          id="addhamster"
        />
        <label>Age</label>

        <input
          value={value.age}
          type="text"
          name="age"
          onChange={onChange}
          id="addhamster"
        />
      </form>

      <button onClick={(e) => postHamster()}>Add Hamster</button>
    </div>
  );
};

HamsterCard

const HamsterCard = () => {
    const [hamsters, setHamsters] = useState([])
    const [value,setValue] = useState({name:'',age:''})

    useEffect(() => {
        async function get(){
        const response = await fetch('/hamsters', {method: 'GET',})
        //fetchar och tar emot data i reponsens
        const data = await response.json() //Data
        setHamsters(data)
        console.log(data)

        }
       get()
    }, []  );

    const onChange = (e) => {
      setValue(currValue => ({...currValue,[e.target.name]: e.target.value}))
    }

    return (
      //pass the id inside of the delete function to which id to delete
        <div className="container">
            <div className="hamster-card">
            {hamsters.map((hamster) => (
            <Hamster hamster={hamster}
            key={hamster.id} {...value}/>
            ))
            }
            <AddHamster onChange={onChange} value={value}/>
            </div>
        </div>

    )
}


来源: stackexchange

问:
AWK: Help on transforming data table
I have the following file called in.txt:

```<code>2020-01-01  fruit   banana  3.4
2020-03-02  alcohol smirnov 26.99
2020-03-10  fruit   orange  4.20
2020-04-03  fruit   orange  4.20
2021-09-01  alcohol beer    6.00
2021-08-03  fruit   mango   6.99
2022-01-01  fruit   orange  4.30
2022-03-04  alcohol beer    6.00
2022-03-03  alcohol beer    6.00
2022-04-01  fruit   mango   7.20
</code>```

I want to transform the file so it reads something like this:

```<code>                2020-01-01      2021-01-01      2022-01-01
                -2020-12-31     -2021-12-31     -2022-12-31
fruit   banana  3.40             0.00            0.00
        orange  8.40            0.00            4.30
        mango   0.00            6.99            7.20

Subt            11.80           6.99            11.50

alcohol beer    0.00            6.00            12.00
        smirnov 26.99           0.00            0.00

Subt            26.99           6.00            12.00

Total           38.59           12.99           23.50
</code>```

I have started writing the following script but am stuck on how to approach this. How can I display totals columns side by side. The other problem is that this is just dummy data. I have many different categories other than fruit and alcohol and it seems wrong to write if statements and for-loops for each one. Also how can I print fruit and alcohol out just once rather than for every iteration of column 3 and bring the date range to the top. Help is much appreciated.

```<code>#!/usr/bin/env bash

awk '

        BEGIN{
        FS=OFS="\t";
        }

        {
        if ($2 ~ fruit && $1 >= "2020-01-01" && $1 <= "2020-12-31") {
                        a[$3]+=$4;
                        sa+=$4;
                }
        }

        END {
        PROCINFO["sorted_in"]="@ind_str_asc";
        for (i in a) {
                        print "fruit", i, a[i]
                }
        }

' "${@:--}"
</code>```

答:
Would you please try the following:

```<code>#!/bin/bash

awk '
    {
        year = substr($1, 1, 4)                         # extract year
        if (from == "" || from > year) from = year      # first (smallest) year
        if (to == "" || to < year) to = year            # last (largest) year

        if ($3 in category == 0) {
            category[$3] = $2                           # map item to category
            list[$2] = list[$2] fs[$2] $3               # csv of items
            fs[$2] = ","                                # delimiter for csv
        }
        sum[$3,year] += $4                              # sum of the item in the year
        subt[$2,year] += $4                             # sum of the category in the year
        ttl[year] += $4                                 # sum in the year

    }
    END {
        format1 = "%-10s%-10s"                          # format for the left cells
        format2 = "%-16s"                               # format for the header
        format3 = "%-16.2f"                             # format for the amounts

        # print upper header
        printf(format1, "", "")
        for (y = from; y <= to; y++) {
            printf(format2, y "-01-01")
        }
        print ""

        # print second header
        printf(format1, "", "")
        for (y = from; y <= to; y++) {
            printf(format2, "-" y "-12-31")
        }
        print ""

        for (cat in list) {                             # loop over the categories ("fruit" and "alcohol")
            n = split(list[cat], item, ",")             # split into items
            for (i = 1; i <= n; i++) {                  # loop over the items
                printf(format1, i == 1 ? cat : "", item[i])
                for (y = from; y <= to; y++) {          # loop over years
                    printf(format3, sum[item[i],y])     # append the sum of the year
                }
                print ""                                # finally break the line
            }
            print ""                                    # insert blank line
            printf(format1, "Subt", "")
            for (y = from; y <= to; y++) {
                printf(format3, subt[cat,y])            # append the subtotal
            }
            print "\n"
        }
        printf(format1, "Total", "")
        for (y = from; y <= to; y++) {
            printf(format3, ttl[y])                     # append the total amount
        }
        print ""
    }
' in.txt
</code>```

Output with the provided input:

```<code>                    2020-01-01      2021-01-01      2022-01-01
                    -2020-12-31     -2021-12-31     -2022-12-31
alcohol   smirnov   26.99           0.00            0.00
          beer      0.00            6.00            12.00

Subt                26.99           6.00            12.00

fruit     banana    3.40            0.00            0.00
          orange    8.40            0.00            4.30
          mango     0.00            6.99            7.20

Subt                11.80           6.99            11.50

Total               38.79           12.99           23.50
</code>```

Please forgive me the order of items are not same as the OP's.

ContentLicense: CC BY-SA 4.0

Title: AWK: Help on transforming data table

Body:
I have the following file called in.txt:

2020-01-01  fruit   banana  3.4
2020-03-02  alcohol smirnov 26.99
2020-03-10  fruit   orange  4.20
2020-04-03  fruit   orange  4.20
2021-09-01  alcohol beer    6.00
2021-08-03  fruit   mango   6.99
2022-01-01  fruit   orange  4.30
2022-03-04  alcohol beer    6.00
2022-03-03  alcohol beer    6.00
2022-04-01  fruit   mango   7.20

I want to transform the file so it reads something like this:

                2020-01-01      2021-01-01      2022-01-01
                -2020-12-31     -2021-12-31     -2022-12-31
fruit   banana  3.40             0.00            0.00
        orange  8.40            0.00            4.30
        mango   0.00            6.99            7.20

Subt            11.80           6.99            11.50

alcohol beer    0.00            6.00            12.00
        smirnov 26.99           0.00            0.00

Subt            26.99           6.00            12.00

Total           38.59           12.99           23.50

I have started writing the following script but am stuck on how to approach this. How can I display totals columns side by side. The other problem is that this is just dummy data. I have many different categories other than fruit and alcohol and it seems wrong to write if statements and for-loops for each one. Also how can I print fruit and alcohol out just once rather than for every iteration of column 3 and bring the date range to the top. Help is much appreciated.

#!/usr/bin/env bash

awk '

        BEGIN{
        FS=OFS="\t";
        }

        {
        if ($2 ~ fruit && $1 >= "2020-01-01" && $1 <= "2020-12-31") {
                        a[$3]+=$4;
                        sa+=$4;
                }
        }

        END {
        PROCINFO["sorted_in"]="@ind_str_asc";
        for (i in a) {
                        print "fruit", i, a[i]
                }
        }

' "${@:--}"

Body:
Would you please try the following:

#!/bin/bash

awk '
    {
        year = substr($1, 1, 4)                         # extract year
        if (from == "" || from > year) from = year      # first (smallest) year
        if (to == "" || to < year) to = year            # last (largest) year

        if ($3 in category == 0) {
            category[$3] = $2                           # map item to category
            list[$2] = list[$2] fs[$2] $3               # csv of items
            fs[$2] = ","                                # delimiter for csv
        }
        sum[$3,year] += $4                              # sum of the item in the year
        subt[$2,year] += $4                             # sum of the category in the year
        ttl[year] += $4                                 # sum in the year

    }
    END {
        format1 = "%-10s%-10s"                          # format for the left cells
        format2 = "%-16s"                               # format for the header
        format3 = "%-16.2f"                             # format for the amounts

        # print upper header
        printf(format1, "", "")
        for (y = from; y <= to; y++) {
            printf(format2, y "-01-01")
        }
        print ""

        # print second header
        printf(format1, "", "")
        for (y = from; y <= to; y++) {
            printf(format2, "-" y "-12-31")
        }
        print ""

        for (cat in list) {                             # loop over the categories ("fruit" and "alcohol")
            n = split(list[cat], item, ",")             # split into items
            for (i = 1; i <= n; i++) {                  # loop over the items
                printf(format1, i == 1 ? cat : "", item[i])
                for (y = from; y <= to; y++) {          # loop over years
                    printf(format3, sum[item[i],y])     # append the sum of the year
                }
                print ""                                # finally break the line
            }
            print ""                                    # insert blank line
            printf(format1, "Subt", "")
            for (y = from; y <= to; y++) {
                printf(format3, subt[cat,y])            # append the subtotal
            }
            print "\n"
        }
        printf(format1, "Total", "")
        for (y = from; y <= to; y++) {
            printf(format3, ttl[y])                     # append the total amount
        }
        print ""
    }
' in.txt

Output with the provided input:

                    2020-01-01      2021-01-01      2022-01-01
                    -2020-12-31     -2021-12-31     -2022-12-31
alcohol   smirnov   26.99           0.00            0.00
          beer      0.00            6.00            12.00

Subt                26.99           6.00            12.00

fruit     banana    3.40            0.00            0.00
          orange    8.40            0.00            4.30
          mango     0.00            6.99            7.20

Subt                11.80           6.99            11.50

Total               38.79           12.99           23.50

Please forgive me the order of items are not same as the OP's.


问:
Keeping track of modifications in Power BI data
Let's say I have a list of the members of a team, and I keep track of their status (active/inactive, or present/absent, for instance). My file contains an id for each member, a column "updated at timestamp" as well as a column giving their current status. The list is updated daily, so some member's status can change from one day to the next.

What I would like to do is get the number of days the status was on "active/present" during a month (or a percentage of "active" during the month).

The problem being that the data is not stored : when there is an update, the column "status" changes but there is no history on whether it was on active/present or inactive/absent the previous day.

Could someone help me find a way to do that ?

Thanks in advance.

答: For the situation you mentioned, you can use a RDBMS systems. I am writing for SQL Server, probably you would use the "Temporal Table" for historical information.</p>


问:
How to find and replace only first occurrence of a node in a tree?
Can you please suggest how to find and replace just a first left node in a tree. I have implemented method that replaces all nodes:

```<code>from dataclasses import dataclass, field
import typing
from typing import List

@dataclass()
class Node:
  value: str
  children: List[Node] = field(default_factory=lambda: [])

# replaces all nodes
def substitute(source, original, replacement):
  if source == original:
    source.value = replacement.value
    source.children = replacement.children
    return source
  else:
    source.children = [substitute(child, original, replacement) for child in source.children]
    return source

t1 = Node('r', [Node('r2', [Node('2')]), Node('2')])
substitute(t1, Node('2'), Node('5')) # will substitue all Node('2') -> Node('5')
</code>```

How to implement method that replaces only first left occurrence (Postorder) of Node('2')?

```<code>Node('r', [Node('r2', [Node('2')]), Node('2')]) -> Node('r', [Node('r2', [Node('5')]), Node('2')])
</code>```

答:
As your substitute function mutates the given tree, there is no real need to also have it return it.

You could instead have it return a boolean that indicates whether a replacement was done or not.

This way you can then write an alternative substitute_first function and detect whether a recursive call returned True, which would be a signal to not do any more replacements, but just return True to the caller, so exiting the recursion tree quickly.

Here is the code:

```<code>def substitute_first(source, original, replacement):
  if any(substitute_first(child, original, replacement) for child in source.children):
      return True  # A replacement was made in recursion
  if source == original:
    source.value = replacement.value
    source.children = replacement.children
    return True
  return False
</code>```

Body:
Can you please suggest how to find and replace just a first left node in a tree. I have implemented method that replaces all nodes:

from dataclasses import dataclass, field
import typing
from typing import List

@dataclass()
class Node:
  value: str
  children: List[Node] = field(default_factory=lambda: [])

# replaces all nodes
def substitute(source, original, replacement):
  if source == original:
    source.value = replacement.value
    source.children = replacement.children
    return source
  else:
    source.children = [substitute(child, original, replacement) for child in source.children]
    return source

t1 = Node('r', [Node('r2', [Node('2')]), Node('2')])
substitute(t1, Node('2'), Node('5')) # will substitue all Node('2') -> Node('5')

How to implement method that replaces only first left occurrence (Postorder) of Node('2')?

Node('r', [Node('r2', [Node('2')]), Node('2')]) -> Node('r', [Node('r2', [Node('5')]), Node('2')])

Body:
As your substitute function mutates the given tree, there is no real need to also have it return it.

You could instead have it return a boolean that indicates whether a replacement was done or not.

This way you can then write an alternative substitute_first function and detect whether a recursive call returned True, which would be a signal to not do any more replacements, but just return True to the caller, so exiting the recursion tree quickly.

Here is the code:

def substitute_first(source, original, replacement):
  if any(substitute_first(child, original, replacement) for child in source.children):
      return True  # A replacement was made in recursion
  if source == original:
    source.value = replacement.value
    source.children = replacement.children
    return True
  return False


问:
Python - Data manipulation in a file
I'm at the stage where I've a txt file in the form:

```<code>text1;10;20;11
text2;3;4;5
text3;4;5;7
</code>```

Anyone got any idea what function to use to get rid of the numbers in the middle of each line?
I would like to have in output:

```<code>text1;11
text2;5
text3;7
</code>```

Currently I have done:

```<code>    for ii in files:
        if ii.endswith(".txt"):  # only txt files
            with open(ii, 'r') as f:
                content = f.read()
                f.close()
                content1 = re.sub('\t', '', content, flags=re.M)
                content2 = re.sub(' ', '', content1, flags=re.M)
                f = open(ii, "w+")
                f.write(content2)
                f.close()
</code>```

答:
To complete Mario Khoury's answer, I'd point out that you don't need to open/close the file you want to read/write to within with open(ii, 'r') as f:.

what do you want to do? Create another file with only the start/end elements of each line, or replace the lines in the original file? File handling depends on what you want to do.

```<code>for ii in files:
        if ii.endswith(".txt"):  # only txt files
            with open(ii, 'r') as f, open(output_file, 'w') as f_out:
                content = f.read()
                res = content.split(";")[0] + ";" + content.split(";")[-1]
                f_out.write(res)
</code>```

Title: Python - Data manipulation in a file

Body:
I'm at the stage where I've a txt file in the form:

text1;10;20;11
text2;3;4;5
text3;4;5;7

Anyone got any idea what function to use to get rid of the numbers in the middle of each line?
I would like to have in output:

text1;11
text2;5
text3;7

Currently I have done:

    for ii in files:
        if ii.endswith(".txt"):  # only txt files
            with open(ii, 'r') as f:
                content = f.read()
                f.close()
                content1 = re.sub('\t', '', content, flags=re.M)
                content2 = re.sub(' ', '', content1, flags=re.M)
                f = open(ii, "w+")
                f.write(content2)
                f.close()

Body:
To complete Mario Khoury's answer, I'd point out that you don't need to open/close the file you want to read/write to within with open(ii, 'r') as f:.

what do you want to do? Create another file with only the start/end elements of each line, or replace the lines in the original file? File handling depends on what you want to do.

for ii in files:
        if ii.endswith(".txt"):  # only txt files
            with open(ii, 'r') as f, open(output_file, 'w') as f_out:
                content = f.read()
                res = content.split(";")[0] + ";" + content.split(";")[-1]
                f_out.write(res)


问:
Cast a base class issues
```<code>class YourInterface {
public:
    YourInterface(){
    }

    virtual ~YourInterface(){
    }

    virtual void saveData(Data data) = 0; //Pure virtual = Childs are forced to implement those functions to become non abstract
    virtual Data loadData() = 0;
};

//One implementation to load and save data to/from a xml file
class XmlImplementation : public YourInterface {
public:
    XmlImplementation(){
    }

    virtual ~XmlImplementation(){
    }

    //Overriding functions:
    void saveData(Data data){
        //Save data to a xml file here
    }

    Data loadData(){
        //Load data from a xml file here
    }
};

void main(){
    YourInterface* p;
    p = (YourInterface*) new XmlImplementation();

    p->loadData(); //We just want to get our Data here, we dont care whether its from a xml or binary file etc.
}
</code>```

Please take that as an example, I know it is not good but I can't write any better than that.

I'd like to know better why the cast in main refuses to work properly ? and it has been suggested as an errorful cast.

答:
There's no need for the (C-style or otherwise) cast here. Your main() function (which should always return int) should look like this:

```<code>int main()
{
    YourInterface* p = new XmlImplementation();

    p->loadData();
}
</code>```

If you're getting an error, it's not because of the cast.

N.B: In C++, it's customary to use static_cast when typecasting from a pointer to a derived class to a pointer to a base class.

ContentLicense: CC BY-SA 3.0

Title: Cast a base class issues

Body:
class YourInterface {
public:
    YourInterface(){
    }

    virtual ~YourInterface(){
    }

    virtual void saveData(Data data) = 0; //Pure virtual = Childs are forced to implement those functions to become non abstract
    virtual Data loadData() = 0;
};

//One implementation to load and save data to/from a xml file
class XmlImplementation : public YourInterface {
public:
    XmlImplementation(){
    }

    virtual ~XmlImplementation(){
    }

    //Overriding functions:
    void saveData(Data data){
        //Save data to a xml file here
    }

    Data loadData(){
        //Load data from a xml file here
    }
};

void main(){
    YourInterface* p;
    p = (YourInterface*) new XmlImplementation();

    p->loadData(); //We just want to get our Data here, we dont care whether its from a xml or binary file etc.
}

Please take that as an example, I know it is not good but I can't write any better than that.

I'd like to know better why the cast in main refuses to work properly ? and it has been suggested as an errorful cast.

Body:
There's no need for the (C-style or otherwise) cast here. Your main() function (which should always return int) should look like this:

int main()
{
    YourInterface* p = new XmlImplementation();

    p->loadData();
}

If you're getting an error, it's not because of the cast.

N.B: In C++, it's customary to use static_cast when typecasting from a pointer to a derived class to a pointer to a base class.


问:
How to share AWS infrastructure among multiple accounts using Terraform and AWS SSO?
I have the following multi-account setup with AWS SSO:

An account called "infrastructure-owner". Under this account, there is a role called "SomeAccessLevel" where I can click to sign-in the web console.

Another account called "infrastructure-consumer". Under this account there is the same role called "SomeAccessLevel" where I can click to sign-in the web console. There may be other roles.

Account "infrastructure-owner" owns resources (for example S3 buckets, DynamoDB tables, or VPNs) typically with read/write access. This account is somewhat protected and rarely used. Account "infrastructure-consumer" merely have read access to resources in "infrastructure-owner". This account is used often by multiple people/services. For example, production data pipelines run in "infrastructure-consumer" and have read-only rights to S3 buckets in "infrastructure-owner". However, from time to time, new data may be included manually in these S3 buckets via sign-in "infrastructure-owner".

I would like to provision this infrastructure with Terraform. I am unable to provide permissions for "infrastructure-consumer" to access resources from "infrastructure-owner". I've read dozens of blog posts on AWS multi-account / SSO / Terraform but I still cannot do it. At this point, I cannot even do it manually in the web console.

Please realize that "SomeAccessLevel" is a role created by AWS that I cannot modify (typically called AWSReservedSSO_YOURNAMEHERE_RANDOMSTRING). Also, I cannot give permissions to particular users, since these users may not be owned by "infrastructure-consumer". Also, users access this account via SSO using a role.

The following Terraform code is an example DynamoDB table created in the "infrastructure-owner" that I would like to read in the "infrastructure-consumer" account (any role):

```<code># Terraform config
terraform {
  required_version = ">= 1.0.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.44"
    }
  }

  backend "remote" {
    hostname = "app.terraform.io"
    organization = "YOUR_ORGANIZATION_HERE"

    workspaces {
      name = "YOUR_TF_WORKSPACE_NAME_HERE"  # linked to "infrastructure-owner"
    }
  }
}

# Local provider
provider "aws" {
  profile = "YOUR_AWS_PROFILE_NAME_HERE"  # linked to "infrastructure-owner"
  region = "eu-central-1"
}

# Example resource that I would like to access from other accounts like "infrastructure-consumer"
resource "aws_dynamodb_table" "my-database" {

  # Basic
  name           = "my-database"
  billing_mode   = "PAY_PER_REQUEST"
  hash_key       = "uuid"

  # Key
  attribute {
    name = "uuid"
    type = "S"
  }
}

# YOUR CODE TO ALLOW "infrastructure-consumer" TO READ THE TABLE.
</code>```

It could also happen that there is a better architecture for this use case. I am trying to follow general practices for AWS multi-account for production environments, and Terraform for provisioning them.

Thank you!

答:
I assume you mean AWS accounts and not IAM accounts (users).

I remember that roles to be assumed via AWS SSO had something called permission sets, which is no more than a policy with API actions allowed|denied to be performed while assuming a role. I don't know exactly how AWS SSO could influence how role trust works in AWS, but you could have a role in infrastructure-owner's account that trusts anything in infrastructure-consumer's account, i.e. trusting "arn:aws:iam::${var.infrastructure-consumer's account}:root"

To achieve that with Terraform you would run it in your management account (SSO Administrator's Account) and make that trust happen.

Body:
I have the following multi-account setup with AWS SSO:

An account called "infrastructure-owner". Under this account, there is a role called "SomeAccessLevel" where I can click to sign-in the web console.

Another account called "infrastructure-consumer". Under this account there is the same role called "SomeAccessLevel" where I can click to sign-in the web console. There may be other roles.

Account "infrastructure-owner" owns resources (for example S3 buckets, DynamoDB tables, or VPNs) typically with read/write access. This account is somewhat protected and rarely used. Account "infrastructure-consumer" merely have read access to resources in "infrastructure-owner". This account is used often by multiple people/services. For example, production data pipelines run in "infrastructure-consumer" and have read-only rights to S3 buckets in "infrastructure-owner". However, from time to time, new data may be included manually in these S3 buckets via sign-in "infrastructure-owner".

I would like to provision this infrastructure with Terraform. I am unable to provide permissions for "infrastructure-consumer" to access resources from "infrastructure-owner". I've read dozens of blog posts on AWS multi-account / SSO / Terraform but I still cannot do it. At this point, I cannot even do it manually in the web console.

Please realize that "SomeAccessLevel" is a role created by AWS that I cannot modify (typically called AWSReservedSSO_YOURNAMEHERE_RANDOMSTRING). Also, I cannot give permissions to particular users, since these users may not be owned by "infrastructure-consumer". Also, users access this account via SSO using a role.

The following Terraform code is an example DynamoDB table created in the "infrastructure-owner" that I would like to read in the "infrastructure-consumer" account (any role):

# Terraform config
terraform {
  required_version = ">= 1.0.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.44"
    }
  }

  backend "remote" {
    hostname = "app.terraform.io"
    organization = "YOUR_ORGANIZATION_HERE"

    workspaces {
      name = "YOUR_TF_WORKSPACE_NAME_HERE"  # linked to "infrastructure-owner"
    }
  }
}

# Local provider
provider "aws" {
  profile = "YOUR_AWS_PROFILE_NAME_HERE"  # linked to "infrastructure-owner"
  region = "eu-central-1"
}

# Example resource that I would like to access from other accounts like "infrastructure-consumer"
resource "aws_dynamodb_table" "my-database" {

  # Basic
  name           = "my-database"
  billing_mode   = "PAY_PER_REQUEST"
  hash_key       = "uuid"

  # Key
  attribute {
    name = "uuid"
    type = "S"
  }
}

# YOUR CODE TO ALLOW "infrastructure-consumer" TO READ THE TABLE.

It could also happen that there is a better architecture for this use case. I am trying to follow general practices for AWS multi-account for production environments, and Terraform for provisioning them.

Thank you!


问:
How to print variable present in python with the help of html?
I've written some code for deep learning text summarization, and I'm trying to render the template using the Flask library. I'm unable to see the results. The python code can be found below.

```<code>    text = ' '.join([summ['summary_text'] for summ in res])
    print(text)
return render_template('result.html', prediction=text)
</code>```

I'm trying to print the prediction variable which is present in the above code. Below is the html code

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/styles.css') }}">
</head>
<body>

    <header>
        <div class="container">
        <div id="brandname">
            Deep Learning App
        </div>
        <h2>Summarized text</h2>

    </div>
    </header>
    <p style="color:blue;font-size:20;text-align: center;"><b>Result for Text</b></p>
    <div class="results">

    <p><strong>{prediction}</strong></p>

    </div>

</body>
</html>
</code>```

Below is output image

enter image description here

Can anyone help me how to display text present in prediction variable on web page?

答:
You need double curly braces</p>
```<code><p><strong>{{ prediction }}</strong></p>
</code>```

Body:
I've written some code for deep learning text summarization, and I'm trying to render the template using the Flask library. I'm unable to see the results. The python code can be found below.

    text = ' '.join([summ['summary_text'] for summ in res])
    print(text)
return render_template('result.html', prediction=text)

I'm trying to print the prediction variable which is present in the above code. Below is the html code

<!DOCTYPE html>

    <title></title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/styles.css') }}">

            Deep Learning App

Summarized text

Result for Text

{prediction}

Below is output image

enter image description here

Can anyone help me how to display text present in prediction variable on web page?

Body:
You need double curly braces

<p><strong>{{ prediction }}</strong></p>


问:
file does not begin with %pdf-
I asked this question and have now got it mostly working.

However I am still getting the titled error and cannot seem to find any reference to anyone that has solved it.

This is driving me insane!

My ASHX C# code looks like this;

```<code>context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.AddHeader("Content-Disposition", "inline;filename=file.pdf");
context.Response.ContentType = "application/pdf";

Stream fileStream = publishBookManager.GetFile();
byte[] buffer = new byte[32 * 1024];
using (MemoryStream ms = new MemoryStream())
{
  int read;
  while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
  {
    ms.Write(buffer, 0, read);
  }
}

context.Response.BinaryWrite(buffer);
context.Response.Flush();
context.Response.Close();
</code>```

And my jQuery / javascript looks like;

```<code>window.open('/UserControls/download.ashx?format=pdf&bookId=' + bookId, "pdfViewer");
</code>```

答:
Is the Acrobat Reader upgraded to the latest version?  Is the file openable in Acrobat Reader separate from coming from the HTTP request?

Also, is the file larger than 32K?  Because it looks like you are only able to hold 32K in your buffer that you are writing out the the caller.

Title: file does not begin with %pdf-

Body:
I asked this question and have now got it mostly working.

However I am still getting the titled error and cannot seem to find any reference to anyone that has solved it.

This is driving me insane!

My ASHX C# code looks like this;

context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.AddHeader("Content-Disposition", "inline;filename=file.pdf");
context.Response.ContentType = "application/pdf";

Stream fileStream = publishBookManager.GetFile();
byte[] buffer = new byte[32 * 1024];
using (MemoryStream ms = new MemoryStream())
{
  int read;
  while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
  {
    ms.Write(buffer, 0, read);
  }
}

context.Response.BinaryWrite(buffer);
context.Response.Flush();
context.Response.Close();

And my jQuery / javascript looks like;

window.open('/UserControls/download.ashx?format=pdf&bookId=' + bookId, "pdfViewer");


问:
Kubernetes NodePort not accesible from outside
I'm trying to use the latest bitnami postgres chart to deploy postgres to a local kubernetes cluster (mac os, docker desktop 4.4.2, kubernetes 1.22.5):
https://github.com/bitnami/bitnami-docker-postgresql

I have set the node port:

```<code>primary:
  service:
    # Kubernetes Service type
    type: NodePort
    nodePorts:
      # Node port for PostgreSQL
      postgresql: '30000'
</code>```

the service is visible:

```<code>NAME                             TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
service/postgres-nodeport      NodePort    10.111.195.149   <none>        5432:30000/TCP   9m56s
</code>```

but I cant access it from outside, eg:

```<code>psql -h localhost -p 30000 -U myusername -d mydatabase
</code>```

but I think it is configured correctly, because when I execute port-forward postgres is available:

```<code>kubectl port-forward pod/postgres-nodeport-0 30000:5432
</code>```

答: Nodeport only exposes the service on the nodes at the specified port. It does not expose it to the public. You need to configure ingress or load balancer to expose the service to the outside world.</p>

Body:
I'm trying to use the latest bitnami postgres chart to deploy postgres to a local kubernetes cluster (mac os, docker desktop 4.4.2, kubernetes 1.22.5):
https://github.com/bitnami/bitnami-docker-postgresql

I have set the node port:

primary:
  service:
    # Kubernetes Service type
    type: NodePort
    nodePorts:
      # Node port for PostgreSQL
      postgresql: '30000'

the service is visible:

NAME                             TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
service/postgres-nodeport      NodePort    10.111.195.149   <none>        5432:30000/TCP   9m56s

but I cant access it from outside, eg:

psql -h localhost -p 30000 -U myusername -d mydatabase

but I think it is configured correctly, because when I execute port-forward postgres is available:

kubectl port-forward pod/postgres-nodeport-0 30000:5432


问:
ajp_msg_append_cvt_string(): BufferOverflowException on apache 2.4
In below code from apache server ajp_msg.c, any idea where the
msg->max_size is coming from ?

I am trying to fix error message below :

ajp_msg_append_cvt_string(): BufferOverflowException 4 8186

```<code>**
*  Add a String in AJP message, and transform the String in ASCII
*  if convert is set and we're on an EBCDIC machine
*
* @param msg       AJP Message to get value from
* @param value     Pointer to String
* @param convert   When set told to convert String to ASCII
* @return          APR_SUCCESS or error
*/
apr_status_t ajp_msg_append_string_ex(ajp_msg_t *msg, const char *value,
                                      int convert)
{
    apr_size_t len;

    if (value == NULL) {
        return(ajp_msg_append_uint16(msg, 0xFFFF));
    }

    len = strlen(value);
    if ((msg->len + len + 3) > msg->max_size) {
        return ajp_log_overflow(msg, "ajp_msg_append_cvt_string");
    }

    /* ignore error - we checked once */
    ajp_msg_append_uint16(msg, (apr_uint16_t)len);

    /* We checked for space !!  */
    memcpy(msg->buf + msg->len, value, len + 1); /* including \0 */

    if (convert) {
        /* convert from EBCDIC if needed */
        ap_xlate_proto_to_ascii((char *)msg->buf + msg->len, len + 1);
    }

    msg->len += len + 1;

    return APR_SUCCESS;
}
</code>```

答:
In my case the error was this

```<code>AH00548: NameVirtualHost has no effect and will be removed in the next release /home/jadmin_q/apache2/conf/extra/httpd-vhosts.conf:1
</code>```

As mentioned i opened the file httpd-vhosts.conf and line number 1 and commented the line NameVirtualHost and next time the error did not came

Body:
In below code from apache server ajp_msg.c, any idea where the
msg->max_size is coming from ?

I am trying to fix error message below :

ajp_msg_append_cvt_string(): BufferOverflowException 4 8186

**
*  Add a String in AJP message, and transform the String in ASCII
*  if convert is set and we're on an EBCDIC machine
*
* @param msg       AJP Message to get value from
* @param value     Pointer to String
* @param convert   When set told to convert String to ASCII
* @return          APR_SUCCESS or error
*/
apr_status_t ajp_msg_append_string_ex(ajp_msg_t *msg, const char *value,
                                      int convert)
{
    apr_size_t len;

    if (value == NULL) {
        return(ajp_msg_append_uint16(msg, 0xFFFF));
    }

    len = strlen(value);
    if ((msg->len + len + 3) > msg->max_size) {
        return ajp_log_overflow(msg, "ajp_msg_append_cvt_string");
    }

    /* ignore error - we checked once */
    ajp_msg_append_uint16(msg, (apr_uint16_t)len);

    /* We checked for space !!  */
    memcpy(msg->buf + msg->len, value, len + 1); /* including \0 */

    if (convert) {
        /* convert from EBCDIC if needed */
        ap_xlate_proto_to_ascii((char *)msg->buf + msg->len, len + 1);
    }

    msg->len += len + 1;

    return APR_SUCCESS;
}

Body:
In my case the error was this

AH00548: NameVirtualHost has no effect and will be removed in the next release /home/jadmin_q/apache2/conf/extra/httpd-vhosts.conf:1

As mentioned i opened the file httpd-vhosts.conf and line number 1 and commented the line NameVirtualHost and next time the error did not came


问:
PyCharm shows "PEP8: expected 2 blank lines, found 1"
Consider the following code:

```<code>def add_function(a, b):
    c = str(a) + b
    print "c is %s" % c

def add_int_function(c, d):
    e = c + d
    print "the vaule of e is %d" % e

if __name__ =="__main__":
    add_function(59906, 'kugrt5')
    add_int_function(1, 2)
</code>```

It always shows me: "expected 2 blank lines ，found 1" in aadd_int_function, but not in the add_function.

When I add two spaces in front of the def add_int_function(c, d):
there is a error shows unindent does not match any outer indentation level
in the end of add_function:

答:
Further clarification on @kennet-celeste & @shreyshrey 's answers,

Each function or class defined requires 2 spaces above and 2 spaces below. Unless the function is the last item in the script, in which the expected format is one blank line as an End of File marker. So:

```<code># some code followed by 2 blank spaces

def function1():

def function2():

def function3():
</code>```

Body:
Consider the following code:

def add_function(a, b):
    c = str(a) + b
    print "c is %s" % c

def add_int_function(c, d):
    e = c + d
    print "the vaule of e is %d" % e

if __name__ =="__main__":
    add_function(59906, 'kugrt5')
    add_int_function(1, 2)

It always shows me: "expected 2 blank lines ，found 1" in aadd_int_function, but not in the add_function.

When I add two spaces in front of the def add_int_function(c, d):
there is a error shows unindent does not match any outer indentation level
in the end of add_function:

Body:
Further clarification on @kennet-celeste & @shreyshrey 's answers,

Each function or class defined requires 2 spaces above and 2 spaces below. Unless the function is the last item in the script, in which the expected format is one blank line as an End of File marker. So:

# some code followed by 2 blank spaces

def function1():

def function2():

def function3():


问:
Undefined reference error to function in other file
I have a game program and I am getting VERY frustrated. Everything was running fine, and I decided to clean up my program by making separate files for each set of functions. The code is very long with multiple files, but heres the basic idea:

Im on Windows XP using the Code::Blocks IDE

In my entity.h Ive declared all of my functions and variables for that class. In my entity.cpp Ive included it, as well as in all my other files. But Im still getting a huge list of errors that tell me I have an undefined reference to all of the methods in entity.h as well as all my other header files. For example, I have a function call print() to make it easier to print out things, and thats the first method I call from the entity.h file. I get this error:

Heres the code for print():

```<code>void print(string f) {
 cout<<f<<endl;
}
</code>```

How Im calling it:

```<code>void Player::win(){
entity e;
e.print("You have defeated the orc");
</code>```

}
The error:

In function 'ZN6Player3winEv':
   undefined reference to 'entity::print(std::string)'

And yes, I do have an object of entity.

答:
I had the same problem. For me the solution was :
When you add a file in your project, dont forget to click on "add to DEBUG" and "add to RELEASE", either the file will be in the project tree yes, but you will have error "undefined reference"</p>

Body:
I have a game program and I am getting VERY frustrated. Everything was running fine, and I decided to clean up my program by making separate files for each set of functions. The code is very long with multiple files, but heres the basic idea:

Im on Windows XP using the Code::Blocks IDE

In my entity.h Ive declared all of my functions and variables for that class. In my entity.cpp Ive included it, as well as in all my other files. But Im still getting a huge list of errors that tell me I have an undefined reference to all of the methods in entity.h as well as all my other header files. For example, I have a function call print() to make it easier to print out things, and thats the first method I call from the entity.h file. I get this error:

Heres the code for print():

void print(string f) {
 cout<<f<<endl;
}

How Im calling it:

void Player::win(){
entity e;
e.print("You have defeated the orc");

}
The error:

In function 'ZN6Player3winEv':
   undefined reference to 'entity::print(std::string)'

And yes, I do have an object of entity.


问:
print message when read timeout occur
I am using pyserial to read sensor data through USB. But, sometimes the sensor does not send any data and it needs to be restarted. I found, we can use timeout, if for a certain time, the read() function of pyserial can not read. But, it does not work as I expected. I used the following code snippet for example:

```<code>ser=serial.Serial(port=addr, timeout=4)
while True:
    try:
        print(ser.read(size=5))
    except:
        print('not ok, restart!')
</code>```

I was expecting, after 4 seconds, the except will be triggered. But that is not the case. After 4 seconds, printing null of length zero. This repeats each 4 seconds until restart.
How does my code sense that the time out happened and a certain massage needs to be printed?
I can also check the length len(ser.read(size=5)) and do print the restart massage but problem will be even there is no timeout and the length will be calculated. That might hurt the performance. There should be some other better way.
Also, I can not use serial.SerialTimeoutException, because according to the doc:

```<code>Exception that is raised on write timeouts
</code>```

答:
Pyserial does not trigger an exception on a read timeout, it just moves on.
What you could try instead is write a condition the check if the output length is zero</p>
```<code>ser=serial.Serial(port=addr, timeout=4)
while True:
output = ser.read(size5)
if len(output) == 0:
   print('not ok, restart!')
else:
   print(output)
</code>```

Title: print message when read timeout occur

Body:
I am using pyserial to read sensor data through USB. But, sometimes the sensor does not send any data and it needs to be restarted. I found, we can use timeout, if for a certain time, the read() function of pyserial can not read. But, it does not work as I expected. I used the following code snippet for example:

ser=serial.Serial(port=addr, timeout=4)
while True:
    try:
        print(ser.read(size=5))
    except:
        print('not ok, restart!')

I was expecting, after 4 seconds, the except will be triggered. But that is not the case. After 4 seconds, printing null of length zero. This repeats each 4 seconds until restart.
How does my code sense that the time out happened and a certain massage needs to be printed?
I can also check the length len(ser.read(size=5)) and do print the restart massage but problem will be even there is no timeout and the length will be calculated. That might hurt the performance. There should be some other better way.
Also, I can not use serial.SerialTimeoutException, because according to the doc:

Exception that is raised on write timeouts

Body:
Pyserial does not trigger an exception on a read timeout, it just moves on.
What you could try instead is write a condition the check if the output length is zero

ser=serial.Serial(port=addr, timeout=4)
while True:
output = ser.read(size5)
if len(output) == 0:
   print('not ok, restart!')
else:
   print(output)


问:
Can I get object name from a symbol information in the symbol table in an ELF file?
I have successfully parsed an elf file (executable file) compiled from multiple source files. I am able to get the binding(local,global,weak), type(object,file,section,function), size of the symbol and the address of the symbol along with the symbol name ( from string table).

The section to which the symbol is linked is also known to me.

My question is that can we get the exact object file name(**.obj) which contains the symbol from the symbol table information? Am I missing some information while parsing ?

答:
You cannot get the object file name directly, this is lost during linking. However, depending on the build process used to create the executable, you can infer the object file name from the STT_FILE symbols (e.g., an executable contains a STT_FILE symbol with name foo.c -> you could maybe infer the object file was foo.o).

It appears that symbols in a specific source file follow the STT_FILE symbol with a binding of STB_LOCAL.

From the System V ABI standard:

STT_FILE -- Conventionally, the symbol’s name gives the name of the source file associated with the object file. A file symbol has STB_LOCAL binding, its section index is SHN_ABS, and it precedes the other STB_LOCAL symbols for the file, if it is present.


问:
Python Django: How to prevent form field from clearing?
I am working with Python Django and I have this really simple form, consisting of a button and an input field. The problem is that the input field is for some reason cleared after I submit the form. So How can I prevent it from clearing?

This is my python file:

```<code>def index(request):
    # print(f"its me {os.getcwd()}")
    txt = request.GET.get("some_txt")
    if (request.GET.get('mybtn')):
        print(f"THIS IS THE TEXT VALUE: {txt}")
    else:
        print("Has not been clicked")
    return render(request, "main/index.html")
</code>```

This is the HTML file:

```<code><form action="#" method="get">
        {% csrf_token %}
        <input type="text" name="some_txt">
        <button type="submit" class="btn btn-primary" value="mybtn" name="mybtn">Submit</button>

</form>
</code>```

答:
You each time render a new form, so if you want to populate the form with the old data, you pass it to the template:

```<code>def index(request):
    txt = request.GET.get('some_txt', '')
    if (request.GET.get('mybtn')):
        print(f'THIS IS THE TEXT VALUE: {txt}')
    else:
        print('Has not been clicked')
    return render(request, 'main/index.html', <strong>{'txt': txt}</strong>)</code>```

and in the the form, you use that as value:

```<code><form action="" method="get">
    <input type="text" name="some_txt"<strong> value="{{ txt }}"</strong>>
    <button type="submit" class="btn btn-primary" value="mybtn" name="mybtn">Submit</button>
</form></code>```

or with a clear function:

```<code>def index(request):
    txt = request.GET.get('some_txt', '')
    if request.GET.get('mybtn') == 'mybtn2':
        txt = ''
    else if request.GET.get('mybtn'):
        print(f'THIS IS THE TEXT VALUE: {txt}')
    else:
        print('Has not been clicked')
    return render(request, 'main/index.html', <strong>{'txt': txt}</strong>)</code>```

and at the HTML side we thus work with a second button:

```<code><form action="" method="get">
    <input type="text" name="some_txt" value="{{ txt }}">
    <button type="submit" class="btn btn-primary" value="mybtn" name="mybtn">Submit</button>
    <button type="submit" class="btn" <strong>value="mybtn2"</strong> name="mybtn">Reset</button>
</form></code>```

Body:
I am working with Python Django and I have this really simple form, consisting of a button and an input field. The problem is that the input field is for some reason cleared after I submit the form. So How can I prevent it from clearing?

This is my python file:

def index(request):
    # print(f"its me {os.getcwd()}")
    txt = request.GET.get("some_txt")
    if (request.GET.get('mybtn')):
        print(f"THIS IS THE TEXT VALUE: {txt}")
    else:
        print("Has not been clicked")
    return render(request, "main/index.html")

This is the HTML file:

<form action="#" method="get">
        {% csrf_token %}
        <input type="text" name="some_txt">
        <button type="submit" class="btn btn-primary" value="mybtn" name="mybtn">Submit</button>

</form>

Body:
You each time render a new form, so if you want to populate the form with the old data, you pass it to the template:

def index(request):
    txt = request.GET.get('some_txt', '')
    if (request.GET.get('mybtn')):
        print(f'THIS IS THE TEXT VALUE: {txt}')
    else:
        print('Has not been clicked')
    return render(request, 'main/index.html', {'txt': txt})

and in the the form, you use that as value:

<form action="" method="get">
    <input type="text" name="some_txt" value="{{ txt }}">
    <button type="submit" class="btn btn-primary" value="mybtn" name="mybtn">Submit</button>
</form>

or with a clear function:

def index(request):
    txt = request.GET.get('some_txt', '')
    if request.GET.get('mybtn') == 'mybtn2':
        txt = ''
    else if request.GET.get('mybtn'):
        print(f'THIS IS THE TEXT VALUE: {txt}')
    else:
        print('Has not been clicked')
    return render(request, 'main/index.html', {'txt': txt})

and at the HTML side we thus work with a second button:

<form action="" method="get">
    <input type="text" name="some_txt" value="{{ txt }}">
    <button type="submit" class="btn btn-primary" value="mybtn" name="mybtn">Submit</button>
    <button type="submit" class="btn" value="mybtn2" name="mybtn">Reset</button>
</form>


问:
How can i call theme colour in constructor
```<code>var boxDecoration = BoxDecoration(
  borderRadius: BorderRadius.circular(10),
  color: Colors.grey.shade300,

  boxShadow: [
    BoxShadow(
        blurRadius: 15,
        offset: Offset(4, 4),
        color: Colors.grey.shade500,
        spreadRadius: 1),
    BoxShadow(
        blurRadius: 15,
        offset: Offset(-4, -4),
        color: Colors.white,
        spreadRadius: 1)
  ],
);
</code>```

This is my constructor for the container, I want to change its color according to the system theme. Like different colors for the dark and light themes.
How can I do that?

答:
I will prefer using method in this case,

BoxDecoration boxDecoration(BuildContext context) => BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Theme.of(context).colorScheme.primary,
        boxShadow: [...],
      );
```

And use it like decoration: boxDecoration(context),

Body:
var boxDecoration = BoxDecoration(
  borderRadius: BorderRadius.circular(10),
  color: Colors.grey.shade300,

  boxShadow: [
    BoxShadow(
        blurRadius: 15,
        offset: Offset(4, 4),
        color: Colors.grey.shade500,
        spreadRadius: 1),
    BoxShadow(
        blurRadius: 15,
        offset: Offset(-4, -4),
        color: Colors.white,
        spreadRadius: 1)
  ],
);

This is my constructor for the container, I want to change its color according to the system theme. Like different colors for the dark and light themes.
How can I do that?

Body:
I will prefer using method in this case,

BoxDecoration boxDecoration(BuildContext context) => BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Theme.of(context).colorScheme.primary,
        boxShadow: [...],
      );

And use it like decoration: boxDecoration(context),


问:
Android GridLayout layout_columnWeight="1" and layout_width="0dp" programmatically
I use GridLayout and want to add View programmatically.

I want all view evenly divided but get some problem.

My problem:(600 width and 700 width are not equals)

I want :

xml:

```<code>  <GridLayout
                        android:id="@+id/withdrawSettingLayout"
                        android:layout_width="match_parent"
                        android:useDefaultMargins="true"
                        android:layout_height="wrap_content"
                        android:columnCount="4"/>
</code>```

Kotlin code:

```<code>list.forEach { amount->

    val titleText = TextView(context).apply {
        text = amount
        setTextColor(ContextCompat.getColor(context, R.color.white))
    }
    val layoutParams = GridLayout.LayoutParams(GridLayout.spec(GridLayout.UNDEFINED, 1f), GridLayout.spec(GridLayout.UNDEFINED, 1f))
    layoutParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1f)
    viewBinding.withdrawSettingLayout.addView(titleText, layoutParams)
}
</code>```

how to solve it, thanks.

答:
Not sure if it helps, but you can try to also add:</p>
```<code>layoutParams.width = 0
</code>```

Body:
I use GridLayout and want to add View programmatically.

I want all view evenly divided but get some problem.

My problem:(600 width and 700 width are not equals)

I want :

xml:

  <GridLayout
                        android:id="@+id/withdrawSettingLayout"
                        android:layout_width="match_parent"
                        android:useDefaultMargins="true"
                        android:layout_height="wrap_content"
                        android:columnCount="4"/>

Kotlin code:

list.forEach { amount->

    val titleText = TextView(context).apply {
        text = amount
        setTextColor(ContextCompat.getColor(context, R.color.white))
    }
    val layoutParams = GridLayout.LayoutParams(GridLayout.spec(GridLayout.UNDEFINED, 1f), GridLayout.spec(GridLayout.UNDEFINED, 1f))
    layoutParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1f)
    viewBinding.withdrawSettingLayout.addView(titleText, layoutParams)
}

how to solve it, thanks.

Body:
Not sure if it helps, but you can try to also add:

layoutParams.width = 0


问:
How to Pass Id correctly to Rest API Endpoint from React
I'm trying to fetch data through endpoint from Django Rest Framework
endpoint is :

```<code>/api/v1/categories/nested/{id}/
</code>```

Problem is when I'm requesting with id, Django server show this error :

```<code>ValueError: Field 'id' expected a number but got 'undefined'.
[07/Feb/2022 15:53:01] "GET /api/v1/categories/nested/undefined/ HTTP/1.1" 500 162581
</code>```

As this suggest I'm unable to Pass id correctly,
So need littl help to fix that
I'm using actions > reducer > store > component approach using react redux
action.js

```<code>export const listCategoryDetails = (id) => async (dispatch) => {
    try {
      dispatch({ type: CATEGORY_DETAIL_REQUEST });

      const { data } = await axios.get(`/api/v1/categories/nested/${id}`); // Purpose to show nested brands[]

      dispatch({
        type: CATEGORY_DETAIL_SUCCESS,
        payload: data,
      });
    } catch (error) {
      dispatch({
        type: CATEGORY_DETAIL_FAIL,
        payload:
          error.response && error.response.data.detail
            ? error.response.data.detail
            : error.message,
      });
    }
  };
</code>```

reducer.js

```<code>export const categoryDetailsReducer = (
    state = { category: {  } },
    action
  ) => {
    switch (action.type) {
      case CATEGORY_DETAIL_REQUEST:
        return { loading: true, ...state };

      case CATEGORY_DETAIL_SUCCESS:
        return { loading: false, category: action.payload };

      case CATEGORY_DETAIL_FAIL:
        return { loading: false, error: action.payload };

      default:
        return state;
    }
  };
</code>```

store.js

```<code>const reducer = combineReducers({
  categoryDetail: categoryDetailsReducer,
});
</code>```

component

```<code>function CategoryDetail({ match, history }) {
    // const { id } = useParams();
    // console.log(id);
    const dispatch = useDispatch();
    const categoryList = useSelector((state) => state.categoryList);
    const { loading, error, categories , page, pages} = categoryList;

    useEffect(() => {

        dispatch(listCategoryDetails());
    }, [dispatch, match]);

  return <div>

                {categories.map(category => (
                <Col key={category.id} sm={12} md={8} lg={4} xl={3} >

                    <h1><strong>{category.title}</strong></h1>))}

</div>;
}

export default CategoryDetail;
</code>```

答:
const id = ...
and pass it to dispatch function dispatch(listCategoryDetails(id))

Body:
I'm trying to fetch data through endpoint from Django Rest Framework
endpoint is :

/api/v1/categories/nested/{id}/

Problem is when I'm requesting with id, Django server show this error :

ValueError: Field 'id' expected a number but got 'undefined'.
[07/Feb/2022 15:53:01] "GET /api/v1/categories/nested/undefined/ HTTP/1.1" 500 162581

As this suggest I'm unable to Pass id correctly,
So need littl help to fix that
I'm using actions > reducer > store > component approach using react redux
action.js

export const listCategoryDetails = (id) => async (dispatch) => {
    try {
      dispatch({ type: CATEGORY_DETAIL_REQUEST });

      const { data } = await axios.get(`/api/v1/categories/nested/${id}`); // Purpose to show nested brands[]

      dispatch({
        type: CATEGORY_DETAIL_SUCCESS,
        payload: data,
      });
    } catch (error) {
      dispatch({
        type: CATEGORY_DETAIL_FAIL,
        payload:
          error.response && error.response.data.detail
            ? error.response.data.detail
            : error.message,
      });
    }
  };

reducer.js

export const categoryDetailsReducer = (
    state = { category: {  } },
    action
  ) => {
    switch (action.type) {
      case CATEGORY_DETAIL_REQUEST:
        return { loading: true, ...state };

      case CATEGORY_DETAIL_SUCCESS:
        return { loading: false, category: action.payload };

      case CATEGORY_DETAIL_FAIL:
        return { loading: false, error: action.payload };

      default:
        return state;
    }
  };

store.js

const reducer = combineReducers({
  categoryDetail: categoryDetailsReducer,
});

component

function CategoryDetail({ match, history }) {
    // const { id } = useParams();
    // console.log(id);
    const dispatch = useDispatch();
    const categoryList = useSelector((state) => state.categoryList);
    const { loading, error, categories , page, pages} = categoryList;

    useEffect(() => {

        dispatch(listCategoryDetails());
    }, [dispatch, match]);

  return

                {categories.map(category => (
                <Col key={category.id} sm={12} md={8} lg={4} xl={3} >

{category.title}
))}

;
}

export default CategoryDetail;


问:
open viewcontroller on half screen
I want to open a segue, but only on a half screen, the rest I want to be an ImageView, I tried searching up segue padding, but couldn't find what I was looking for, In figma, I've added an IOS extension, where I got an asset( picture below ), what I see on picture is a view opened on half screen, is there any other way beside UIView to achive my end result?

答:
I'm always using this pod FittedSheets</p>
```<code>        let storyboard = UIStoryboard(name: "Order", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "PaymentTypeVC") as! PaymentTypeVC
        let sheetVC = Utils.createSheetController(vc: vc, sizes: [.fixed(320)])
        sheetVC.modalPresentationStyle = .overFullScreen
        present(sheetVC, animated: true, completion: nil)
</code>```

Title: open viewcontroller on half screen

Body:
I'm always using this pod FittedSheets

        let storyboard = UIStoryboard(name: "Order", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "PaymentTypeVC") as! PaymentTypeVC
        let sheetVC = Utils.createSheetController(vc: vc, sizes: [.fixed(320)])
        sheetVC.modalPresentationStyle = .overFullScreen
        present(sheetVC, animated: true, completion: nil)


Title: Python - Data manipulation in a file

Body:
I'm at the stage where I've a txt file in the form:

text1;10;20;11
text2;3;4;5
text3;4;5;7

Anyone got any idea what function to use to get rid of the numbers in the middle of each line?
I would like to have in output:

text1;11
text2;5
text3;7

Currently I have done:

    for ii in files:
        if ii.endswith(".txt"):  # only txt files
            with open(ii, 'r') as f:
                content = f.read()
                f.close()
                content1 = re.sub('\t', '', content, flags=re.M)
                content2 = re.sub(' ', '', content1, flags=re.M)
                f = open(ii, "w+")
                f.write(content2)
                f.close()

Body:
a=['text1;10;20;11','text2;3;4;5','text3;4;5;7']
for i in a:
  s=i.split(';')
  print(s[0] + ';' + s[-1])

Output:

text1;11
text2;5
text3;7


问:
How to write a java program that computes the value of e^x
I'm trying to figure out how to answer this question for my Java class, using only while loops:

Write an application that computes the value of mathematical constant e^x by using the following formula. Allow the user to enter the number of terms to calculate. e^x = 1 + (x/1!) + (x^2/2!) + (x^3/3!) + ...

I can't figure out how I would do this without also asking the user for a value for x? Below is the code that I created for calculating x with the number of terms and just the number 1 for the exponent of each fraction. Any help is appreciated

```<code>import java.util.Scanner;
public class FactorialB {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int counter = 0;
        float answer = 0;

        System.out.print("Enter number of terms: ");
    int n = scanner.nextInt();

    while (counter < n) {
            double factorial = 1;
            int factCounter = counter;
            while (factCounter > 1) {
        factorial = factCounter * factorial;
        factCounter--;
            }

            answer += 1 / factorial;
            counter++;
    }

    System.out.printf("e = %f%n", answer);
    }
}
</code>```

答:
Firstly the question you seem to be asking:

There is no way to make a program that will give e for a specific number unless you ask the user for that number.

However it might be that they just want you to make a method that provides the solution (if it were called) independently of user input. (because the code to get user input isn't very interesting, what is interesting is how you reach the result).

An alternative way to provide x and n are for instance passing them as commandline arguments. (args[] in your main would be a way to provide them)

I would create a separate method that receives x and n that covers the main calculation:

```<code>e^x = 1 + (x/1!) + (x^2/2!) + (x^3/3!) + ...
</code>```

And separate methods that cover 'calculating a single term (x^1/1!), (x^2/2!), etc' and 'factorialize(n)'

```<code>public void calculatePartialE_term(int x, int n) {
    if (n == 0) {
        return 1; // this will allow you to use a while loop, covers the n = 0 case
    } else {
        // removed the implementation, but basically do
        // x^n/n! here for whatever value of n this term is calculating.
    }
}

public int calcualteNFactorial(int n) {
    // assert n >= 1
    // use a while loop to calculate n factorial
}
</code>```

the benefit of doing this in a separate methods is that you can prove / verify the working of calculatePartialE_term or calcualteNFactorial independently of one another.

now you can simply write a while loop based on x and n to do something like

```<code>public int calculateE_to_x(int x, int n) {
    int current = 0;
    int sum = 0;
    while (current <= n) {
        sum += calculatePartialE_term(x, current);
    }
}
</code>```

I wouldn't expect your teacher to expect you to show code that handles user input but even if that is the case it will be easier for them to verify your work if the actual work (of calculating) is done in a separate method.

Body:
I'm trying to figure out how to answer this question for my Java class, using only while loops:

Write an application that computes the value of mathematical constant e^x by using the following formula. Allow the user to enter the number of terms to calculate. e^x = 1 + (x/1!) + (x^2/2!) + (x^3/3!) + ...

I can't figure out how I would do this without also asking the user for a value for x? Below is the code that I created for calculating x with the number of terms and just the number 1 for the exponent of each fraction. Any help is appreciated

import java.util.Scanner;
public class FactorialB {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int counter = 0;
        float answer = 0;

        System.out.print("Enter number of terms: ");
    int n = scanner.nextInt();

    while (counter < n) {
            double factorial = 1;
            int factCounter = counter;
            while (factCounter > 1) {
        factorial = factCounter * factorial;
        factCounter--;
            }

            answer += 1 / factorial;
            counter++;
    }

    System.out.printf("e = %f%n", answer);
    }
}

Body:
Firstly the question you seem to be asking:

There is no way to make a program that will give e for a specific number unless you ask the user for that number.

However it might be that they just want you to make a method that provides the solution (if it were called) independently of user input. (because the code to get user input isn't very interesting, what is interesting is how you reach the result).

An alternative way to provide x and n are for instance passing them as commandline arguments. (args[] in your main would be a way to provide them)

I would create a separate method that receives x and n that covers the main calculation:

e^x = 1 + (x/1!) + (x^2/2!) + (x^3/3!) + ...

And separate methods that cover 'calculating a single term (x^1/1!), (x^2/2!), etc' and 'factorialize(n)'

public void calculatePartialE_term(int x, int n) {
    if (n == 0) {
        return 1; // this will allow you to use a while loop, covers the n = 0 case
    } else {
        // removed the implementation, but basically do
        // x^n/n! here for whatever value of n this term is calculating.
    }
}

public int calcualteNFactorial(int n) {
    // assert n >= 1
    // use a while loop to calculate n factorial
}

the benefit of doing this in a separate methods is that you can prove / verify the working of calculatePartialE_term or calcualteNFactorial independently of one another.

now you can simply write a while loop based on x and n to do something like

public int calculateE_to_x(int x, int n) {
    int current = 0;
    int sum = 0;
    while (current <= n) {
        sum += calculatePartialE_term(x, current);
    }
}

I wouldn't expect your teacher to expect you to show code that handles user input but even if that is the case it will be easier for them to verify your work if the actual work (of calculating) is done in a separate method.


问:
Linked Service Microsoft office inside a Managed Virtual Network or REST API
Hopefully someone will have some experience of trying similar things and can offer some help.

Background

I have an Azure Synapse Analytics Workspace inside a Managed Virtual Network with Data Exfiltration Protection enabled.  Public network access has been disabled. I have a customer VNET to with Private endpoints and a Virtual Machine to connect to the workspace. This works fine and I can connect to and configure a range of services e.g.:

Azure SQL

On-premises SQL using a Self Hosted IR

Azure Key Safe

So I'm comfortable with the concepts in general.

I have questions about connecting to other sources.

Connections

Connections to Microsoft Office for the collection of Graph data.

I have POC on another Synapse Workspace that collects BasicDataSet_v0.Message_v0 and BasicDataSet_v0.User_v0.  However when I attempt to connect to the Microsoft Office Connection as a linked service from within the Managed Virtual Network I cannot connect.

```<code>{
    "name": "Office3651",
    "type": "Microsoft.Synapse/workspaces/linkedservices",
    "properties": {
        "annotations": [],
        "type": "Office365",
        "typeProperties": {
            "office365TenantId": "[TENANT GUID]",
            "servicePrincipalTenantId": "[TENANT GUID]",
            "servicePrincipalId": "[SERVICE PRINCIPAL GUID]",
            "encryptedCredential": "ew0KICAiVmVyc2lvbiI6ICIyMDE3LTExLTMwIiwNCiAgIlByb3RlY3Rpb25Nb2RlIjogIktleSIsDQogICJTZWNyZXRDb250ZW50VHlwZSI6ICJQbGFpbnRleHQiLA0KICAiQ3JlZGVudGlhbElkIjogIlNZTkFQU0VAQUJFNEVBODktM0E5MS00RjExLTgzOTItMjcyOURFNTY2NDk3XzhhMGViNzIyLTRmNTAtNGQ4Zi1iYTVhLTYwYWNiNzQyYjMzMiINCn0="
        },
        "connectVia": {
            "referenceName": "AutoResolveIntegrationRuntime",
            "type": "IntegrationRuntimeReference"
        }
    }
}
</code>```

The error I get attempting to validate the connection is:

```<code>One or more errors occurred.
An error occurred while sending the request.
Unable to connect to the remote server
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 51.105.5.65:443
Activity ID: 218a9020-6de9-4436-b61b-0e62c6b9c147.
</code>```

As indicated I can get this to work without a Managed VNET.

I get similar experiences for REST Api connections, these are connections which I have used outside of a Manage VNET

```<code>The connection to the REST service failed. Endpoint=https://***URL***/, Reason=.
A task was canceled.
Activity ID: 7bc36bd7-d135-4636-8303-89acc84ef711.
</code>```

Request

If anyone has tried similar or has found documentation for a more detailed exploration of how to create linked services I would be very grateful. It becomes harder to justify the use of the Managed VNET if these are hard limitations.

答: I have experimented with this and find that the limiting technology is the use of the Data Exfiltration Protection. If I provision a Managed Virtual Network on the Synapse environment I find that I am able to connect, and extract data from REST endpoints and from Microsoft Office.</p>

Body:
Hopefully someone will have some experience of trying similar things and can offer some help.

Background

I have an Azure Synapse Analytics Workspace inside a Managed Virtual Network with Data Exfiltration Protection enabled.  Public network access has been disabled. I have a customer VNET to with Private endpoints and a Virtual Machine to connect to the workspace. This works fine and I can connect to and configure a range of services e.g.:

Azure SQL

On-premises SQL using a Self Hosted IR

Azure Key Safe

So I'm comfortable with the concepts in general.

I have questions about connecting to other sources.

Connections

Connections to Microsoft Office for the collection of Graph data.

I have POC on another Synapse Workspace that collects BasicDataSet_v0.Message_v0 and BasicDataSet_v0.User_v0.  However when I attempt to connect to the Microsoft Office Connection as a linked service from within the Managed Virtual Network I cannot connect.

{
    "name": "Office3651",
    "type": "Microsoft.Synapse/workspaces/linkedservices",
    "properties": {
        "annotations": [],
        "type": "Office365",
        "typeProperties": {
            "office365TenantId": "[TENANT GUID]",
            "servicePrincipalTenantId": "[TENANT GUID]",
            "servicePrincipalId": "[SERVICE PRINCIPAL GUID]",
            "encryptedCredential": "ew0KICAiVmVyc2lvbiI6ICIyMDE3LTExLTMwIiwNCiAgIlByb3RlY3Rpb25Nb2RlIjogIktleSIsDQogICJTZWNyZXRDb250ZW50VHlwZSI6ICJQbGFpbnRleHQiLA0KICAiQ3JlZGVudGlhbElkIjogIlNZTkFQU0VAQUJFNEVBODktM0E5MS00RjExLTgzOTItMjcyOURFNTY2NDk3XzhhMGViNzIyLTRmNTAtNGQ4Zi1iYTVhLTYwYWNiNzQyYjMzMiINCn0="
        },
        "connectVia": {
            "referenceName": "AutoResolveIntegrationRuntime",
            "type": "IntegrationRuntimeReference"
        }
    }
}

The error I get attempting to validate the connection is:

One or more errors occurred.
An error occurred while sending the request.
Unable to connect to the remote server
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 51.105.5.65:443
Activity ID: 218a9020-6de9-4436-b61b-0e62c6b9c147.

As indicated I can get this to work without a Managed VNET.

I get similar experiences for REST Api connections, these are connections which I have used outside of a Manage VNET

The connection to the REST service failed. Endpoint=https://***URL***/, Reason=.
A task was canceled.
Activity ID: 7bc36bd7-d135-4636-8303-89acc84ef711.

Request

If anyone has tried similar or has found documentation for a more detailed exploration of how to create linked services I would be very grateful. It becomes harder to justify the use of the Managed VNET if these are hard limitations.


问:
What is the difference between Subject and BehaviorSubject?
I'm not clear on the difference between a Subject and a BehaviorSubject. Is it just that a BehaviorSubject has the getValue() function?

答:
A BehaviorSubject holds one value (so we actually need to initialize a default value). When it is subscribed it emits that value immediately. A Subject on the other hand, does not hold a value.

What it actually means is that in Subject, the subscribers will only receive the upcoming value where as in BehaviorSubject the subscribers will receive the previous value and also upcoming value.

So, let's take an example to see how this will behave:

```<code>let mySubject = new Subject<number>();

mySubject.subscribe(x => console.log("The first Subscription : " + x));

mySubject.next(1);
mySubject.next(2);

mySubject.subscribe(x => console.log("The second Subscription : " + x));

mySubject.next(3);

// The first Subscription : 1
// The first Subscription : 2
// The first Subscription : 3
// The second Subscription : 3
</code>```

Like we saw above, the first 2 values were output from the subject before the second subscription registered, so it didn't get them, it only got the new values after subscribed. The first subscription got them all, since it subscribed before the first values were output.

Now, let's change the subject to BehaviorSubject and see the difference:

```<code>let mySubject = new BehaviorSubject<number>(0);

mySubject.subscribe((x) => console.log('The first Subscription : ' + x));

mySubject.next(1);
mySubject.next(2);

mySubject.subscribe((x) => console.log('The second Subscription : ' + x));

mySubject.next(3);

// The first Subscription : 0 (since it's the initial value)
// The first Subscription : 1
// The first Subscription : 2
// The second Subscription : 2 (since it's the initial value for the seconde subscriber)
// The first Subscription : 3
// The second Subscription : 3
</code>```

Now, notice how the first subscriber outputs 0 since the BehaviorSubject was initialized with 0. When the second subscriber subscribes, it immediately emits the '2' value since it was the last value to be handled so it acts as the initial value for it.

More about the difference between BehaviorSubject and Subject can be found here

Body:
A BehaviorSubject holds one value (so we actually need to initialize a default value). When it is subscribed it emits that value immediately. A Subject on the other hand, does not hold a value.

What it actually means is that in Subject, the subscribers will only receive the upcoming value where as in BehaviorSubject the subscribers will receive the previous value and also upcoming value.

So, let's take an example to see how this will behave:

let mySubject = new Subject<number>();

mySubject.subscribe(x => console.log("The first Subscription : " + x));

mySubject.next(1);
mySubject.next(2);

mySubject.subscribe(x => console.log("The second Subscription : " + x));

mySubject.next(3);

// The first Subscription : 1
// The first Subscription : 2
// The first Subscription : 3
// The second Subscription : 3

Like we saw above, the first 2 values were output from the subject before the second subscription registered, so it didn't get them, it only got the new values after subscribed. The first subscription got them all, since it subscribed before the first values were output.

Now, let's change the subject to BehaviorSubject and see the difference:

let mySubject = new BehaviorSubject<number>(0);

mySubject.subscribe((x) => console.log('The first Subscription : ' + x));

mySubject.next(1);
mySubject.next(2);

mySubject.subscribe((x) => console.log('The second Subscription : ' + x));

mySubject.next(3);

// The first Subscription : 0 (since it's the initial value)
// The first Subscription : 1
// The first Subscription : 2
// The second Subscription : 2 (since it's the initial value for the seconde subscriber)
// The first Subscription : 3
// The second Subscription : 3

Now, notice how the first subscriber outputs 0 since the BehaviorSubject was initialized with 0. When the second subscriber subscribes, it immediately emits the '2' value since it was the last value to be handled so it acts as the initial value for it.

More about the difference between BehaviorSubject and Subject can be found here


问:
String / label issue
I've got an issue with a label showing a String.

So, basically, I've got a function - (void) didFinishUpdatesSuccessfully. If this function is being called it means that an action has been completed successfully. It creates a time stamp and stores it to NSUserDefaults. All this works like a charme..
Here's the function:

```<code>    - (void) didFinishUpdatesSuccessfully {

        // Create formatted date string
        NSDate *currDate = [NSDate date];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"dd/MM/YYYY - hh:mm:ss a"];
        NSString *dateString = [dateFormatter stringFromDate:currDate];

        NSMutableString* lastUpdated;
        lastUpdated = [[NSMutableString stringWithFormat:@"%@",dateString] retain];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:lastUpdated forKey:@"lastUpdated"];
        [defaults synchronize];

        //--- Alert dialog
        NSString *title;
        title = @"All the latest hotspots have now been saved!";
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: title
                                                    message: lastUpdated
                                                   delegate: nil
                                          cancelButtonTitle: [FileUtils appResourceForKey:@"HOTSPOT_GENERAL_BUTTON_TITLE_OK"]
                                          otherButtonTitles: nil];

// ------------------------
//Create label
    UILabel *UpDLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 205, 250, 100)];
    UpDLabel.backgroundColor = [UIColor clearColor]; // [UIColor brownColor];
    UpDLabel.font = [UIFont fontWithName:@"Helvetica" size: 11.0];
    UpDLabel.shadowColor = [UIColor whiteColor];
    UpDLabel.shadowOffset = CGSizeMake(1,1);
    UpDLabel.textColor = [UIColor blackColor];
    UpDLabel.textAlignment = UITextAlignmentRight; // UITextAlignmentCenter, UITextAlignmentLeft
    UpDLabel.lineBreakMode = UILineBreakModeWordWrap;
    NSString *lupdate   = [NSString stringWithFormat: @"Last Update: %@", lastUpdated];

    UpDLabel.text = lupdate;

    [self.view addSubview:UpDLabel];

    [UpDLabel release];
// ------------------------

        [dateFormatter release];
        [lastUpdated release];
        [alert show];
        [alert release];

        //--- remove indicator view
        [self indicatorViewShow:NO];

    }
</code>```

The label with the date string is being displayed. It overrides itself but seems to keep the previous string so it actualy looks like it just adds another layer on top of the previous one. Or in other words, if I perform the - (void) didFinishUpdatesSuccessfully 3 times it will show 3 date strings on top of each other which looks screwed...

What am I doing wrong?

Cheers
Jan

答: Why not create the UILabel inside the - viewDidLoad method instead? Make the label a property of the class then create the label on - viewDidLoad then update the string inside the label inside the - didFinishUpdatesSuccessfully. It will be more convenient.

Title: String / label issue

Body:
I've got an issue with a label showing a String.

So, basically, I've got a function - (void) didFinishUpdatesSuccessfully. If this function is being called it means that an action has been completed successfully. It creates a time stamp and stores it to NSUserDefaults. All this works like a charme..
Here's the function:

    - (void) didFinishUpdatesSuccessfully {

        // Create formatted date string
        NSDate *currDate = [NSDate date];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"dd/MM/YYYY - hh:mm:ss a"];
        NSString *dateString = [dateFormatter stringFromDate:currDate];

        NSMutableString* lastUpdated;
        lastUpdated = [[NSMutableString stringWithFormat:@"%@",dateString] retain];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:lastUpdated forKey:@"lastUpdated"];
        [defaults synchronize];

        //--- Alert dialog
        NSString *title;
        title = @"All the latest hotspots have now been saved!";
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: title
                                                    message: lastUpdated
                                                   delegate: nil
                                          cancelButtonTitle: [FileUtils appResourceForKey:@"HOTSPOT_GENERAL_BUTTON_TITLE_OK"]
                                          otherButtonTitles: nil];

// ------------------------
//Create label
    UILabel *UpDLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 205, 250, 100)];
    UpDLabel.backgroundColor = [UIColor clearColor]; // [UIColor brownColor];
    UpDLabel.font = [UIFont fontWithName:@"Helvetica" size: 11.0];
    UpDLabel.shadowColor = [UIColor whiteColor];
    UpDLabel.shadowOffset = CGSizeMake(1,1);
    UpDLabel.textColor = [UIColor blackColor];
    UpDLabel.textAlignment = UITextAlignmentRight; // UITextAlignmentCenter, UITextAlignmentLeft
    UpDLabel.lineBreakMode = UILineBreakModeWordWrap;
    NSString *lupdate   = [NSString stringWithFormat: @"Last Update: %@", lastUpdated];

    UpDLabel.text = lupdate;

    [self.view addSubview:UpDLabel];

    [UpDLabel release];
// ------------------------

        [dateFormatter release];
        [lastUpdated release];
        [alert show];
        [alert release];

        //--- remove indicator view
        [self indicatorViewShow:NO];

    }

The label with the date string is being displayed. It overrides itself but seems to keep the previous string so it actualy looks like it just adds another layer on top of the previous one. Or in other words, if I perform the - (void) didFinishUpdatesSuccessfully 3 times it will show 3 date strings on top of each other which looks screwed...

What am I doing wrong?

Cheers
Jan