问:
Flutter Inkwell does not update right away
I am trying to insert a widget / change height of a widget upon clicking a button. As demonstrated by the video, the InkWell does not update after calling setState(). This only happens with Ink, if changed to Container everything works fine.

market.dart

```<code>class MarketPage extends StatefulWidget {
  const MarketPage({Key? key}) : super(key: key);

  @override
  _MarketPageState createState() => _MarketPageState();
}

class _MarketPageState extends State<MarketPage> {
  List<String> displayedList = [];
  bool isSearchActive = false;

  final TextEditingController _controller = new TextEditingController();

  @override
  void initState() {
    super.initState();
    MarketList marketList = context.read<MarketList>();
    displayedList = marketList.markets.keys.toList();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(25),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Text(
                    "Markets",
                    style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
                  ),
                ),
                isSearchActive == false
                    ? GestureDetector(
                        onTap: () {
                          print("hello");
                          setState(() {
                            isSearchActive = !isSearchActive;
                          });
                        },
                        child: Icon(
                          Icons.search,
                          size: 30,
                        ),
                      )
                    : GestureDetector(
                        onTap: () {
                          setState(() {
                            isSearchActive = !isSearchActive;
                          });
                        },
                        child: Icon(
                          Icons.arrow_right,
                          size: 30,
                        ),
                      )
              ],
            ),
          ),
          Container(
            height: isSearchActive == true ? 100 : 0,
          ),
          Flexible(
            child: ListView.separated(
              padding: EdgeInsets.all(20),
              separatorBuilder: (BuildContext context, int index) {
                return SizedBox(
                  height: 15,
                );
              },
              shrinkWrap: true,
              physics: BouncingScrollPhysics(),
              scrollDirection: Axis.vertical,
              itemCount: displayedList.length,
              itemBuilder: (BuildContext ctxt, int index) {
                return MarketCard(
                    index, displayedList.length - 1, displayedList[index]);
              },
            ),
          ),
        ],
      ),
    );
  }
</code>```

market_card.dart

```<code>class MarketCard extends StatefulWidget {
  final int myIndex;
  final int lastIndex;
  final String name;

  MarketCard(this.myIndex, this.lastIndex, this.name);

  @override
  State<MarketCard> createState() => _MarketCardState();
}

class _MarketCardState extends State<MarketCard> {
  @override
  initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<MarketList>(
      builder: (context, value, child) => InkWell(
        onTap: () {
          FocusManager.instance.primaryFocus?.unfocus();
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => MarketDetailsPage(widget.name),
            ),
          );
        },
        borderRadius: BorderRadius.vertical(
          top: widget.myIndex == 0 ? Radius.circular(10) : Radius.circular(0),
          bottom: widget.myIndex == widget.lastIndex
              ? Radius.circular(10)
              : Radius.circular(0),
        ),
        child: card(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      ClipOval(
                        child: SizedBox(
                          width: 50,
                          height: 50,
                          child:
                              Image.asset(value.markets[widget.name]!.iconURL),
                        ),
                      ),
                      SizedBox(width: 15),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            value.markets[widget.name]!.name,
                            style: TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 18),
                          ),
                          SizedBox(height: 10),
                          Text(
                            "\$${value.markets[widget.name]!.currentPrice.toString()}",
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                color: value.markets[widget.name]!
                                            .priceChangePercent >
                                        0
                                    ? Colors.green
                                    : Colors.red),
                          ),
                        ],
                      ),
                    ],
                  ),
                  Icon(Icons.keyboard_arrow_right),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}
</code>```

答:
GestureDetector does not work well with InkWell for some reason.

Replacing GestureDetector with InkWell solves the problem:

```<code>InkWell(
  onTap: () {
    setState(() {
      isSearchActive = !isSearchActive;
    });
  },
  child: Icon(Icons.search),
),
</code>```

Edit

Trying to recreate the bug in a completely new codebase I came to the conclusion that it is not the problem of any single Widget. Something went wrong with the combination of those widgets. I am not sure what. InkWell seems to solve the problem for me, though.

Body:
I am trying to insert a widget / change height of a widget upon clicking a button. As demonstrated by the video, the InkWell does not update after calling setState(). This only happens with Ink, if changed to Container everything works fine.

market.dart

class MarketPage extends StatefulWidget {
  const MarketPage({Key? key}) : super(key: key);

  @override
  _MarketPageState createState() => _MarketPageState();
}

class _MarketPageState extends State<MarketPage> {
  List<String> displayedList = [];
  bool isSearchActive = false;

  final TextEditingController _controller = new TextEditingController();

  @override
  void initState() {
    super.initState();
    MarketList marketList = context.read<MarketList>();
    displayedList = marketList.markets.keys.toList();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(25),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Text(
                    "Markets",
                    style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
                  ),
                ),
                isSearchActive == false
                    ? GestureDetector(
                        onTap: () {
                          print("hello");
                          setState(() {
                            isSearchActive = !isSearchActive;
                          });
                        },
                        child: Icon(
                          Icons.search,
                          size: 30,
                        ),
                      )
                    : GestureDetector(
                        onTap: () {
                          setState(() {
                            isSearchActive = !isSearchActive;
                          });
                        },
                        child: Icon(
                          Icons.arrow_right,
                          size: 30,
                        ),
                      )
              ],
            ),
          ),
          Container(
            height: isSearchActive == true ? 100 : 0,
          ),
          Flexible(
            child: ListView.separated(
              padding: EdgeInsets.all(20),
              separatorBuilder: (BuildContext context, int index) {
                return SizedBox(
                  height: 15,
                );
              },
              shrinkWrap: true,
              physics: BouncingScrollPhysics(),
              scrollDirection: Axis.vertical,
              itemCount: displayedList.length,
              itemBuilder: (BuildContext ctxt, int index) {
                return MarketCard(
                    index, displayedList.length - 1, displayedList[index]);
              },
            ),
          ),
        ],
      ),
    );
  }

market_card.dart

class MarketCard extends StatefulWidget {
  final int myIndex;
  final int lastIndex;
  final String name;

  MarketCard(this.myIndex, this.lastIndex, this.name);

  @override
  State<MarketCard> createState() => _MarketCardState();
}

class _MarketCardState extends State<MarketCard> {
  @override
  initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<MarketList>(
      builder: (context, value, child) => InkWell(
        onTap: () {
          FocusManager.instance.primaryFocus?.unfocus();
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => MarketDetailsPage(widget.name),
            ),
          );
        },
        borderRadius: BorderRadius.vertical(
          top: widget.myIndex == 0 ? Radius.circular(10) : Radius.circular(0),
          bottom: widget.myIndex == widget.lastIndex
              ? Radius.circular(10)
              : Radius.circular(0),
        ),
        child: card(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      ClipOval(
                        child: SizedBox(
                          width: 50,
                          height: 50,
                          child:
                              Image.asset(value.markets[widget.name]!.iconURL),
                        ),
                      ),
                      SizedBox(width: 15),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            value.markets[widget.name]!.name,
                            style: TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 18),
                          ),
                          SizedBox(height: 10),
                          Text(
                            "\$${value.markets[widget.name]!.currentPrice.toString()}",
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                color: value.markets[widget.name]!
                                            .priceChangePercent >
                                        0
                                    ? Colors.green
                                    : Colors.red),
                          ),
                        ],
                      ),
                    ],
                  ),
                  Icon(Icons.keyboard_arrow_right),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}

Body:
GestureDetector does not work well with InkWell for some reason.

Replacing GestureDetector with InkWell solves the problem:

InkWell(
  onTap: () {
    setState(() {
      isSearchActive = !isSearchActive;
    });
  },
  child: Icon(Icons.search),
),

Edit

Trying to recreate the bug in a completely new codebase I came to the conclusion that it is not the problem of any single Widget. Something went wrong with the combination of those widgets. I am not sure what. InkWell seems to solve the problem for me, though.


来源: stackexchange

问:
ansible_network_ os not valid attribute error
I am new to Ansible and I am trying to run this playbook. I get an error stating "ansible_network_os is not valid attribute to play". Can you please let me know what could be wrong with my script?

---
- name: configure interfaces setting
  hosts: switches
  connection: network_cli
  ansible_network_os: cisco.ios.ios
  tasks:
    - name: configure interface
      ios_config:
        before:
          - default interface Gi0/3
        lines:
          - ip address 10.10.10.1 255.255.255.0
        after:
          -no shutdown
        parents: interface Gi0/3
```

答: Much appreciated your help, the other issue is resolved by providing the username and password parameter into the play.</p>

ContentLicense: CC BY-SA 4.0


问:
using .substring after .replace is creating an error sometimes, how could I properly structure the substring so that it always works?
I'm getting an error with my code below. I am trying to make a calculator, and I am using strings as input and typecasting in order to solve. The calculator was working fine, but now I am trying to add an ans button to allow for having equations based on previous answer. I am having an issue with the substrings now, and in equations where ans comes first like 'ans+88" I get NaN as a result and 88 turns into undefined. But when I switch the substring parameters it messes it up for other types of equations as described in the comments below.

link to repository

else if(equation.indexOf("+") != -1){
//this finds the the index of +
                let pInd = equation.indexOf("+")

        /*before I added this, it worked properly, firstValue would get the firstvalue
        secondvalue would get the second value and it added correctly
        the point of the if statement is to replace ans with props.prevResult which is
       the previous answer from the previous entered equation. After it replaces it
       removes the whitespace*/
                if(equation.includes("ᴀɴs")){
                   equation =  equation.replace(/ᴀɴs/gi, String(props.prevResult))
                  //my attempt to remove whitespace since i thought it might be the issue
                   // but now I'm pretty sure the issue is with substring.
                   equation = equation.replace(/\s/g, '')
                }
                equation = String(equation)
                firstVal = equation.substring(0,pInd)
                //this line is where the error seems to come from
                secondVal = equation.substring(pInd+1,equation.length)
                /* when ans is first such as in 'ans + 9" 9 becomes undefined ans stays
                correct. I tried replacing it with pInd+1, equation.length-1, but that
               made it so that equations like '9+ans' were cut short,
               and regular ('1+55') equations also broke.*/

                result = parseFloat(firstVal)+parseFloat(secondVal)
                props.setInput(result)
                props.setPrevResult(result)
                setResultGot(true)
            }
```

答: The solution @james gave solved the issue, the position of the + sign was obviously going to change after I replaced ans, so that line just had to be moved to after the replacement, silly mistake, I appreciate the help.</p>


问:
Return different values from computed Vue
I have buttons to set different dates (one for tomorrow and one for in a week) and have made a function for only calculating business days. So the 'tomorrow' button should show either 'Tomorrow' or 'Monday' and the 'week' button should either show 'in 7 days', 'in 8 days' or 'in 9 days' depending on what day of the week it currently is.

These are my two buttons:

```<code>        <v-btn
            :value="dates[0]"
        >
            {{ buttonText }}
        </v-btn>
        <v-btn
            :value="dates[1]"
        >
            {{ buttonText }}
        </v-btn>
</code>```

This is my computed for the different dates to postpone and this works just fine:

```<code>postponeDays(): DateTime[] {
    const today = DateTime.local()
    return [
        onlyBusinessDays(today, 1),
        onlyBusinessDays(today, 7),
    ]
},
</code>```

The onlyBusinessDays function looks like this:

```<code>export const onlyBusinessDays = (date: DateTime, nrOfDays: number): DateTime => {
    const d = date.startOf('day').plus({ days: nrOfDays })
    const daysToAdd = d.weekday === 6 ? 2 : d.weekday === 7 ? 1 : 0
    return d.plus({ days: daysToAdd })
}
</code>```

And here is my computed for getting the button text that is not working and I need help with:

```<code>    buttonText(): DateTime | string {
        if (!this.dates[1]) {
            if (DateTime.local().plus({ days: 7 }).hasSame(this.dates[1], 'day')) {
                return 'in 7 days'
            }
            if (DateTime.local().plus({ days: 8 }).hasSame(this.dates[1], 'day')) {
                return 'in 8 days'
            } else return 'in 9 days'
        } else {
            if (DateTime.local().plus({ days: 1 }).hasSame(this.dates[0], 'day')) {
                return 'Tomorrow'
            } else return 'Monday'
        }
    },
</code>```

I've tried doing the computed for the button text in many different ways but I always end up getting the exact same text for both buttons which feels weird since the postpone function for actually getting the correct dates is working perfectly fine. Anyone that knows what I'm doing wrong? :)

答:
Make buttonText a method instead, so you can put {{ buttonText(dates[0]) }} and {{ buttonText(dates[0]) }}.

As in the Vue docs on computed properties:

Instead of a computed property, we can define the same function as a method. For the end result, the two approaches are indeed exactly the same. However, the difference is that computed properties are cached based on their reactive dependencies. A computed property will only re-evaluate when some of its reactive dependencies have changed.

Your two v-btn elements aren't evaluated with different scopes, so there's no reason for Vue to believe that buttonText will have different values in both cases. What you want conceptually is for buttonText to return different values based on the date you pass in, which fits much closer to a method as far as Vue is concerned.

As on the methods page of the guide:

It is also possible to call a method directly from a template. As we'll see shortly, it's usually better to use a computed property instead. However, using a method can be useful in scenarios where computed properties aren't a viable option.

Body:
I have buttons to set different dates (one for tomorrow and one for in a week) and have made a function for only calculating business days. So the 'tomorrow' button should show either 'Tomorrow' or 'Monday' and the 'week' button should either show 'in 7 days', 'in 8 days' or 'in 9 days' depending on what day of the week it currently is.

These are my two buttons:

        <v-btn
            :value="dates[0]"
        >
            {{ buttonText }}
        </v-btn>
        <v-btn
            :value="dates[1]"
        >
            {{ buttonText }}
        </v-btn>

This is my computed for the different dates to postpone and this works just fine:

postponeDays(): DateTime[] {
    const today = DateTime.local()
    return [
        onlyBusinessDays(today, 1),
        onlyBusinessDays(today, 7),
    ]
},

The onlyBusinessDays function looks like this:

export const onlyBusinessDays = (date: DateTime, nrOfDays: number): DateTime => {
    const d = date.startOf('day').plus({ days: nrOfDays })
    const daysToAdd = d.weekday === 6 ? 2 : d.weekday === 7 ? 1 : 0
    return d.plus({ days: daysToAdd })
}

And here is my computed for getting the button text that is not working and I need help with:

    buttonText(): DateTime | string {
        if (!this.dates[1]) {
            if (DateTime.local().plus({ days: 7 }).hasSame(this.dates[1], 'day')) {
                return 'in 7 days'
            }
            if (DateTime.local().plus({ days: 8 }).hasSame(this.dates[1], 'day')) {
                return 'in 8 days'
            } else return 'in 9 days'
        } else {
            if (DateTime.local().plus({ days: 1 }).hasSame(this.dates[0], 'day')) {
                return 'Tomorrow'
            } else return 'Monday'
        }
    },

I've tried doing the computed for the button text in many different ways but I always end up getting the exact same text for both buttons which feels weird since the postpone function for actually getting the correct dates is working perfectly fine. Anyone that knows what I'm doing wrong? :)


问:
Values are not inserting into the table (this only happens when I include the $token variable so I assume it is something to do with that variable)?
Here is my index.php code:

```<code>class DB {
    private static function connection() {
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname="social";

        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $conn;
    }
    public static function query($query, $params =array()) {
        $statement=self::connection()->prepare($query);
        $statement->execute($params);

        if (explode(' ', $query)[0] == 'SELECT') {
            $data = $statement->fetchAll();
            return $data;
        }
    }
}
</code>```

And here is my actlogin.php code:

```<code>include('index.php');

if(isset($_POST['login'])) {
 $username = $_POST['username'];
 $password = $_POST['password'];

if (DB::query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))){

    if (password_verify($password, DB::query('SELECT password FROM users WHERE username=:username', array(':username'=>$username))[0]['password'])){
        echo 'Logged in!';

        $cstrong = True;
        $token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
        echo $token;
        $user_id = DB::query('SELECT id FROM users WHERE username=:username', array(':username'=>$username))[0]['id'];
        DB::query('INSERT INTO login_tokens (token, user_id) VALUES (:token, :user_id)', array(':token'=>$token, ':user_id'=>$user_id));

    }else{
        echo 'Incorrect password!';
    }

} else {
    echo 'User not found!';
}

}
</code>```

I created a table in Sequel Pro called login_tokens with three columns: id, token, and user_id. Token has a unique key. I then made a relationship with the user_id column in the login_tokens table to the id column in the users table. I am following a tutorial and can't seem to figure out what I missed.

答:
DB::query() returns an array, so you're assigning an array to $user_id. You need to index the array to get the userid from the results. So you need to do

```<code>$rows = DB::query('SELECT id FROM users WHERE username=:username', array(':username'=>$username))[0]['id'];
if (!empty($rows)) {
    $user_id = $rows[0]['id'];
}
</code>```

You could also just avoid the problem entirely by getting the userid in the INSERT query:

```<code>DB::query('INSERT INTO login_tokens (token, user_id)
    SELECT :token, id
    FROM users
    WHERE username = :username', array(':token'=>$token, ':usename'=>$username));
</code>```

Body:
Here is my index.php code:

class DB {
    private static function connection() {
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname="social";

        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $conn;
    }
    public static function query($query, $params =array()) {
        $statement=self::connection()->prepare($query);
        $statement->execute($params);

        if (explode(' ', $query)[0] == 'SELECT') {
            $data = $statement->fetchAll();
            return $data;
        }
    }
}

And here is my actlogin.php code:

include('index.php');

if(isset($_POST['login'])) {
 $username = $_POST['username'];
 $password = $_POST['password'];

if (DB::query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))){

    if (password_verify($password, DB::query('SELECT password FROM users WHERE username=:username', array(':username'=>$username))[0]['password'])){
        echo 'Logged in!';

        $cstrong = True;
        $token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
        echo $token;
        $user_id = DB::query('SELECT id FROM users WHERE username=:username', array(':username'=>$username))[0]['id'];
        DB::query('INSERT INTO login_tokens (token, user_id) VALUES (:token, :user_id)', array(':token'=>$token, ':user_id'=>$user_id));

    }else{
        echo 'Incorrect password!';
    }

} else {
    echo 'User not found!';
}

}

I created a table in Sequel Pro called login_tokens with three columns: id, token, and user_id. Token has a unique key. I then made a relationship with the user_id column in the login_tokens table to the id column in the users table. I am following a tutorial and can't seem to figure out what I missed.

Body:
DB::query() returns an array, so you're assigning an array to $user_id. You need to index the array to get the userid from the results. So you need to do

$rows = DB::query('SELECT id FROM users WHERE username=:username', array(':username'=>$username))[0]['id'];
if (!empty($rows)) {
    $user_id = $rows[0]['id'];
}

You could also just avoid the problem entirely by getting the userid in the INSERT query:

DB::query('INSERT INTO login_tokens (token, user_id)
    SELECT :token, id
    FROM users
    WHERE username = :username', array(':token'=>$token, ':usename'=>$username));


问:
How to use Get request with DTO in NestJs?
I am trying to write a function to handle the Get request, here is my code:

```<code>  @Get('/find')
  async find(@Param() testname: NameDto) {
    console.log(testname.name);
  }
</code>```

Here is my dto:

```<code>export class NameDto {
  @IsString()
  @ApiProperty({ required: true })
  name: string;
}
</code>```

I am using the Swagger to test this API :

When I input a signle a , I got the following response:

```<code>{
  "statusCode": 400,
  "message": [
    "name must be a string"
  ],
  "error": "Bad Request"
}
</code>```

here are more input example :

They all return the same response.

Then, I change the find function like this with @Query:

```<code>  @Get('/find')
  async find(@Query() testname: NameDto) {
    console.log(testname.name);
  }
</code>```

here is my input :

I can have the 200-ok response.
Here is another example:

I enter 1 as the input, and I still can get the 200 response. The dto is not working as expected.

Am I missing something?
Any help would be appreciate.

答: You're using query parameters for the url, so you do need to use @Query(). Query parameters will always come in as strings, because that's how express and fastify work. You can enable transform: true and {transformOptions: { enableImplicitConverion: true } } in the ValidationPipe's options and get numbers to show up as actual numbers.

Body:
I am trying to write a function to handle the Get request, here is my code:

  @Get('/find')
  async find(@Param() testname: NameDto) {
    console.log(testname.name);
  }

Here is my dto:

export class NameDto {
  @IsString()
  @ApiProperty({ required: true })
  name: string;
}

I am using the Swagger to test this API :

When I input a signle a , I got the following response:

{
  "statusCode": 400,
  "message": [
    "name must be a string"
  ],
  "error": "Bad Request"
}

here are more input example :

They all return the same response.

Then, I change the find function like this with @Query:

  @Get('/find')
  async find(@Query() testname: NameDto) {
    console.log(testname.name);
  }

here is my input :

I can have the 200-ok response.
Here is another example:

I enter 1 as the input, and I still can get the 200 response. The dto is not working as expected.

Am I missing something?
Any help would be appreciate.


问:
Send prop with react route
I try to send a data called favProduct to Favourites component. When I send the data, I get undefined. How can I send a data when I use react route?</p>
```<code>const [favProduct, setFavProduct] = useState([1,2,3,4,5]);

  return (
    <Router>
      <div className="App">
        <Header />
        <Switch>
          <Route path="/" exact component={Home}/>
          <Route path="/men" component={Men} />
          <Route path="/women" component={Women} />
          <Route path="/kids" component={Kids} />
          <Route path="/productBuy" component={ProductBuy} />
          <Route path="/favourites" component={Favourites} />
          <Route path="/cart" component={Cart} />
          <Route path="/checkout" component={Checkout} />
          <Route path="/addproduct" component={AddProduct} />
        </Switch>
        <Footer />
      </div>
    </Router>
  );
}
</code>```

答:
If you want, or need, to send additional props to routed components, use the Route's render prop to inject the props and forward the route props.

Example:

```<code><Route
  path="/favourites"
  render={props => <Favourites {...props} favProduct={favProduct} />}
/>
</code>```

Access all the route props as done previously, i.e. props.location, props.history, etc... and access the new prop that was passed, i.e. props.favProduct.

Title: Send prop with react route

Body:
I try to send a data called favProduct to Favourites component. When I send the data, I get undefined. How can I send a data when I use react route?

const [favProduct, setFavProduct] = useState([1,2,3,4,5]);

  return (
    <Router>

        <Switch>
          <Route path="/" exact component={Home}/>
          <Route path="/men" component={Men} />
          <Route path="/women" component={Women} />
          <Route path="/kids" component={Kids} />
          <Route path="/productBuy" component={ProductBuy} />
          <Route path="/favourites" component={Favourites} />
          <Route path="/cart" component={Cart} />
          <Route path="/checkout" component={Checkout} />
          <Route path="/addproduct" component={AddProduct} />
        </Switch>

    </Router>
  );
}

Body:
If you want, or need, to send additional props to routed components, use the Route's render prop to inject the props and forward the route props.

Example:

<Route
  path="/favourites"
  render={props => <Favourites {...props} favProduct={favProduct} />}
/>

Access all the route props as done previously, i.e. props.location, props.history, etc... and access the new prop that was passed, i.e. props.favProduct.


问:
how do i expand the enter button to bridge all 3 rows? i.e should be extended to sit under both '0' '.' and 'Del'
I'm using tkinter to create my first GUI and i have reached a problem. How do I expand the 'enter' button of the numpad (which opens when you click a empty box) to cover the empty space currently there?

How do I designate the opening position of the numpad?

Additionally if anyone has a shorter/faster way to code this i would be interested as to how it can be done as whilst speed isn't extremely necessary for my project, it is always nice to have.

The code is as follows below:

import tkinter
from tkinter import *
from tkinter import simpledialog

def enumerate_row_column(iterable, num_cols):
    for idx, item in enumerate(iterable):
        row = idx // num_cols
        col = idx % num_cols
        yield row,col,item

class NumpadEntry(Entry):
    def __init__(self,parent=None,**kw):
        Entry.__init__(self,parent,**kw)
        self.bind('<FocusIn>',self.numpadEntry)
        self.bind('<FocusOut>',self.numpadExit)
        self.edited = False
    def numpadEntry(self,event):
        if self.edited == False:
            print("You Clicked on me")
            self['bg']= '#ffffcc'
            self.edited = True
            new = numPad(self)
        else:
            self.edited = False
    def numpadExit(self,event):
        self['bg']= '#ffffff'

class numPad(simpledialog.Dialog):
    def __init__(self,master=None,textVariable=None):
        self.top = Toplevel(master=master)
        self.top.protocol("WM_DELETE_WINDOW",self.ok)
        self.createWidgets()
        self.master = master

    def createWidgets(self):
        btn_list = ['1',  '2',  '3', '4',  '5',  '6', '7',  '8',  '0', '0',  '.',  'Del', 'Enter']
        # create and position all buttons with a for-loop
        btn = []
        # Use custom generator to give us row/column positions
        for r,c,label in enumerate_row_column(btn_list,3):
            # partial takes care of function and argument
            cmd = lambda x = label: self.click(x)
            # create the button
            cur = Button(self.top, text=label, width=5, height=3, command=cmd)
            # position the button
            cur.grid(row=r, column=c)
            btn.append(cur)

    def click(self,label):
        print(label)
        if label == 'Del':
            currentText = self.master.get()
            self.master.delete(0, END)
            self.master.insert(0, currentText[:-1])
        elif label == 'Enter':
            self.ok()
        else:
            currentText = self.master.get()
            self.master.delete(0, END)
            self.master.insert(0, currentText+label)
    def ok(self):
        self.top.destroy()
        self.top.master.focus()

class App(Frame):
    def __init__(self,parent=None,**kw):
        Frame.__init__(self,parent,**kw)
        self.textEntryVar1 = StringVar()
        self.e1 = NumpadEntry(self,textvariable=self.textEntryVar1)
        self.e1.grid()

        self.textEntryVar2 = StringVar()
        self.e2 = NumpadEntry(self,textvariable=self.textEntryVar2)
        self.e2.grid()

if __name__ == '__main__':
    root = Tk()
    root.geometry("550x300")
    root.title("Monitoring Site GUI")
    app = App(root)
    app.grid()

    root.mainloop()
```

答:
As you get in comment: you need to use columnspan to use space in many columns, and sticky (west-east) to resize button in this space.

```<code>    cur.grid(row=4, column=0, columnspan=3, sticky='we')
</code>```

```<code>def createWidgets(self):

    # create and position all buttons
    btn = []

    # --- without ENTER ---

    btn_list = [
        '1',  '2',  '3',
        '4',  '5',  '6',
        '7',  '8',  '0',
        '0',  '.',  'Del'
    ]
    # Use custom generator to give us row/column positions
    for r,c,label in enumerate_row_column(btn_list, 3):
        # partial takes care of function and argument
        cmd = lambda x = label: self.click(x)
        # create the button
        cur = Button(self.top, text=label, width=5, height=3, command=cmd)
        # position the button
        cur.grid(row=r, column=c)
        btn.append(cur)
        cur.grid(row=r, column=c)

    # --- only ENTER ---

    cmd = lambda x="Enter": self.click(x)
    # create the button
    cur = Button(self.top, text="Enter", width=5, height=3, command=cmd)
    # position the button
    cur.grid(row=4, column=0, columnspan=3, sticky='we')
    btn.append(cur)
</code>```

Body:
As you get in comment: you need to use columnspan to use space in many columns, and sticky (west-east) to resize button in this space.

    cur.grid(row=4, column=0, columnspan=3, sticky='we')

def createWidgets(self):

    # create and position all buttons
    btn = []

    # --- without ENTER ---

    btn_list = [
        '1',  '2',  '3',
        '4',  '5',  '6',
        '7',  '8',  '0',
        '0',  '.',  'Del'
    ]
    # Use custom generator to give us row/column positions
    for r,c,label in enumerate_row_column(btn_list, 3):
        # partial takes care of function and argument
        cmd = lambda x = label: self.click(x)
        # create the button
        cur = Button(self.top, text=label, width=5, height=3, command=cmd)
        # position the button
        cur.grid(row=r, column=c)
        btn.append(cur)
        cur.grid(row=r, column=c)

    # --- only ENTER ---

    cmd = lambda x="Enter": self.click(x)
    # create the button
    cur = Button(self.top, text="Enter", width=5, height=3, command=cmd)
    # position the button
    cur.grid(row=4, column=0, columnspan=3, sticky='we')
    btn.append(cur)


问:
How to grab the onSubmit event for a form?
I want to know how to grab the onsubmit event from a form to do some form validation, because I don't have access to it directly. (I am writing a Wordpress plugin for comments, so don't have direct access to the form tag or the submit button.)

I got so frustrated trying to do this for my plugin that I have written a Hello World version below. I want it to show the 'Hello World' alert when I load the page, and the "form submitted" alert when I click on the submit button. Instead, it shows both pop ups when the page loads.

Here is my code:

```<code>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>
    <head>
    <title>Hello World</title>
    </head>
    <body>
    <h2>Test</h2>
    <form action="#" method="post" id="commentform">

    <p><input type="text" name="author" id="author" size="22" tabindex="1" />
    <label for="author"><small>Name (required)</small></label></p>

    <p><input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />

    </form>

    <script type="text/JavaScript">
    <!--
    alert("Hello world");

    var formCheck = document.getElementById("commentform");

    formCheck.onSubmit = doMapping();

    function doMapping() {
        alert("form submitted");
        return false;
    }

    -->
    </script>

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

答:
Thank you! Actually I solved it another way, using both Andrew's suggestion and the window.onload event - I think the problem was partly because the element hadn't actually loaded.</p>

```<code>window.onload = function(){
    if (document.getElementById("commentform")){
        document.getElementById("commentform").onsubmit = doMapping;
    }
}

function doMapping(){
            alert("form submitted");
            return false;
}
</code>```

OwnerDisplayName: Dan

LastEditorDisplayName: Dan

ContentLicense: CC BY-SA 3.0

Body:
I want to know how to grab the onsubmit event from a form to do some form validation, because I don't have access to it directly. (I am writing a Wordpress plugin for comments, so don't have direct access to the form tag or the submit button.)

I got so frustrated trying to do this for my plugin that I have written a Hello World version below. I want it to show the 'Hello World' alert when I load the page, and the "form submitted" alert when I click on the submit button. Instead, it shows both pop ups when the page loads.

Here is my code:

  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

    <title>Hello World</title>

Test

    <form action="#" method="post" id="commentform">

<input type="text" name="author" id="author" size="22" tabindex="1" />
    Name (required)

<input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />

    </form>

Body:
Thank you! Actually I solved it another way, using both Andrew's suggestion and the window.onload event - I think the problem was partly because the element hadn't actually loaded.

window.onload = function(){
    if (document.getElementById("commentform")){
        document.getElementById("commentform").onsubmit = doMapping;
    }
}

function doMapping(){
            alert("form submitted");
            return false;
}

ContentLicense: CC BY-SA 2.5


问:
HTTPS equivalent of WebRequest.CreateHttp on Windows Phone 7?
I have some C# code in a Windows Phone app...

```<code>WebRequest wrq = WebRequest.CreateHttp("http://bing.com");
</code>```

is it possible to make this use HTTPS instead? There's no CreateHttps, and no obvious flags for me to fiddle with.

Chris

答:
Note you should not use CreateHttp in your app code!
http://msdn.microsoft.com/en-us/library/ff382776%28v=vs.95%29.aspx</p>

Body:
I have some C# code in a Windows Phone app...

WebRequest wrq = WebRequest.CreateHttp("http://bing.com");

is it possible to make this use HTTPS instead? There's no CreateHttps, and no obvious flags for me to fiddle with.

Chris


问:
SXSSFSheet autoSizeColumn error on apache poi 4.1.2
My project using Spring Boot. I try to export data to excel file with org.apache.poi 4.1.2 , i use method autoSizeColumn to auto size column

```<code>headerRow.forEach(item -> {
  sheet.autoSizeColumn(item.getColumnIndex());
});
</code>```

but i get the error

```<code>java.lang.IllegalStateException: Could not auto-size column. Make sure the column was tracked prior to auto-sizing the column.
at org.apache.poi.xssf.streaming.SXSSFSheet.autoSizeColumn(SXSSFSheet.java:1591)
at org.apache.poi.xssf.streaming.SXSSFSheet.autoSizeColumn(SXSSFSheet.java:1545)
</code>```

how to fix this error

答:
I have fixed the above issue with the following, do this only after you are done rendering everything on to the sheet

if you have list for columns then the following will work fine.

```<code>// autoSizing of the columns

for (int i = 0; i < columns.size(); i++) {
  workbookSheet.trackAllColumnsForAutoSizing();
  workbookSheet.autoSizeColumn(i);
}
</code>```

For your case the below will work.

```<code>headerRow.forEach(item -> {
  sheet.trackAllColumnsForAutoSizing();
  sheet.autoSizeColumn(item.getColumnIndex());
});
</code>```

Body:
My project using Spring Boot. I try to export data to excel file with org.apache.poi 4.1.2 , i use method autoSizeColumn to auto size column

headerRow.forEach(item -> {
  sheet.autoSizeColumn(item.getColumnIndex());
});

but i get the error

java.lang.IllegalStateException: Could not auto-size column. Make sure the column was tracked prior to auto-sizing the column.
at org.apache.poi.xssf.streaming.SXSSFSheet.autoSizeColumn(SXSSFSheet.java:1591)
at org.apache.poi.xssf.streaming.SXSSFSheet.autoSizeColumn(SXSSFSheet.java:1545)

how to fix this error

Body:
I have fixed the above issue with the following, do this only after you are done rendering everything on to the sheet

if you have list for columns then the following will work fine.

// autoSizing of the columns

for (int i = 0; i < columns.size(); i++) {
  workbookSheet.trackAllColumnsForAutoSizing();
  workbookSheet.autoSizeColumn(i);
}

For your case the below will work.

headerRow.forEach(item -> {
  sheet.trackAllColumnsForAutoSizing();
  sheet.autoSizeColumn(item.getColumnIndex());
});


问:
Disk clean up in Apache geode
I have set up apache geode for caching.

```<code>Cluster Configuration:
Locator: 1GB      - Mounted volume 2GB
Server2: 1GB      - Mounted volume 2GB
Server2: 1GB      - Mounted volume 2GB
</code>```

Region configuration in cache.xml

```<code><region name="answerCache">
    <region-attributes data-policy="PARTITION_PERSISTENT_OVERFLOW">
        <eviction-attributes>
            <lru-heap-percentage action="overflow-to-disk" />
        </eviction-attributes>
    </region-attributes>
</region>
</code>```

Geode pushes the data to disk (based on LRU) when region fills with data.
But I'm not getting any configuration where geode lets me delete entry from disk if its getting filled.
I'm getting Out of memory error if disk gets full.

I want to apply LRU on disk writes as well so that least used entries can be deleted from disk.

答: You can use GFSH disk store commands to manage disk stores. You can even use a GUI (https://github.com/ldom22/GGGUI)</p>

Title: Disk clean up in Apache geode

Body:
I have set up apache geode for caching.

Cluster Configuration:
Locator: 1GB      - Mounted volume 2GB
Server2: 1GB      - Mounted volume 2GB
Server2: 1GB      - Mounted volume 2GB

Region configuration in cache.xml

<region name="answerCache">
    <region-attributes data-policy="PARTITION_PERSISTENT_OVERFLOW">
        <eviction-attributes>
            <lru-heap-percentage action="overflow-to-disk" />
        </eviction-attributes>
    </region-attributes>
</region>

Geode pushes the data to disk (based on LRU) when region fills with data.
But I'm not getting any configuration where geode lets me delete entry from disk if its getting filled.
I'm getting Out of memory error if disk gets full.

I want to apply LRU on disk writes as well so that least used entries can be deleted from disk.


问:
Distributed cache or maybe database to send data to clients?
I need help with a common senario.....

I have a central database or datastore in some way. Then I have a bunch of Win-clients. These clients all needs a part of this data in a local datastore of some kind. They also need to update their local datastore if the central datastore is updated.

I think this must be a common senario but I cant find any simple solutions to it. Of course I can implement a pubsub system using queues or something like that. But is there another way? (hopefully simpler or at least smarter :) )

答: CouchDB offers bi-directional replication of data and supports working in a disconnected way. Sounds like a good match for your high-level requirements.</p>


问:
Vuetify <v-toolbar-title> and links that do not change formating
It looks like you can use the to in  so the router link extends.  I want to make the  link to the the front page.   does not work and wrapping  in  changes the formatting.  How can I make <-v-toolbar-title> link without changing the formatting?  Thanks!</p>

答:
this is a simplified version using v-btn and plain. class to center title is optional.</p>
```<code>   <v-toolbar-title class="flex text-center">
    <v-btn plain to="/">Title</v-btn>
   </v-toolbar-title>
</code>```

Body:
this is a simplified version using v-btn and plain. class to center title is optional.

   <v-toolbar-title class="flex text-center">
    <v-btn plain to="/">Title</v-btn>
   </v-toolbar-title>


问:
Maven. Repository authentication
I tried setup deploy to local repository:

-- settings.xml --

```<code><server>
  <id>myrepo</id>
  <username>deployer</username>
  <password>123456</password>
</server>
</code>```

-- pom.xml ---

```<code><repositories>
    <repository>
        <id>myrepo</id>
        <url>http://myserver.com/artifactory/libs-release-local</url>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
        </releases>
        <snapshots>
            <enabled>false</enabled>
            <updatePolicy>always</updatePolicy>
        </snapshots>
    </repository>
</repositories>
</code>```

when I execute "mvn deploy" I got error:

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.4:
deploy (default-deploy) on project xxx: Failed to deploy artifacts: Co
uld not transfer artifact xxx:xxx:war:0.1-20130527.121430-3 from/to myserver.com
(http://myserver.com:8083/artifactory/libs-snapshot-local): Failed to transfer file:
http://myserver.com:8083/artifactory/libs-snapshot-local/xxx/0.1-SNAPSHOT
/xxx-0.1-20130527.121430-3.war. Return code is: 401
</code>```

Artifactory log:

```<code>2013-05-27 16:14:38,158 [DENIED DEPLOY] libs-snapshot-local:xxx/0.1-SNAPSHOT
/xxx-0.1-20130527.121430-3.pom for anonymous/192.168.6.36.
</code>```

If I change server/repository id to "myserver.com" - deploy WORK!
But it does not suit me because that did not work plugin changelog with svn at myserver.com

I tried to add tags "profile" and "mirror" to server.xml and "distributionManagement" to pom.xml - getting the same error

server/repository id must be named ONLY as my server?

UPDATE1:

I remove tag  'repositories' from pom.xml and added tag 'distributionManagment':

--- pom.xml ---

```<code><distributionManagement>
    <repository>
        <id>myrepo</id>
        <name>myrepo</name>
        <url>http://myserver.com/artifactory/libs-release-local</url>
    </repository>
    <snapshotRepository>
        <id>myrepo</id>
        <name>myrepo</name>
        <url>http://myserver.com/artifactory/libs-snapshots-local</url>
        <uniqueVersion>false</uniqueVersion>
    </snapshotRepository>
</distributionManagement>
</code>```

(server.xml has not changed) - getting the same error "Failed to deploy..."

UPDATE2:

Try...

--- server.xml ---

```<code><profiles>
    <profile>
        <id>artifactory</id>
        <repositories>
            <repository>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
                <id>central</id>
                <name>libs-release</name>
                <url>http://myserver.com/artifactory/libs-release-local</url>
            </repository>
            <repository>
                <snapshots />
                <id>snapshots</id>
                <name>libs-snapshot</name>
                <url>http://myserver.com/artifactory/libs-snapshot-local</url>
            </repository>
        </repositories>
    </profile>
</profiles>

<activeProfiles>
    <activeProfile>artifactory</activeProfile>
</activeProfiles>

<server>
    <id>snapshots</id>
    <username>deployer</username>
    <password>123456</password>
</server>
<server>
    <id>central</id>
    <username>deployer</username>
    <password>123456</password>
</server>
</code>```

--- pom.xml ---

```<code><distributionManagement>
    <repository>
        <id>central</id>
        <name>Internal Releases</name>
        <url>http://myserver.com/artifactory/libs-release-local</url>
    </repository>
    <snapshotRepository>
        <id>snapshots</id>
        <name>Internal Snapshots</name>
        <url>http://myserver.com/artifactory/libs-snapshots-local</url>
        <uniqueVersion>false</uniqueVersion>
    </snapshotRepository>
</distributionManagement>
</code>```

execute 'mvn deploy' - again error :(

```<code>Failed to deploy artifacts: Could not transfer artifact xxx:xxx:war:0.1-20130528.050526-1 from/to snapshots (http://myserver.com/artifactory/libs-snapshots-local)
</code>```

答:
You settings.xml is missing the <servers> </servers> tags around your two <server> nodes. - https://maven.apache.org/settings.html#Servers

Also, I would avoid using generic id's like 'snapshots' and 'central'. Understandable if they are there for the purpose of SO.

The last update to this question didn't include the specific error code, but in the original error it was a 401 (Unauthorized) which leads me to believe that it's not able to find your servers authentication information due to invalid settings.xml

Title: Maven. Repository authentication

Body:
I tried setup deploy to local repository:

-- settings.xml --

<server>
  <id>myrepo</id>
  <username>deployer</username>
  <password>123456</password>
</server>

-- pom.xml ---

<repositories>
    <repository>
        <id>myrepo</id>
        <url>http://myserver.com/artifactory/libs-release-local</url>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
        </releases>
        <snapshots>
            <enabled>false</enabled>
            <updatePolicy>always</updatePolicy>
        </snapshots>
    </repository>
</repositories>

when I execute "mvn deploy" I got error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.4:
deploy (default-deploy) on project xxx: Failed to deploy artifacts: Co
uld not transfer artifact xxx:xxx:war:0.1-20130527.121430-3 from/to myserver.com
(http://myserver.com:8083/artifactory/libs-snapshot-local): Failed to transfer file:
http://myserver.com:8083/artifactory/libs-snapshot-local/xxx/0.1-SNAPSHOT
/xxx-0.1-20130527.121430-3.war. Return code is: 401

Artifactory log:

2013-05-27 16:14:38,158 [DENIED DEPLOY] libs-snapshot-local:xxx/0.1-SNAPSHOT
/xxx-0.1-20130527.121430-3.pom for anonymous/192.168.6.36.

If I change server/repository id to "myserver.com" - deploy WORK!
But it does not suit me because that did not work plugin changelog with svn at myserver.com

I tried to add tags "profile" and "mirror" to server.xml and "distributionManagement" to pom.xml - getting the same error

server/repository id must be named ONLY as my server?

UPDATE1:

I remove tag  'repositories' from pom.xml and added tag 'distributionManagment':

--- pom.xml ---

<distributionManagement>
    <repository>
        <id>myrepo</id>
        <name>myrepo</name>
        <url>http://myserver.com/artifactory/libs-release-local</url>
    </repository>
    <snapshotRepository>
        <id>myrepo</id>
        <name>myrepo</name>
        <url>http://myserver.com/artifactory/libs-snapshots-local</url>
        <uniqueVersion>false</uniqueVersion>
    </snapshotRepository>
</distributionManagement>

(server.xml has not changed) - getting the same error "Failed to deploy..."

UPDATE2:

Try...

--- server.xml ---

<profiles>
    <profile>
        <id>artifactory</id>
        <repositories>
            <repository>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
                <id>central</id>
                <name>libs-release</name>
                <url>http://myserver.com/artifactory/libs-release-local</url>
            </repository>
            <repository>
                <snapshots />
                <id>snapshots</id>
                <name>libs-snapshot</name>
                <url>http://myserver.com/artifactory/libs-snapshot-local</url>
            </repository>
        </repositories>
    </profile>
</profiles>

<activeProfiles>
    <activeProfile>artifactory</activeProfile>
</activeProfiles>

<server>
    <id>snapshots</id>
    <username>deployer</username>
    <password>123456</password>
</server>
<server>
    <id>central</id>
    <username>deployer</username>
    <password>123456</password>
</server>

--- pom.xml ---

<distributionManagement>
    <repository>
        <id>central</id>
        <name>Internal Releases</name>
        <url>http://myserver.com/artifactory/libs-release-local</url>
    </repository>
    <snapshotRepository>
        <id>snapshots</id>
        <name>Internal Snapshots</name>
        <url>http://myserver.com/artifactory/libs-snapshots-local</url>
        <uniqueVersion>false</uniqueVersion>
    </snapshotRepository>
</distributionManagement>

execute 'mvn deploy' - again error :(

Failed to deploy artifacts: Could not transfer artifact xxx:xxx:war:0.1-20130528.050526-1 from/to snapshots (http://myserver.com/artifactory/libs-snapshots-local)


问:
How to resolve `error starting spoon shell`?
I'm porting Pentaho kettle to apache hop and I followed the steps given in this document, after changing the dependencies build was successful but got an error while starting spoon.sh file

Below was the error I caught when I run spoon.sh

```<code>2021/12/01 13:08:04 - General - ERROR (version 1.1.0-SNAPSHOT, build 1.1.0-SNAPSHOT from 2021-12-01 07.33.36 by ****) : Error starting Spoon shell
2021/12/01 13:08:04 - General - ERROR (version 1.1.0-SNAPSHOT, build 1.1.0-SNAPSHOT from 2021-12-01 07.33.36 by ****) : java.lang.ExceptionInInitializerError
2021/12/01 13:08:04 - General -     at org.pentaho.di.ui.spoon.Spoon.init(Spoon.java:870)
2021/12/01 13:08:04 - General -     at org.pentaho.di.ui.spoon.Spoon.createContents(Spoon.java:9352)
2021/12/01 13:08:04 - General -     at org.eclipse.jface.window.Window.create(Window.java:431)
2021/12/01 13:08:04 - General -     at org.eclipse.jface.window.Window.open(Window.java:788)
2021/12/01 13:08:04 - General -     at org.pentaho.di.ui.spoon.Spoon.start(Spoon.java:9383)
2021/12/01 13:08:04 - General -     at org.pentaho.di.ui.spoon.Spoon.main(Spoon.java:711)
2021/12/01 13:08:04 - General -     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2021/12/01 13:08:04 - General -     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
2021/12/01 13:08:04 - General -     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
2021/12/01 13:08:04 - General -     at java.lang.reflect.Method.invoke(Method.java:498)
2021/12/01 13:08:04 - General -     at org.pentaho.commons.launcher.Launcher.main(Launcher.java:92)
2021/12/01 13:08:04 - General - Caused by: java.util.MissingResourceException: Can't find bundle for base name ui/laf, locale en_IN
2021/12/01 13:08:04 - General -     at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1581)
2021/12/01 13:08:04 - General -     at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1396)
2021/12/01 13:08:04 - General -     at java.util.ResourceBundle.getBundle(ResourceBundle.java:1091)
2021/12/01 13:08:04 - General -     at org.pentaho.di.ui.spoon.XulSpoonResourceBundle.<clinit>(XulSpoonResourceBundle.java:69)
2021/12/01 13:08:04 - General -     ... 11 more
</code>```

Has anyone run into this before? Do you have a resolution?

答:
I am not sure what you are trying to do, but Apache Hop does not have a spoon.sh file. To start the GUI you have to use the hop-gui.sh file.

It seems you have copied over the spoon.sh file?

If you are porting over a step/job entry to a Hop Transform or Action there is a sample repository available here you can use the code in there as a base to see what has to be done to get everything running in Hop.

If you have specific questions you can also contact the developers on the mailing list

Body:
I'm porting Pentaho kettle to apache hop and I followed the steps given in this document, after changing the dependencies build was successful but got an error while starting spoon.sh file

Below was the error I caught when I run spoon.sh

2021/12/01 13:08:04 - General - ERROR (version 1.1.0-SNAPSHOT, build 1.1.0-SNAPSHOT from 2021-12-01 07.33.36 by ****) : Error starting Spoon shell
2021/12/01 13:08:04 - General - ERROR (version 1.1.0-SNAPSHOT, build 1.1.0-SNAPSHOT from 2021-12-01 07.33.36 by ****) : java.lang.ExceptionInInitializerError
2021/12/01 13:08:04 - General -     at org.pentaho.di.ui.spoon.Spoon.init(Spoon.java:870)
2021/12/01 13:08:04 - General -     at org.pentaho.di.ui.spoon.Spoon.createContents(Spoon.java:9352)
2021/12/01 13:08:04 - General -     at org.eclipse.jface.window.Window.create(Window.java:431)
2021/12/01 13:08:04 - General -     at org.eclipse.jface.window.Window.open(Window.java:788)
2021/12/01 13:08:04 - General -     at org.pentaho.di.ui.spoon.Spoon.start(Spoon.java:9383)
2021/12/01 13:08:04 - General -     at org.pentaho.di.ui.spoon.Spoon.main(Spoon.java:711)
2021/12/01 13:08:04 - General -     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2021/12/01 13:08:04 - General -     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
2021/12/01 13:08:04 - General -     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
2021/12/01 13:08:04 - General -     at java.lang.reflect.Method.invoke(Method.java:498)
2021/12/01 13:08:04 - General -     at org.pentaho.commons.launcher.Launcher.main(Launcher.java:92)
2021/12/01 13:08:04 - General - Caused by: java.util.MissingResourceException: Can't find bundle for base name ui/laf, locale en_IN
2021/12/01 13:08:04 - General -     at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1581)
2021/12/01 13:08:04 - General -     at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1396)
2021/12/01 13:08:04 - General -     at java.util.ResourceBundle.getBundle(ResourceBundle.java:1091)
2021/12/01 13:08:04 - General -     at org.pentaho.di.ui.spoon.XulSpoonResourceBundle.<clinit>(XulSpoonResourceBundle.java:69)
2021/12/01 13:08:04 - General -     ... 11 more

Has anyone run into this before? Do you have a resolution?


问:
Murmur Hash 3 in python
I'm trying to implement murmur hash 3 in python. I have confusion with this function mmh3.hash_bytes(key).

Here is the code that I tried:

```<code>a = bitarray()
print(mmh3.hash('A')) # output is 1423767502 a hash value
</code>```

Next, I tried one more function

```<code>print(mmh3.hash_bytes('A'))
# output is b'z\xb1)\x9a\xb7\xc2_\x037\x99\xddF\x9c\xf2}8'
</code>```

The output of mmh3.hash_bytes('A') confuses me. Shouldn't both functions have the same value? Because both hash value 'A'. Correct me if I'm wrong.

答:
The reason why they are different is simple in modern cryptography; domain separation so that different sized calls to MurmurHash (SHA2 has it and SHA3 derived has it, too) will output different values. This may prevent some attacks in the Cryptographic case (MurmurHash is not cryptographic hash) or help to diverge the tables in some attacks...

A nice definition from  Hashing to Elliptic Curves

Cryptographic protocols that use random oracles are often analyzed

under the assumption that random oracles answer only queries

generated by that protocol.  In practice, this assumption does not

hold if two protocols query the same random oracle.  Concretely,

consider protocols P1 and P2 that query random oracle R: if P1 and P2
both query R on the same value x, the security analysis of one or

both protocols may be invalidated.

A common approach to addressing this issue is called domain

separation, which allows a single random oracle to simulate multiple,
independent oracles.  This is effected by ensuring that each

simulated oracle sees queries that are distinct from those seen by

all other simulated oracles.  For example, to simulate two oracles R1
and R2 given a single oracle R, one might define

R1(x) := R("R1" || x)    R2(x) := R("R2" || x)

In this example, "R1" and "R2" are called domain separation tags;

they ensure that queries to R1 and R2 cannot result in identical

queries to R.  Thus, it is safe to treat R1 and R2 as independent

oracles.

If we look at the code sample from Wikipedia we will see this line;

hash ← hash XOR len

that is the desired length (len) is incorporated into MurmurHash so that the value will change instead of simple truncation of the 128-bit output.

Title: Murmur Hash 3 in python

Body:
I'm trying to implement murmur hash 3 in python. I have confusion with this function mmh3.hash_bytes(key).

Here is the code that I tried:

a = bitarray()
print(mmh3.hash('A')) # output is 1423767502 a hash value

Next, I tried one more function

print(mmh3.hash_bytes('A'))
# output is b'z\xb1)\x9a\xb7\xc2_\x037\x99\xddF\x9c\xf2}8'

The output of mmh3.hash_bytes('A') confuses me. Shouldn't both functions have the same value? Because both hash value 'A'. Correct me if I'm wrong.


问:
Use Automator App Variables as imput for Javascript action steps
I am trying to input the content of a variable generated with the Automator app onto the next action step, to define the value of a javascript script variable. Change the variable using javascript code and push the result further to the next action step. Then turn it back into an Automator variable, or update the one previously used as input. I am sure you will find it as a simple thing, but I couldn't find a way to get it working. This question might be silly, after all. Many thanks in advance. Check the screenshot of the Automator sequence of steps. Screenshot of the actions set in Automator App</p>
```<code>function run(input) {

    var str = input;
var l1 = str.replace(/ /g, "_");
    str = l1;
var l2 = str.replace(/:/g, "-");

    return l2;
}
</code>```

答:
The input to an Automator action is an array, so you will need to step through the array or convert/coerce to whatever class you are wanting to work with. In your posted script, the replace() method is for a string, so you are getting an error trying to use that method on the input array.

If you just want a single input item you can use input[0] to get the first item in the array, or input.join() to join the array items together.

Body:
I am trying to input the content of a variable generated with the Automator app onto the next action step, to define the value of a javascript script variable. Change the variable using javascript code and push the result further to the next action step. Then turn it back into an Automator variable, or update the one previously used as input. I am sure you will find it as a simple thing, but I couldn't find a way to get it working. This question might be silly, after all. Many thanks in advance. Check the screenshot of the Automator sequence of steps. Screenshot of the actions set in Automator App

function run(input) {

    var str = input;
var l1 = str.replace(/ /g, "_");
    str = l1;
var l2 = str.replace(/:/g, "-");

    return l2;
}


问:
IVS Token Authorisation
I hope I explain a bit clearly with the problems I'm having.
I used this guide ( https://catalog.us-east-1.prod.workshops.aws/v2/workshops/022adf04-0ff9-49af-848f-993e42575540/en-US/playauth) to generate a playback token , and after reading and following this entire guide, I was able to successfully generate a token.

```<code>"statusCode": 200,
  "body": "{\"token\":\"eyJhbGciOiJFUzM4NCIsInR5cCI6IkpXVCJ9.xxxxxxxxxxxxxxxxxxxxxxm4iOiJhcm46YXdzOml2czpldS13ZXN0LTE6MDgxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxOmFjY2Vzcy1jb250cm9sLWFsbG93LW9yaWdpbiI6Imh0dHBzOi8vd3d3LmZvb3R5LnRvIiwiaWF0IjoxNjQ0MzUyMjI2LCJleHAiOjE2NDY5NDQyMjZ9.EQ1tnLU5uQhxnkVjJvrOo_z1Jlf4w0yMuhgWtB8ZBf_NKgWJCcMmToKia8u1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"}",
  "headers": {
    "Access-Control-Allow-Origin": "https://www.xxxxxx.com"
  }
}
</code>```

I put this token behind the stream url and everything works as it should work;

```<code>https://247dfhj3e56u467.us-xxxx-1.playback.live-video.net/api/video/v1/us-east-1.08xxxxxx06.channel.GpxxxxxxxxxxwA.m3u8?token=eyJhbGciOiJFUzM4NCIsInR5cCI6IkpXVCJ9.xxxxxxxxxxxxxxxxxxxxxxm4iOiJhcm46YXdzOml2czpldS13ZXN0LTE6MDgxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxOmFjY2Vzcy1jb250cm9sLWFsbG93LW9yaWdpbiI6Imh0dHBzOi8vd3d3LmZvb3R5LnRvIiwiaWF0IjoxNjQ0MzUyMjI2LCJleHAiOjE2NDY5NDQyMjZ9.EQ1tnLU5uQhxnkVjJvrOo_z1Jlf4w0yMuhgWtB8ZBf_NKgWJCcMmToKia8u1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
</code>```

This token only works on my domain, and when I use it on my other domain I get a CORS error because it only works on the domain I specified in the lambda function.

So so far the token generator works...

But guess what, as soon as there are people who can take the stream link through the source code, say use this link in VLC or any other m3u8 player, even some hls/m3u8 browser extensions in chrome can play it effortlessly.

My question to you is as follows;

Am I using the given token correctly?

Is there perhaps a lambda function script (json) that no longer enables these playback options?

Or can I solve this in another way so that the stream can only be played on my domain and not on a VLC player or browser extension.

Hopefully someone has a solution for this, because in this way the function of the token generator is not really valuable.

Sincerely.

答:
Your use case seems correct.

Unfortunately, it's difficult to revoke the JWT token once you created. There is a property of expire time. Default value is 2 days in index.js and you can set shorter in case.

If I'd do, I'd integrate with some other systems like Cognito or IP based security groups.

Title: IVS Token Authorisation

Body:
I hope I explain a bit clearly with the problems I'm having.
I used this guide ( https://catalog.us-east-1.prod.workshops.aws/v2/workshops/022adf04-0ff9-49af-848f-993e42575540/en-US/playauth) to generate a playback token , and after reading and following this entire guide, I was able to successfully generate a token.

"statusCode": 200,
  "body": "{\"token\":\"eyJhbGciOiJFUzM4NCIsInR5cCI6IkpXVCJ9.xxxxxxxxxxxxxxxxxxxxxxm4iOiJhcm46YXdzOml2czpldS13ZXN0LTE6MDgxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxOmFjY2Vzcy1jb250cm9sLWFsbG93LW9yaWdpbiI6Imh0dHBzOi8vd3d3LmZvb3R5LnRvIiwiaWF0IjoxNjQ0MzUyMjI2LCJleHAiOjE2NDY5NDQyMjZ9.EQ1tnLU5uQhxnkVjJvrOo_z1Jlf4w0yMuhgWtB8ZBf_NKgWJCcMmToKia8u1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"}",
  "headers": {
    "Access-Control-Allow-Origin": "https://www.xxxxxx.com"
  }
}

I put this token behind the stream url and everything works as it should work;

https://247dfhj3e56u467.us-xxxx-1.playback.live-video.net/api/video/v1/us-east-1.08xxxxxx06.channel.GpxxxxxxxxxxwA.m3u8?token=eyJhbGciOiJFUzM4NCIsInR5cCI6IkpXVCJ9.xxxxxxxxxxxxxxxxxxxxxxm4iOiJhcm46YXdzOml2czpldS13ZXN0LTE6MDgxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxOmFjY2Vzcy1jb250cm9sLWFsbG93LW9yaWdpbiI6Imh0dHBzOi8vd3d3LmZvb3R5LnRvIiwiaWF0IjoxNjQ0MzUyMjI2LCJleHAiOjE2NDY5NDQyMjZ9.EQ1tnLU5uQhxnkVjJvrOo_z1Jlf4w0yMuhgWtB8ZBf_NKgWJCcMmToKia8u1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

This token only works on my domain, and when I use it on my other domain I get a CORS error because it only works on the domain I specified in the lambda function.

So so far the token generator works...

But guess what, as soon as there are people who can take the stream link through the source code, say use this link in VLC or any other m3u8 player, even some hls/m3u8 browser extensions in chrome can play it effortlessly.

My question to you is as follows;

Am I using the given token correctly?

Is there perhaps a lambda function script (json) that no longer enables these playback options?

Or can I solve this in another way so that the stream can only be played on my domain and not on a VLC player or browser extension.

Hopefully someone has a solution for this, because in this way the function of the token generator is not really valuable.

Sincerely.


问:
SQL select IN clause from array?
I have a list

```<code>$list = array('a','b','c','d','e','f');
$filter_list = join(", " $list);
select * from test where id_col=12 and try_col in ($filter_list);
</code>```

Anybody could tell me how Can I do this.?

答:
```<code>$list = array('a','b','c','d','e','f');
$filter_list = "'" . join("', '", $list) . "'";
$query = "select * from test where id=12 and try_col in ($filter_list)";
// select * from test where id=12 and try_col in ('a', 'b', 'c', 'd', 'e', 'f')
</code>```

Note that this will fail if your array values contain '. Here is a workaround:

```<code>$list = array("a'a",'a\a','b','c','d','e','f');
$temp = array_map("addslashes", $list);
$query = "SELECT * FROM test WHERE id=12 AND try_col in ('" . implode("','", $temp) . "')";
// SELECT * FROM test WHERE id=12 AND try_col in ('a\'a','a\\a','b','c','d','e','f')
</code>```

Title: SQL select IN clause from array?

Body:
I have a list

$list = array('a','b','c','d','e','f');
$filter_list = join(", " $list);
select * from test where id_col=12 and try_col in ($filter_list);

Anybody could tell me how Can I do this.?

Body:
$list = array('a','b','c','d','e','f');
$filter_list = "'" . join("', '", $list) . "'";
$query = "select * from test where id=12 and try_col in ($filter_list)";
// select * from test where id=12 and try_col in ('a', 'b', 'c', 'd', 'e', 'f')

Note that this will fail if your array values contain '. Here is a workaround:

$list = array("a'a",'a\a','b','c','d','e','f');
$temp = array_map("addslashes", $list);
$query = "SELECT * FROM test WHERE id=12 AND try_col in ('" . implode("','", $temp) . "')";
// SELECT * FROM test WHERE id=12 AND try_col in ('a\'a','a\\a','b','c','d','e','f')


答:
If using react-router v6+, in your route, try this:</p>
```<code><Route path="/favourites" element={<Favourites favProduct={favProduct} />} />
</code>```

Title: Send prop with react route

Body:
I try to send a data called favProduct to Favourites component. When I send the data, I get undefined. How can I send a data when I use react route?

const [favProduct, setFavProduct] = useState([1,2,3,4,5]);

  return (
    <Router>

        <Switch>
          <Route path="/" exact component={Home}/>
          <Route path="/men" component={Men} />
          <Route path="/women" component={Women} />
          <Route path="/kids" component={Kids} />
          <Route path="/productBuy" component={ProductBuy} />
          <Route path="/favourites" component={Favourites} />
          <Route path="/cart" component={Cart} />
          <Route path="/checkout" component={Checkout} />
          <Route path="/addproduct" component={AddProduct} />
        </Switch>

    </Router>
  );
}

Body:
If using react-router v6+, in your route, try this:

<Route path="/favourites" element={<Favourites favProduct={favProduct} />} />


问:
Calculate time duration based on timestamp from previous row and new inserted row and put result into previous row
I created table in postgres with real time machine logs.
Every time when state of machine is changed new data are sending to database as below:

```<code>idx; timestamp; state
-----------------------------------------------
1;  2021-10-15 13:39:11.843; state0
2;  2021-10-15 13:40:12.857; state1
3;  2021-10-15 13:41:13.856; state2
4;  2021-10-15 13:43:17.657; state6
5;  2021-10-15 13:45:18.257; state0
6;  2021-10-14 12:32:12.857; state1
7;  2021-10-14 12:40:17.247; state6
8;  2021-10-15 09:18:19.156; state0
</code>```

I would like to add new column with state duration.
The duration will be calculated as a difference between timestamp from new row and timestamp from previous row.

```<code>idx; timestamp; state; duration
-----------------------------------------------
1;  2021-10-15 13:39:11.843; state0; (timestamp row 2 - timestamp row 1)
2;  2021-10-15 13:40:12.857; state1; (timestamp row 3 - timestamp row 2)
3;  2021-10-15 13:41:13.856; state2; (timestamp row 4 - timestamp row 3)
4;  2021-10-15 13:43:17.657; state6; (timestamp row 5 - timestamp row 4)
</code>```

I have very little experience with databases but my idea is follow:

Create function in postgres that makes above calculation (using lag()) and use triggers to place duration data every time when new data arrive.

Could anyone advise me if above make sense and if so help me with create that function?

答:
```<code>select
    t1."timestamp",
    t1.state,
    (t2."timestamp" - t1."timestamp")::interval hour to minute as "duration"
from
    (
        select "timestamp", state,
        (ROW_NUMBER () OVER (ORDER BY idx)) as rnum
        from test.tbl_status
    ) t1
inner join
    (
        select "timestamp",
        (ROW_NUMBER () OVER (ORDER BY idx)) as rnum
        from test.tbl_status
    ) t2 on t1.rnum + 1 = t2.rnum
</code>```

Result of this query:

timestamp
state
duration

2021-10-15 13:39:11.843
state0
00:01:00

2021-10-15 13:40:12.857
state1
00:01:00

2021-10-15 13:41:13.856
state2
00:02:00

2021-10-15 13:43:17.657
state6
00:02:00

2021-10-15 13:45:18.257
state0
-1 days -01:13:00

2021-10-14 12:32:12.857
state1
00:08:00

2021-10-14 12:40:17.247
state6
20:38:00

Body:
I created table in postgres with real time machine logs.
Every time when state of machine is changed new data are sending to database as below:

idx; timestamp; state
-----------------------------------------------
1;  2021-10-15 13:39:11.843; state0
2;  2021-10-15 13:40:12.857; state1
3;  2021-10-15 13:41:13.856; state2
4;  2021-10-15 13:43:17.657; state6
5;  2021-10-15 13:45:18.257; state0
6;  2021-10-14 12:32:12.857; state1
7;  2021-10-14 12:40:17.247; state6
8;  2021-10-15 09:18:19.156; state0

I would like to add new column with state duration.
The duration will be calculated as a difference between timestamp from new row and timestamp from previous row.

idx; timestamp; state; duration
-----------------------------------------------
1;  2021-10-15 13:39:11.843; state0; (timestamp row 2 - timestamp row 1)
2;  2021-10-15 13:40:12.857; state1; (timestamp row 3 - timestamp row 2)
3;  2021-10-15 13:41:13.856; state2; (timestamp row 4 - timestamp row 3)
4;  2021-10-15 13:43:17.657; state6; (timestamp row 5 - timestamp row 4)

I have very little experience with databases but my idea is follow:

Create function in postgres that makes above calculation (using lag()) and use triggers to place duration data every time when new data arrive.

Could anyone advise me if above make sense and if so help me with create that function?

Body:
select
    t1."timestamp",
    t1.state,
    (t2."timestamp" - t1."timestamp")::interval hour to minute as "duration"
from
    (
        select "timestamp", state,
        (ROW_NUMBER () OVER (ORDER BY idx)) as rnum
        from test.tbl_status
    ) t1
inner join
    (
        select "timestamp",
        (ROW_NUMBER () OVER (ORDER BY idx)) as rnum
        from test.tbl_status
    ) t2 on t1.rnum + 1 = t2.rnum

Result of this query:

timestamp
state
duration

2021-10-15 13:39:11.843
state0
00:01:00

2021-10-15 13:40:12.857
state1
00:01:00

2021-10-15 13:41:13.856
state2
00:02:00

2021-10-15 13:43:17.657
state6
00:02:00

2021-10-15 13:45:18.257
state0
-1 days -01:13:00

2021-10-14 12:32:12.857
state1
00:08:00

2021-10-14 12:40:17.247
state6
20:38:00


问:
jq: convert milliseconds to date
I need to convert seconds to date:

My input documents are:

```<code>{"_id":"ae53d3ec-8fc3-44fc-a7eb-f2f32da4eaae","birthDate":{"value":{"$date":{"$numberLong":"-469929600000"}}}}
{"_id":"ef92c3e4-d5d7-4b81-8a0b-1ab1eac10331","birthDate":{"value":{"$date":{"$numberLong":"-854755200000"}}}}
</code>```

I need to get:

```<code>{"_id":"ae53d3ec-8fc3-44fc-a7eb-f2f32da4eaae","birthDate":"1955-02-10"}
{"_id":"ef92c3e4-d5d7-4b81-8a0b-1ab1eac10331","birthDate":"1942-12-01"}
</code>```

Any ideas?

答:
```<code>.birthDate |= (
   .value."$date"."$numberLong" |
   tonumber |
   . / 1000 |
   strftime("%F")
)
</code>```

With -c, this produces the desired output exactly.

{"_id":"ae53d3ec-8fc3-44fc-a7eb-f2f32da4eaae","birthDate":"1955-02-10"}
{"_id":"ef92c3e4-d5d7-4b81-8a0b-1ab1eac10331","birthDate":"1942-12-01"}
```

Demo on jqplay

Title: jq: convert milliseconds to date

Body:
I need to convert seconds to date:

My input documents are:

{"_id":"ae53d3ec-8fc3-44fc-a7eb-f2f32da4eaae","birthDate":{"value":{"$date":{"$numberLong":"-469929600000"}}}}
{"_id":"ef92c3e4-d5d7-4b81-8a0b-1ab1eac10331","birthDate":{"value":{"$date":{"$numberLong":"-854755200000"}}}}

I need to get:

{"_id":"ae53d3ec-8fc3-44fc-a7eb-f2f32da4eaae","birthDate":"1955-02-10"}
{"_id":"ef92c3e4-d5d7-4b81-8a0b-1ab1eac10331","birthDate":"1942-12-01"}

Any ideas?

Body:
.birthDate |= (
   .value."$date"."$numberLong" |
   tonumber |
   . / 1000 |
   strftime("%F")
)

With -c, this produces the desired output exactly.

{"_id":"ae53d3ec-8fc3-44fc-a7eb-f2f32da4eaae","birthDate":"1955-02-10"}
{"_id":"ef92c3e4-d5d7-4b81-8a0b-1ab1eac10331","birthDate":"1942-12-01"}

Demo on jqplay


问:
How to calculate an equation using eval-parse in R?
How do I calculate the value of an equation using eval parse in R? The value for each component of the equation should be taken from the eponymously named columns within the same row e.g. 'alpha' from column 'alpha' and so on.

Dataframe:

```<code>dput(<alpha beta    gamma   delta   epsilon zeta    eta theta   RF  min.speed.kph   max.speed.kph   speed   equation
9.70E-05    0.0026  1.432   0   0   0   0   0   0   10  130 30  ((alpha*speed^2)+(beta*speed)+gamma+(delta*log10(speed))+(epsilon*exp(zeta*speed))+(eta*(speed^theta)))*(1-RF)
7.40E-05    0.013   1.484   0   0   0   0   0   0   10  130 30  ((alpha*speed^2)+(beta*speed)+gamma+(delta*log10(speed))+(epsilon*exp(zeta*speed))+(eta*(speed^theta)))*(1-RF)
0.000266    -0.014  2.427   0   0   0   0   0   0   10  130 30  ((alpha*speed^2)+(beta*speed)+gamma+(delta*log10(speed))+(epsilon*exp(zeta*speed))+(eta*(speed^theta)))*(1-RF)
2.88E-12    2.56E-10    -2.09E-07   7.75E-05    -0.005274381    0.152658622 0   0.88    NA  10  140 30  ((alpha*speed^5)+beta*speed^4+gamma*speed^3+delta*speed^2+epsilon*speed+zeta)*(theta)
2.88E-12    2.56E-10    -2.09E-07   7.75E-05    -0.005274381    0.152658622 0   0.6 NA  10  140 30  ((alpha*speed^5)+beta*speed^4+gamma*speed^3+delta*speed^2+epsilon*speed+zeta)*(theta)
0.524738843 0   -0.01   0   9.36E-05    0   0   0   0   5   130 30  ((alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2))*(1-RF)
0.283553945 -0.0234 -0.00869    0.000443    0.000114    0   0   0   0   5   130 30  ((alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2))*(1-RF)
0.189162424 1.571506423 0.081547506 0.027327758 -0.000248892    -0.268467236    0   0   0   5   130 30  (alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2)
0.474232144 5.621746462 0.340577763 0.083762882 -0.001515827    -1.191086695    0   0   0   5   130 30  (alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2)
0.189162424 1.571506423 0.081547506 0.027327758 -0.000248892    -0.268467236    0   0   0   5   130 30  (alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2)
>)
</code>```

I have tried this but it's not working:

nox.file$calculated_col <- eval(parse(text=as.character(nox.file$equation)), nox.file)

I have also tried wrapping it in 'mutate' to help with vectorising it but neither does this work:

nox.file <- nox.file %>% mutate(calculated_col=eval(parse(text=as.character(equation)), nox.file))

Can anyone tell me what's wrong?

答:
The problem with your attempt is that eval is not vectorized. It only evaluates the last element of the expression vector parse(text = equation). You can try something like this instead:

library("dplyr")

dd <- nox.file %>%
    group_by(equation) %>%
    ## mutate(calculated_col = eval(str2lang(cur_group()[[1L]])))
    mutate(calculated_col = tryCatch(eval(str2lang(cur_group()[[1L]])), error = function(e) NA_real_))

dd$calculated_col
## [1] 1.59730000 1.94060000 2.24640000 0.05175415 0.03528692
## [6] 0.30897884 0.18006882 0.03303038 0.03790261 0.03303038
```
<p>I reconstructed <code>nox.file</code> from your copy and paste like so:</p>
<pre class="lang-r prettyprint-override"><code>x <- "alpha beta    gamma   delta   epsilon zeta    eta theta   RF  min.speed.kph   max.speed.kph   speed   equation
9.70E-05    0.0026  1.432   0   0   0   0   0   0   10  130 30  ((alpha*speed^2)+(beta*speed)+gamma+(delta*log10(speed))+(epsilon*exp(zeta*speed))+(eta*(speed^theta)))*(1-RF)
7.40E-05    0.013   1.484   0   0   0   0   0   0   10  130 30  ((alpha*speed^2)+(beta*speed)+gamma+(delta*log10(speed))+(epsilon*exp(zeta*speed))+(eta*(speed^theta)))*(1-RF)
0.000266    -0.014  2.427   0   0   0   0   0   0   10  130 30  ((alpha*speed^2)+(beta*speed)+gamma+(delta*log10(speed))+(epsilon*exp(zeta*speed))+(eta*(speed^theta)))*(1-RF)
2.88E-12    2.56E-10    -2.09E-07   7.75E-05    -0.005274381    0.152658622 0   0.88    NA  10  140 30  ((alpha*speed^5)+beta*speed^4+gamma*speed^3+delta*speed^2+epsilon*speed+zeta)*(theta)
2.88E-12    2.56E-10    -2.09E-07   7.75E-05    -0.005274381    0.152658622 0   0.6 NA  10  140 30  ((alpha*speed^5)+beta*speed^4+gamma*speed^3+delta*speed^2+epsilon*speed+zeta)*(theta)
0.524738843 0   -0.01   0   9.36E-05    0   0   0   0   5   130 30  ((alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2))*(1-RF)
0.283553945 -0.0234 -0.00869    0.000443    0.000114    0   0   0   0   5   130 30  ((alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2))*(1-RF)
0.189162424 1.571506423 0.081547506 0.027327758 -0.000248892    -0.268467236    0   0   0   5   130 30  (alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2)
0.474232144 5.621746462 0.340577763 0.083762882 -0.001515827    -1.191086695    0   0   0   5   130 30  (alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2)
0.189162424 1.571506423 0.081547506 0.027327758 -0.000248892    -0.268467236    0   0   0   5   130 30  (alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2)"

con <- textConnection(x)
nox.file <- read.table(con, header = TRUE)
close(con)
</code>```

The reconstruction may not be exact, which is why you are encouraged to include proper dput output in your question.

Body:
How do I calculate the value of an equation using eval parse in R? The value for each component of the equation should be taken from the eponymously named columns within the same row e.g. 'alpha' from column 'alpha' and so on.

Dataframe:

dput(<alpha beta    gamma   delta   epsilon zeta    eta theta   RF  min.speed.kph   max.speed.kph   speed   equation
9.70E-05    0.0026  1.432   0   0   0   0   0   0   10  130 30  ((alpha*speed^2)+(beta*speed)+gamma+(delta*log10(speed))+(epsilon*exp(zeta*speed))+(eta*(speed^theta)))*(1-RF)
7.40E-05    0.013   1.484   0   0   0   0   0   0   10  130 30  ((alpha*speed^2)+(beta*speed)+gamma+(delta*log10(speed))+(epsilon*exp(zeta*speed))+(eta*(speed^theta)))*(1-RF)
0.000266    -0.014  2.427   0   0   0   0   0   0   10  130 30  ((alpha*speed^2)+(beta*speed)+gamma+(delta*log10(speed))+(epsilon*exp(zeta*speed))+(eta*(speed^theta)))*(1-RF)
2.88E-12    2.56E-10    -2.09E-07   7.75E-05    -0.005274381    0.152658622 0   0.88    NA  10  140 30  ((alpha*speed^5)+beta*speed^4+gamma*speed^3+delta*speed^2+epsilon*speed+zeta)*(theta)
2.88E-12    2.56E-10    -2.09E-07   7.75E-05    -0.005274381    0.152658622 0   0.6 NA  10  140 30  ((alpha*speed^5)+beta*speed^4+gamma*speed^3+delta*speed^2+epsilon*speed+zeta)*(theta)
0.524738843 0   -0.01   0   9.36E-05    0   0   0   0   5   130 30  ((alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2))*(1-RF)
0.283553945 -0.0234 -0.00869    0.000443    0.000114    0   0   0   0   5   130 30  ((alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2))*(1-RF)
0.189162424 1.571506423 0.081547506 0.027327758 -0.000248892    -0.268467236    0   0   0   5   130 30  (alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2)
0.474232144 5.621746462 0.340577763 0.083762882 -0.001515827    -1.191086695    0   0   0   5   130 30  (alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2)
0.189162424 1.571506423 0.081547506 0.027327758 -0.000248892    -0.268467236    0   0   0   5   130 30  (alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2)
>)

I have tried this but it's not working:

nox.file$calculated_col <- eval(parse(text=as.character(nox.file$equation)), nox.file)

I have also tried wrapping it in 'mutate' to help with vectorising it but neither does this work:

nox.file <- nox.file %>% mutate(calculated_col=eval(parse(text=as.character(equation)), nox.file))

Can anyone tell me what's wrong?

Body:
The problem with your attempt is that eval is not vectorized. It only evaluates the last element of the expression vector parse(text = equation). You can try something like this instead:

library("dplyr")

dd <- nox.file %>%
    group_by(equation) %>%
    ## mutate(calculated_col = eval(str2lang(cur_group()[[1L]])))
    mutate(calculated_col = tryCatch(eval(str2lang(cur_group()[[1L]])), error = function(e) NA_real_))

dd$calculated_col
## [1] 1.59730000 1.94060000 2.24640000 0.05175415 0.03528692
## [6] 0.30897884 0.18006882 0.03303038 0.03790261 0.03303038

I reconstructed nox.file from your copy and paste like so:

x <- "alpha beta    gamma   delta   epsilon zeta    eta theta   RF  min.speed.kph   max.speed.kph   speed   equation
9.70E-05    0.0026  1.432   0   0   0   0   0   0   10  130 30  ((alpha*speed^2)+(beta*speed)+gamma+(delta*log10(speed))+(epsilon*exp(zeta*speed))+(eta*(speed^theta)))*(1-RF)
7.40E-05    0.013   1.484   0   0   0   0   0   0   10  130 30  ((alpha*speed^2)+(beta*speed)+gamma+(delta*log10(speed))+(epsilon*exp(zeta*speed))+(eta*(speed^theta)))*(1-RF)
0.000266    -0.014  2.427   0   0   0   0   0   0   10  130 30  ((alpha*speed^2)+(beta*speed)+gamma+(delta*log10(speed))+(epsilon*exp(zeta*speed))+(eta*(speed^theta)))*(1-RF)
2.88E-12    2.56E-10    -2.09E-07   7.75E-05    -0.005274381    0.152658622 0   0.88    NA  10  140 30  ((alpha*speed^5)+beta*speed^4+gamma*speed^3+delta*speed^2+epsilon*speed+zeta)*(theta)
2.88E-12    2.56E-10    -2.09E-07   7.75E-05    -0.005274381    0.152658622 0   0.6 NA  10  140 30  ((alpha*speed^5)+beta*speed^4+gamma*speed^3+delta*speed^2+epsilon*speed+zeta)*(theta)
0.524738843 0   -0.01   0   9.36E-05    0   0   0   0   5   130 30  ((alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2))*(1-RF)
0.283553945 -0.0234 -0.00869    0.000443    0.000114    0   0   0   0   5   130 30  ((alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2))*(1-RF)
0.189162424 1.571506423 0.081547506 0.027327758 -0.000248892    -0.268467236    0   0   0   5   130 30  (alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2)
0.474232144 5.621746462 0.340577763 0.083762882 -0.001515827    -1.191086695    0   0   0   5   130 30  (alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2)
0.189162424 1.571506423 0.081547506 0.027327758 -0.000248892    -0.268467236    0   0   0   5   130 30  (alpha+gamma*speed+epsilon*speed^2+zeta/speed)/(1+beta*speed+delta*speed^2)"

con <- textConnection(x)
nox.file <- read.table(con, header = TRUE)
close(con)

The reconstruction may not be exact, which is why you are encouraged to include proper dput output in your question.


问:
SQL arithmetic does not return same answer when I multiply
I'm doing a free course on DataCamp and I am at the aggregating function section.
It is asking me to get the percentage of people who are no longer alive.

```<code>SELECT
  COUNT(deathdate) * 100.0 / COUNT(*)
FROM people
</code>```

Returns 9.37

```<code>SELECT
  COUNT(deathdate) / COUNT(*) * 100.0
FROM people
</code>```

Returns 0.0

The right answer is the first code, but why doesn't the second code return the same as the first? Why can't I multiply by 100.0 after I divide?

答:
In the first example, COUNT(deathdate) * 100.0 is performed first and since it includes a number with a decimal, the result is a double-precision/float value. Then the divide by COUNT(*) can give you a result with decimal places.

In the second example, COUNT(deathdate) / COUNT(*) uses two integer values which causes the fraction to be lost resulting in zero. Then, zero * 100.0 is zero.

Body:
I'm doing a free course on DataCamp and I am at the aggregating function section.
It is asking me to get the percentage of people who are no longer alive.

SELECT
  COUNT(deathdate) * 100.0 / COUNT(*)
FROM people

Returns 9.37

SELECT
  COUNT(deathdate) / COUNT(*) * 100.0
FROM people

Returns 0.0

The right answer is the first code, but why doesn't the second code return the same as the first? Why can't I multiply by 100.0 after I divide?


问:
Writing a function that returns true if given string has exactly 6 characters
I am trying to write a function that returns true or false if a given string has exactly  6 consecutive characters with the same value. If the string has more or less than 6, it will return false:

I am not allowed to use lists, sets or import any packages. I am only restricted to while loops, for loops, and utilizing basic mathematical operations

Two example runs are shown below:

```<code>Enter a string: 367777776
True
</code>```
```<code>Enter a string: 3677777777776
False
</code>```

Note that although I entered numbers, it is actually a string within the function argument for example: consecutive('3777776')

I tried to convert the string into an ASCII table and then try and filter out the numbers there. However, I

```<code>def consecutive(x):
    storage= ' '
    acc=0
    count=0
    for s in x:
        storage+= str(ord(s)) + ' '
        acc+=ord(s)
        if acc == acc:
            count+=1
    for s in x-1:

    return count

</code>```

My intention is to compare the previous character's ASCII code  to the current character's ASCII code in the string. If the ASCII doesnt match, I will add an accumulator for it. The accumulator will list the number of duplicates. From there, I will implement an if-else statement to see if it is greater or less than 6 However, I have a hard time translating my thoughts into python code.

Can anyone assist me?

答:
would something like this be allowed?

def consecF(n):
    consec = 1
    prev = n[0]
    for i in n:
        if i==prev:
            consec+=1
        else:
            consec=1
        if consec == 6:
            return True
        prev = i

    return False
n = "12111123333221"
print(consecF(n))
```

Body:
I am trying to write a function that returns true or false if a given string has exactly  6 consecutive characters with the same value. If the string has more or less than 6, it will return false:

I am not allowed to use lists, sets or import any packages. I am only restricted to while loops, for loops, and utilizing basic mathematical operations

Two example runs are shown below:

Enter a string: 367777776
True

Enter a string: 3677777777776
False

Note that although I entered numbers, it is actually a string within the function argument for example: consecutive('3777776')

I tried to convert the string into an ASCII table and then try and filter out the numbers there. However, I

def consecutive(x):
    storage= ' '
    acc=0
    count=0
    for s in x:
        storage+= str(ord(s)) + ' '
        acc+=ord(s)
        if acc == acc:
            count+=1
    for s in x-1:

    return count

My intention is to compare the previous character's ASCII code  to the current character's ASCII code in the string. If the ASCII doesnt match, I will add an accumulator for it. The accumulator will list the number of duplicates. From there, I will implement an if-else statement to see if it is greater or less than 6 However, I have a hard time translating my thoughts into python code.

Can anyone assist me?


问:
How to get actual width/height of some element after loading whose width/height originally set by PERCENTAGE?
I have an iframe, whose content points to an HTML document.

In that HTML document, there's an EMBED element pointing to a PDF document. This EMBED originally set up with width and height in PERCENTAGE (such as: width: 100%; height: 100%).

My question is:

After the iframe has been loaded, how can I retrieve the actual, absolute width and height (in any unit px, pt, em etc.) of the EMBED element.

I've been trying on all possible js properties (width, height, style: clientWidth, clientHeight, offsetWidth, offsetHeight...) and in jQuery as well (such as outerWidth, outerHeight etc.) but it seems hopeless.

答:
http://jsfiddle.net/purmou/9XXwf/2/

This uses jQuery's width() and height(). Currently it finds the total width/height of an object, including padding, border, margins, etc. If you'd like to find the width and height of the element itself, excluding the the borders, etc., replace var width = this.offsetWidth; with var width = $(this).width(); and var height = this.offsetHeight; with var height = $(this).height();.


问:
What is the advantage of a single-function-class over a function?
I have often encountered classes with the following structure:

```<code>class FooAlgorithm {
  public:
    FooAlgorithm(A a, B b);
    void run();
  private:
    A _a;
    B _b;
};
</code>```

So classes with only one public member function that are also only run once.
Is there any advantage in any case over a single free function foo(A a, B b)?
The latter option is easier to call, potentially has less header dependencies and also has  much less boilerplate in the header.

答:
For bigger projects it may be easier to structure your programm using OOP.
For a simple program like yours it is easier to use a single function.</p>

Body:
I have often encountered classes with the following structure:

class FooAlgorithm {
  public:
    FooAlgorithm(A a, B b);
    void run();
  private:
    A _a;
    B _b;
};

So classes with only one public member function that are also only run once.
Is there any advantage in any case over a single free function foo(A a, B b)?
The latter option is easier to call, potentially has less header dependencies and also has  much less boilerplate in the header.


问:
Cannot stop real time stream of paramiko exec_command()
I am using the following python code to get a continuous log from a linux server:

```<code>ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.168.1', 22, username="root", password="", timeout=5)
stdin, stdout, stderror = ssh.exec_command('journalctl -f', get_pty=True)
for log in iter(stdout.readline, ""):
    print(log, end="")
</code>```

I would like to break this feed by any key press, but once this is running, there is no other way to stop it other than exiting the program.

Any ideas would be greatly appreciated.

答:
To close only the process, use Channel.close():

```<code>stdin.channel.close()
</code>```

Or you can close whole connection:

```<code>ssh.close()
</code>```

Body:
I am using the following python code to get a continuous log from a linux server:

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.168.1', 22, username="root", password="", timeout=5)
stdin, stdout, stderror = ssh.exec_command('journalctl -f', get_pty=True)
for log in iter(stdout.readline, ""):
    print(log, end="")

I would like to break this feed by any key press, but once this is running, there is no other way to stop it other than exiting the program.

Any ideas would be greatly appreciated.

Body:
To close only the process, use Channel.close():

stdin.channel.close()

Or you can close whole connection:

ssh.close()