问:
Can't convert to Lower/uppercase a char* pointer using a loop in C without toupper
I am trying to make a function toLowerCase(char *string) but I am unable to make it work properly.

This is my code

```<code>void toLowerCase(char *string) {
    int i = 0;
    while (*(string+i) != '\0') {
        if (*(string+i) >= 'A' && *(string+i) <= 'Z') {
            *(string+i) = *(string+i) + 32;
        }
        i++;
    }
    printf("%s", string);
}
</code>```

I am trying to loop through the string that is a char * pointer by accessing each element using *(string + i) and using ASCII to convert to Lowercase.

I am new here, if this was answered before I am sorry, but I am asking because I couldn't find a specific solution to my problem. I've tried what's in this thread: Converting Char * to Uppercase in C
but it didn't work for me either.

EDIT: This is how I call my function

```<code>int main() {
    toLowerCase("HELLO WORLD");
    return 0;
}
</code>```

EDIT 2: So, I did this, as showed by PSkocik. And it worked, but I don't know why it works like this. Will the toLowerCase() function work with any char * pointer? even if I don't declare it as char array?

This also fixes the problem that Vlad from Moscow pointed out that I am using a string literal

```<code>#define T 100
int main() {
    char string[T] = "HELLO WORLD";
    toLowerCase(&string);
    return 0;
}
</code>```

EDIT 3: Thank you very much for your help! I wasn't expecting to get help so quickly! I didn't know what a string literal was!

Thank you very much for your time

答:
C string literals are typed char[] for historical reasons, but they're effectively char const[]—you are not allowed to modify them.

Fortunately C makes it very easy to create a writable copy by letting you initialize a writable char array with a string literal:

```<code>#include <stdio.h>
void toLowerCase(char* string)
{
    int i=0;
    while(*(string+i)!= '\0'){
        if (*(string+i) >= 'A' && *(string+i)<='Z'){
            *(string+i)= *(string+i)+32;
        }
        i++;
    }
}
int main()
{
     char string[]="HELLO WORLD";
     toLowerCase(&string[0]);
     puts(string);
    //prints: hello world
}
</code>```

https://gcc.godbolt.org/z/X4YA5B

(*(string+i) instead of string[i] is slightly unusual and I'd at least replace the magic constant 32 with ('a'-'A'), but the callee's code is otherwise OK.)

Body:
I am trying to make a function toLowerCase(char *string) but I am unable to make it work properly.

This is my code

void toLowerCase(char *string) {
    int i = 0;
    while (*(string+i) != '\0') {
        if (*(string+i) >= 'A' && *(string+i) <= 'Z') {
            *(string+i) = *(string+i) + 32;
        }
        i++;
    }
    printf("%s", string);
}

I am trying to loop through the string that is a char * pointer by accessing each element using *(string + i) and using ASCII to convert to Lowercase.

I am new here, if this was answered before I am sorry, but I am asking because I couldn't find a specific solution to my problem. I've tried what's in this thread: Converting Char * to Uppercase in C
but it didn't work for me either.

EDIT: This is how I call my function

int main() {
    toLowerCase("HELLO WORLD");
    return 0;
}

EDIT 2: So, I did this, as showed by PSkocik. And it worked, but I don't know why it works like this. Will the toLowerCase() function work with any char * pointer? even if I don't declare it as char array?

This also fixes the problem that Vlad from Moscow pointed out that I am using a string literal

#define T 100
int main() {
    char string[T] = "HELLO WORLD";
    toLowerCase(&string);
    return 0;
}

EDIT 3: Thank you very much for your help! I wasn't expecting to get help so quickly! I didn't know what a string literal was!

Thank you very much for your time

Body:
C string literals are typed char[] for historical reasons, but they're effectively char const[]—you are not allowed to modify them.

Fortunately C makes it very easy to create a writable copy by letting you initialize a writable char array with a string literal:

#include <stdio.h>
void toLowerCase(char* string)
{
    int i=0;
    while(*(string+i)!= '\0'){
        if (*(string+i) >= 'A' && *(string+i)<='Z'){
            *(string+i)= *(string+i)+32;
        }
        i++;
    }
}
int main()
{
     char string[]="HELLO WORLD";
     toLowerCase(&string[0]);
     puts(string);
    //prints: hello world
}

https://gcc.godbolt.org/z/X4YA5B

(*(string+i) instead of string[i] is slightly unusual and I'd at least replace the magic constant 32 with ('a'-'A'), but the callee's code is otherwise OK.)


来源: stackexchange

问:
Whats the Difference between (As) and (=) in object declaration in VB.NET
I can create a new object like this:

```<code>Dim sqlconn As New SqlClient.SqlConnection(cs)
</code>```

or like this:

```<code>Dim sqlconn = New SqlClient.SqlConnection(cs)
</code>```

What's the difference? Since both worked fine for me!

答:
The first one is the short form of:

```<code>Dim sqlconn As SqlClient.SqlConnection = New SqlClient.SqlConnection(cs)
</code>```

The second one depends on what version of VB you are using. In VB 7 and VB 8 it is the same as:

```<code>Dim sqlconn As Object = New SqlClient.SqlConnection(cs)
</code>```

In VB 9 type inference was introduced, so the compiler will infer the type from the assignment and produce the same code as the first one.

The type inference requires that the option Option Infer is set to on. This is the default setting, but it might be off if you migrate a project from an older version.

ContentLicense: CC BY-SA 3.0

Body:
I can create a new object like this:

Dim sqlconn As New SqlClient.SqlConnection(cs)

or like this:

Dim sqlconn = New SqlClient.SqlConnection(cs)

What's the difference? Since both worked fine for me!

Body:
The first one is the short form of:

Dim sqlconn As SqlClient.SqlConnection = New SqlClient.SqlConnection(cs)

The second one depends on what version of VB you are using. In VB 7 and VB 8 it is the same as:

Dim sqlconn As Object = New SqlClient.SqlConnection(cs)

In VB 9 type inference was introduced, so the compiler will infer the type from the assignment and produce the same code as the first one.

The type inference requires that the option Option Infer is set to on. This is the default setting, but it might be off if you migrate a project from an older version.


问:
Removing [ts] errors from JS files In VS Code
I get these TypeScript errors VS Code while I'm working in JS files. Is there anything I can do to disable this? I have put this in my settings and did not solve the issue:

```<code>"typescript.validate.enable": false
</code>```

The error can been seen here

答:
This works for me

On Windows- File > Preferences > Settings

make sure validate is not enable

ContentLicense: CC BY-SA 4.0

Body:
I get these TypeScript errors VS Code while I'm working in JS files. Is there anything I can do to disable this? I have put this in my settings and did not solve the issue:

"typescript.validate.enable": false

The error can been seen here


问:
Stored Procedures that creates a table
Can I create tables using Stored Procedures?

I am using MySQL. I had searched the web for instructions on how to create a table using stored procedure, but I didn't find any results, I just found that you can create temporary tables. Is there any problem if I create tables using stored procedures?

Actually I want to check whether a table exists or not, then I have to create it.

答:
EDIT: Thanks Peter! So the solution to this particular problem:

```<code>DELIMITER //
CREATE PROCEDURE createTable(IN tableName VARCHAR(40))
BEGIN
SET @table := tableName;
SET @sql_text:=CONCAT('CREATE TABLE ',@table,'(id INT NOT NULL AUTO_INCREMENT, FILENAME VARCHAR(40) NOT NULL, DATA BLOB NOT NULL, PRIMARY KEY (ID))');

PREPARE stmt from @sql_text;
EXECUTE stmt;
END //
DELIMITER ;
</code>```

In addition to the manual I also found a very helpful tut by Roland Bouman at:

http://rpbouman.blogspot.com/2005/11/mysql-5-prepared-statement-syntax-and.htmlenter code here

El autor de la respuesta: Conrad Ljungström

link de la respuesta original: https://forums.mysql.com/read.php?98,495352

Title: Stored Procedures that creates a table

Body:
EDIT: Thanks Peter! So the solution to this particular problem:

DELIMITER //
CREATE PROCEDURE createTable(IN tableName VARCHAR(40))
BEGIN
SET @table := tableName;
SET @sql_text:=CONCAT('CREATE TABLE ',@table,'(id INT NOT NULL AUTO_INCREMENT, FILENAME VARCHAR(40) NOT NULL, DATA BLOB NOT NULL, PRIMARY KEY (ID))');

PREPARE stmt from @sql_text;
EXECUTE stmt;
END //
DELIMITER ;

In addition to the manual I also found a very helpful tut by Roland Bouman at:

http://rpbouman.blogspot.com/2005/11/mysql-5-prepared-statement-syntax-and.htmlenter code here

El autor de la respuesta: Conrad Ljungström

link de la respuesta original: https://forums.mysql.com/read.php?98,495352


问:
How can I kill a process when I close the bash terminal?
I have found many ways to keep a process running in the background after a bash terminal is closed. However, how can I do the opposite? How can I kill a background process when my terminal is closed?

Currently, when I close the terminal, I get "Processes are running in session... Close anyway?" and if I hit OK, the terminal closes, but the processes are not killed and linger around. Can I hook the suppression of these processes with the "death" of the terminal process?

Easy example: run ssh-agent bash and then try to close the terminal.

答:
Put this in your .bashrc:

```<code>trap 'kill $(ps -o pid= --ppid $$) 2>/dev/null' exit
</code>```

This command will make the shell kill all its child processes when you exit.

Explanation:

The trap command catches signals and other events and lets you execute commands, that run when the signal is catched or the event has happened.

```<code>trap [-lp] [[arg] signal_spec ...]
</code>```

ARG is a command to be read and executed when the shell receives the signal(s) SIGNAL_SPEC. If a SIGNAL_SPEC is EXIT, ARG is executed on exit from the shell.

The kill command sends a signal to the job(s) of PID(s) supplied as arguments.

```<code>kill [-s sigspec | -n signum | -sigspec] pid ...
</code>```

If neither SIGSPEC nor SIGNUM is present, then SIGTERM (termination signal) is assumed.

The ps command displays information about processes.

-o format
    User defined format of output.
--ppid pidlist
    Select which processes to show by PID of their parent process. Selects processes
    that are children of those listed in PIDLIST.
```

Finally, $$ in shell expands to the process id of the shell. In a $(...) subshell, it expands to the process ID of the current shell, not the subshell.

And 2>/dev/null is used to discard potential error output of the kill command which can be caused by processes that no longer exist when the kill command is executed, but existed while the ps command was executed - which is typically the subshell $(...).

Body:
Put this in your .bashrc:

trap 'kill $(ps -o pid= --ppid $$) 2>/dev/null' exit

This command will make the shell kill all its child processes when you exit.

Explanation:

The trap command catches signals and other events and lets you execute commands, that run when the signal is catched or the event has happened.

trap [-lp] [[arg] signal_spec ...]

ARG is a command to be read and executed when the shell receives the signal(s) SIGNAL_SPEC. If a SIGNAL_SPEC is EXIT, ARG is executed on exit from the shell.

The kill command sends a signal to the job(s) of PID(s) supplied as arguments.

kill [-s sigspec | -n signum | -sigspec] pid ...

If neither SIGSPEC nor SIGNUM is present, then SIGTERM (termination signal) is assumed.

The ps command displays information about processes.

-o format
    User defined format of output.
--ppid pidlist
    Select which processes to show by PID of their parent process. Selects processes
    that are children of those listed in PIDLIST.

Finally, $$ in shell expands to the process id of the shell. In a $(...) subshell, it expands to the process ID of the current shell, not the subshell.

And 2>/dev/null is used to discard potential error output of the kill command which can be caused by processes that no longer exist when the kill command is executed, but existed while the ps command was executed - which is typically the subshell $(...).


问:
Embeded interface : struct doesn't implement method
I don't understand why interface composition doesn't " inherit"  the methods from the parent interface when it is satisfied in the implementation.

```<code>package main

import (
    "fmt"
)

type TestRepository interface {
    FindById(int) (error)
}

type TestService interface {
    TestRepository
    Method(id int) error
}

type testService struct {
    implRepository TestRepository
}

func NewTestService(r TestRepository) TestService {
    return &testService{implRepository: r}
}
</code>```

When compiling this code i'm getting : *testService does not implement TestService (missing FindById method) while i'm actually expecting it to implement it since the type of "implRepository" is TestRepository.

It works if i do :

```<code>func NewTestService(r TestRepository) *testService {
    return &testService{implRepository: r}
}
</code>```

But it kind of defeat the purpose of the interface ( as far as the service one goes at least )

What am i missing / how should it be done ?

答:
The answer to your question is simply "you aren't composing the interface the way you need to." You have made TestRepository a struct member - that is not going to "inherit" the methods on that interface. What you need is the following:

```<code>type testService struct {
    TestRepository
}

func NewTestService(r TestRepository) TestService {
    return &testService{TestRepository: r}
}
</code>```

Of course, the struct testService still need to implement Method(id int) error to actually work.

Body:
I don't understand why interface composition doesn't " inherit"  the methods from the parent interface when it is satisfied in the implementation.

package main

import (
    "fmt"
)

type TestRepository interface {
    FindById(int) (error)
}

type TestService interface {
    TestRepository
    Method(id int) error
}

type testService struct {
    implRepository TestRepository
}

func NewTestService(r TestRepository) TestService {
    return &testService{implRepository: r}
}

When compiling this code i'm getting : *testService does not implement TestService (missing FindById method) while i'm actually expecting it to implement it since the type of "implRepository" is TestRepository.

It works if i do :

func NewTestService(r TestRepository) *testService {
    return &testService{implRepository: r}
}

But it kind of defeat the purpose of the interface ( as far as the service one goes at least )

What am i missing / how should it be done ?

Body:
The answer to your question is simply "you aren't composing the interface the way you need to." You have made TestRepository a struct member - that is not going to "inherit" the methods on that interface. What you need is the following:

type testService struct {
    TestRepository
}

func NewTestService(r TestRepository) TestService {
    return &testService{TestRepository: r}
}

Of course, the struct testService still need to implement Method(id int) error to actually work.


问:
Android button setBackgroundColor change the size of the button
I create android button programmatically, and I put this butons in a TableRow, every thing work fine, but when I change the backgroudColor the colored button not respect the size as it do without the color:

My code is:

```<code>val btn = Button(this)
btn.isEnabled = false
btn.setBackgroundColor(Color.RED)
btn.layoutParams = TableRow.LayoutParams(150, 150)
</code>```

When I don't use the setBackgroundColor the size is correct.

I don't understand why the size is changes, is there any way to change only the default gray color of the button, without the size is changes.

答:
The default background for a button is not a solid color, but is rather a graphic (e.g. a nine-patch bitmap) that has paddings and margins built into it. Thus, when you replace that background image with a color, all of the built-in paddings and margins are thrown away.

Instead of setting a background color with setBackgroundColor() you could try using setBackgroundTintList() which should tint the existing background image with your chosen color(s).

Alternatively, you would need to manually set the margins and paddings after changing the background to the solid red color, something that is much more painful to do via code than it is in a layout XML file.

Example layout file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Red Button"
        android:backgroundTint="#a00"
        android:textColor="#fff" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Default Button" />

</LinearLayout>
```

Which yields this rendering:

Body:
I create android button programmatically, and I put this butons in a TableRow, every thing work fine, but when I change the backgroudColor the colored button not respect the size as it do without the color:

My code is:

val btn = Button(this)
btn.isEnabled = false
btn.setBackgroundColor(Color.RED)
btn.layoutParams = TableRow.LayoutParams(150, 150)

When I don't use the setBackgroundColor the size is correct.

I don't understand why the size is changes, is there any way to change only the default gray color of the button, without the size is changes.

Body:
The default background for a button is not a solid color, but is rather a graphic (e.g. a nine-patch bitmap) that has paddings and margins built into it. Thus, when you replace that background image with a color, all of the built-in paddings and margins are thrown away.

Instead of setting a background color with setBackgroundColor() you could try using setBackgroundTintList() which should tint the existing background image with your chosen color(s).

Alternatively, you would need to manually set the margins and paddings after changing the background to the solid red color, something that is much more painful to do via code than it is in a layout XML file.

Example layout file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Red Button"
        android:backgroundTint="#a00"
        android:textColor="#fff" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Default Button" />

</LinearLayout>

Which yields this rendering:


问:
What is best way to updating tree Panel
I would like know , what is the best way to sync/load tree panel after updating database.
Today, i do an Ajax Request to make an updates. If the response is successful i use method load of my treeStore.

```<code>myTreePanel.getStore.load();
</code>```

But this technic waste times . Maybe is not the best technic to do this ?!

Thanks :)

答:
if user updates a node & you commit changes to server/database you don't need to reload tree, just update that node node.setText('BlahBlah') but if it's more than one node or updates are comming from server & current user hasn't changed them (tree changes by other users & current user just sees changes) i would update UI with comming changes via websocket & if websockets wasn't possible i would fetch changes by doing ajax request every 20-30 seconds or so.

the thing i'm trying to say is it's better to change a small set of UI because it has better performance & DOM won't change so much, also you don't have to fetch all nodes, even those have not changed.

Title: What is best way to updating tree Panel

Body:
I would like know , what is the best way to sync/load tree panel after updating database.
Today, i do an Ajax Request to make an updates. If the response is successful i use method load of my treeStore.

myTreePanel.getStore.load();

But this technic waste times . Maybe is not the best technic to do this ?!

Thanks :)


问:
How to pull integer from mySQL database and display in HTML document
I am trying to write a website that can display information from a mySQL database using PHP.

I have set up the database connection, I believe it is doing the query but it is not displaying the query. It stops displaying data after the first variable is echoed in the code.

I attempted the query directly in mySQL and it gave me the response I wanted.

Here is the code for the HTML document:

EDIT: The value I am trying to display is an integer.

```<code><!DOCTYPE html>
<html>
    <head>
        <!-- Start Link Stylesheet -->
        <link rel="stylesheet" type="text/css" href="style.css" />
        <!-- End Link Stylesheet-->

        <!-- Start Meta Tags -->
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta charset="utf-8">
        <meta author="Cole K. Motuliak">
        <!-- End Meta Tags -->

        <title>sumstats - view stats</title>
    </head>

    <body>
        <header>
            <h1 class="center" id="bigger">JHS IT Summer Statistics Viewpage</h1>
        </header>
            <h1 class="center">Welcome</h1>
            <div class="center">
                <?php
                include 'view_stats.php';
                ?>

        </div>

        <footer>
            <p class="center">© 2020 Cole K. Motuliak | <a href="mailto:cmotuliak3@gmail.com">cmotuliak3@gmail.com</a></p>
        </footer>
    </body>

</html>
</code>```

Here is the PHP code

```<code><?php
                $servername = "localhost:3306"; // Define Server Domain Name / TCP port
                $username = "sumstats_viewonly"; // Define username
                $password = "*****"; // Define password, PASSWORD CHANGED FROM SCRIPT
                $dbname = "sumstats_db"; // Define database name

                // Create connection
                $conn = new mysqli($servername, $username, $password, $dbname);
                // Check connection
                if ($conn->connect_error) {
                    die("Connection failed: " . $conn->connect_error);
                }
                $imaged_query = "SELECT imaged FROM sumstats_table";
                $tagged_query = "SELECT tagged FROM sumstats_table";
                $unboxed_query = "SELECT unboxed FROM sumstats_table";
                $imaged_int = $conn->query($imaged_query);
                $tagged_int = $conn->query($tagged_query);
                $unboxed_int = $conn->query($unboxed_query);
                echo "<p >Imaged Count:", $imaged_int, "EndTest</p>";
                echo "<p >Tagged Count:", $tagged_int, "EndTest</p>";
                echo "<p >Unboxed Count:", $unboxed_int, "EndTest</p>";
                $conn->close();

                ?>
</code>```

If anybody could assist and tell me what I am doing wrong, please let me know. Thanks!

答:
You can use this as your view_stats.php

It makes less database query and allows looping

```<code><?php
$servername = "localhost:3306"; // Define Server Domain Name / TCP port
$username = "sumstats_viewonly"; // Define username
$password = "*****"; // Define password, PASSWORD CHANGED FROM SCRIPT
$dbname = "sumstats_db"; // Define database name

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = $conn->query("SELECT imaged,tagged,unboxed FROM sumstats_table");
while($array = mysqli_fetch_assoc($sql)){
    echo "<p >Imaged Count:", $array['images'], "EndTest</p>";
    echo "<p >Tagged Count:", $array['tagged'], "EndTest</p>";
    echo "<p >Unboxed Count:", $array['unboxed'], "EndTest</p>";
}

$conn->close();
</code>```

Body:
I am trying to write a website that can display information from a mySQL database using PHP.

I have set up the database connection, I believe it is doing the query but it is not displaying the query. It stops displaying data after the first variable is echoed in the code.

I attempted the query directly in mySQL and it gave me the response I wanted.

Here is the code for the HTML document:

EDIT: The value I am trying to display is an integer.

<!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="style.css" />

        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta charset="utf-8">
        <meta author="Cole K. Motuliak">

        <title>sumstats - view stats</title>

JHS IT Summer Statistics Viewpage

Welcome

                <?php
                include 'view_stats.php';
                ?>

© 2020 Cole K. Motuliak | cmotuliak3@gmail.com

Here is the PHP code

<?php
                $servername = "localhost:3306"; // Define Server Domain Name / TCP port
                $username = "sumstats_viewonly"; // Define username
                $password = "*****"; // Define password, PASSWORD CHANGED FROM SCRIPT
                $dbname = "sumstats_db"; // Define database name

                // Create connection
                $conn = new mysqli($servername, $username, $password, $dbname);
                // Check connection
                if ($conn->connect_error) {
                    die("Connection failed: " . $conn->connect_error);
                }
                $imaged_query = "SELECT imaged FROM sumstats_table";
                $tagged_query = "SELECT tagged FROM sumstats_table";
                $unboxed_query = "SELECT unboxed FROM sumstats_table";
                $imaged_int = $conn->query($imaged_query);
                $tagged_int = $conn->query($tagged_query);
                $unboxed_int = $conn->query($unboxed_query);
                echo "
Imaged Count:", $imaged_int, "EndTest
";
                echo "
Tagged Count:", $tagged_int, "EndTest
";
                echo "
Unboxed Count:", $unboxed_int, "EndTest
";
                $conn->close();

                ?>

If anybody could assist and tell me what I am doing wrong, please let me know. Thanks!

Body:
You can use this as your view_stats.php

It makes less database query and allows looping

<?php
$servername = "localhost:3306"; // Define Server Domain Name / TCP port
$username = "sumstats_viewonly"; // Define username
$password = "*****"; // Define password, PASSWORD CHANGED FROM SCRIPT
$dbname = "sumstats_db"; // Define database name

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = $conn->query("SELECT imaged,tagged,unboxed FROM sumstats_table");
while($array = mysqli_fetch_assoc($sql)){
    echo "<p >Imaged Count:", $array['images'], "EndTest</p>";
    echo "<p >Tagged Count:", $array['tagged'], "EndTest</p>";
    echo "<p >Unboxed Count:", $array['unboxed'], "EndTest</p>";
}

$conn->close();


问:
How to stop the error occuring in my Python curses code?
I'm confused about why this error keeps popping up whenever I run some curses code.

Code:

```<code>import curses

stdscr = initscr()
</code>```

Output:

```<code>Traceback (most recent call last):
  File "C:\Users\Abd-ur-Rahmaan\Desktop\Abd-Ur-Rahmaan Shabbir\Python coding\Python Advanced Shit\The first curses project\The first curses project.py", line 3, in <module>
    stdscr = curses.initscr()
  File "C:\Users\Abd-ur-Rahmaan\Desktop\lib\curses\__init__.py", line 30, in initscr
    fd=_sys.__stdout__.fileno())
AttributeError: 'NoneType' object has no attribute 'fileno'
</code>```

答:
put your .py file wherever you have PATH enabled (it should be the python folder as standart)

pip install windows-curses

right click on start > run

enter the name of the file (snake.py for example)

run

Body:
I'm confused about why this error keeps popping up whenever I run some curses code.

Code:

import curses

stdscr = initscr()

Output:

Traceback (most recent call last):
  File "C:\Users\Abd-ur-Rahmaan\Desktop\Abd-Ur-Rahmaan Shabbir\Python coding\Python Advanced Shit\The first curses project\The first curses project.py", line 3, in <module>
    stdscr = curses.initscr()
  File "C:\Users\Abd-ur-Rahmaan\Desktop\lib\curses\__init__.py", line 30, in initscr
    fd=_sys.__stdout__.fileno())
AttributeError: 'NoneType' object has no attribute 'fileno'


问:
Shouldnt the x[1] just take the second array in the multidimensional array=
I have trouble understanding the lambda function, I always confuse myself because I overthink everything, here my problem:

```<code>nm = input().split()
n = int(nm[0])
m = int(nm[1])
arr = []

for _ in range(n):
    arr.append(list(map(int, input().rstrip().split())))

k = int(input())

arr.sort(key=lambda x: x[1])
</code>```

What the Code does isn't important right now, but I receive following output if I print my array(for my example):

```<code>[[7, 1, 0], [10, 2, 5], [6, 5, 9], [9, 9, 9], [1, 23, 12]]
</code>```

As you can see it is a multidimensional array, now I want to sort it based on the second element of each list:

```<code>arr.sort(key=lambda x: x[1])
</code>```

So I have the list and I want to sort it with the key lambda and the variable x: x[1] shouldn't my variable x be the multidimensional array? Isnt it the same if I say x = arr,
how exactly does this function know i want to sort all the elements that are at position x[1] from each list, i would have thought using x[1] would only be the second array in the multidimensional array:

```<code>[[1, 2, 3], **[4, 2, 6]** ...
</code>```

Im a beginner so I would appreciate a beginner friendly response to my question,
cheers!

答:
No, x in the lambda is not the entire arr (that would be kind of pointless), but each element in arr, like when using a for loop.

From the documentation of sorted (it's the same for list.sort), my highlighting:

key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). The default value is None (compare the elements directly).

The function is applied to each element to extract or calculate the comparison key from that element. In your case, it takes the second element [1] from each x in arr, e.g. x is [6, 5, 9], the key function extracts 5, and thus it is sorted third.

The way I understand your question, this is exactly what you wanted to do. If instead you want to sort the second sublist of arr, you could do arr[1].sort(), or if you want just the second elements in sorted order, it would be e.g. sorted(x[1] for x in arr).

Body:
I have trouble understanding the lambda function, I always confuse myself because I overthink everything, here my problem:

nm = input().split()
n = int(nm[0])
m = int(nm[1])
arr = []

for _ in range(n):
    arr.append(list(map(int, input().rstrip().split())))

k = int(input())

arr.sort(key=lambda x: x[1])

What the Code does isn't important right now, but I receive following output if I print my array(for my example):

[[7, 1, 0], [10, 2, 5], [6, 5, 9], [9, 9, 9], [1, 23, 12]]

As you can see it is a multidimensional array, now I want to sort it based on the second element of each list:

arr.sort(key=lambda x: x[1])

So I have the list and I want to sort it with the key lambda and the variable x: x[1] shouldn't my variable x be the multidimensional array? Isnt it the same if I say x = arr,
how exactly does this function know i want to sort all the elements that are at position x[1] from each list, i would have thought using x[1] would only be the second array in the multidimensional array:

[[1, 2, 3], **[4, 2, 6]** ...

Im a beginner so I would appreciate a beginner friendly response to my question,
cheers!


问:
appbundle and split crash on start android flutter
So I recently deployed my appbundle on Google Play store which was working fine up until I released update I get crash on start every time..I tried with different API then I tried split per abi same issue it does not work...
I'm not sure if it's related to digital signature or something

Weird thing generating apk flutter run --release work fine on local
but I rather stick with appbundle since the apk is larger in size

I've been trying to look command to debug this no luck any ideas?

答:
Turn out this was caused after updating classpath 'com.android.tools.build:gradle:4.0.0' in build.gradle dependencies which requires gradle 6.1.1 to work
I didn't notice this before because I was using

```<code>lintOptions {
disable 'InvalidPackage'
checkReleaseBuilds false
}
</code>```

which was causing theses errors

Execution failed for task ':app:lintVitalRelease'.
  Could not resolve all artifacts for configuration ':app:debugRuntimeClasspath'.

So the simple solution was to downgrade the classpath to 3.6.3

Note : I'm using JDK 14 in case it helps.

Body:
Turn out this was caused after updating classpath 'com.android.tools.build:gradle:4.0.0' in build.gradle dependencies which requires gradle 6.1.1 to work
I didn't notice this before because I was using

lintOptions {
disable 'InvalidPackage'
checkReleaseBuilds false
}

which was causing theses errors

Execution failed for task ':app:lintVitalRelease'.
  Could not resolve all artifacts for configuration ':app:debugRuntimeClasspath'.

So the simple solution was to downgrade the classpath to 3.6.3

Note : I'm using JDK 14 in case it helps.


问:
What is causing my program to only print parentheses?
I have written a Haskell program in which I want to implement a carry-save adder. I have defined type Nibble = (Bool, Bool, Bool, Bool) and type Byte = (Nibble, Nibble). The function of the carry-save adder is carrySaveAdder :: Byte -> Byte -> Byte -> ( Byte , Byte ). To display one of the bytes in the tuple, I wrote a small function showBin :: Byte -> String which can display the Byte as a binary number.

This function works perfectly fine if used in ghci with a value I defined there by hand such as let x = ((True,False,True,True),(False,False,False,False)) :: Byte. Once I try to apply it to one of the element of the tuple, it does not perform the expected behaviour. It prints either two parentheses or a single quotation mark and responds to keyboard input which makes it seem like it is waiting for user input of some kind. If I check out the length of it though,it seems to be 8 (as expected) although I cannot see the actual output.

The expected output would be an 8-bit binary number as a string but the actual output is a quotation mark and the "output" does not stop unless I manually interrupt it.

What could be a possible reason for this behaviour?

type Nibble = (Bool, Bool, Bool, Bool)
type Byte = (Nibble, Nibble)

nand :: Bool -> Bool -> Bool
nand a b = not (a && b)

xor :: Bool -> Bool -> Bool
xor a b = nand( nand a (nand a b)) (nand b (nand a b))

fulladder :: Bool -> Bool -> Bool ->(Bool, Bool)
fulladder a b c =  (xor c (xor a b) , (a &&b) || ((xor a b) && c))

carrySaveAdder :: Byte -> Byte -> Byte -> ( Byte , Byte )
carrySaveAdder ((a0, a1, a2, a3),(a4,a5,a6,a7)) ((b0, b1, b2, b3),(b4,b5,b6,b7)) ((c0, c1, c2, c3),(c4,c5,c6,c7)) =
  let (r7,c7) = fulladder a7 b7 c7
      (r6,c6) = fulladder a6 b6 c6
      (r5,c5) = fulladder a5 b5 c5
      (r4,c4) = fulladder a4 b4 c4
      (r3,c3) = fulladder a3 b3 c3
      (r2,c2) = fulladder a2 b2 c2
      (r1,c1) = fulladder a1 b1 c1
      (r0,c0) = fulladder a0 b0 c0
    in (((r0,r1,r2,r3),(r4,r5,r6,r7)),((c0, c1, c2, c3),(c4,c5,c6,c7)))

showNib :: Nibble -> String
showNib (a,b,c,d) =  map showIndividual ([a,b,c,d])

showBin :: Byte -> String
showBin (a,b) =  showNib a ++ showNib b

showIndividual :: Bool -> Char
showIndividual a
                  | a =  '1'
                  | not a = '0'
```

<pre class="lang-hs prettyprint-override"><code>let x = ((True,False,True,True),(False,True,True,True)) :: Byte
let y = ((False,False,True,False),(False,True,True,True)) :: Byte
let z = ((False,False,True,False),(True,True,True,False)) :: Byte
let (sum,carry) = carrySaveAdder x y z
showBin carry
</code>```

答:
Your problem is in this line:

```<code>      (r0,c0) = fulladder a0 b0 c0
</code>```

You are defining the value c0 in terms of itself.  When GHCi tries to evaluate it to show it, it gets into an infinite loop.

Note that every line in there creates that same circular dependency in its carry bit.  They're not wired together properly - a carry bit should carry from an addition into the next one, not itself.

Body:
I have written a Haskell program in which I want to implement a carry-save adder. I have defined type Nibble = (Bool, Bool, Bool, Bool) and type Byte = (Nibble, Nibble). The function of the carry-save adder is carrySaveAdder :: Byte -> Byte -> Byte -> ( Byte , Byte ). To display one of the bytes in the tuple, I wrote a small function showBin :: Byte -> String which can display the Byte as a binary number.

This function works perfectly fine if used in ghci with a value I defined there by hand such as let x = ((True,False,True,True),(False,False,False,False)) :: Byte. Once I try to apply it to one of the element of the tuple, it does not perform the expected behaviour. It prints either two parentheses or a single quotation mark and responds to keyboard input which makes it seem like it is waiting for user input of some kind. If I check out the length of it though,it seems to be 8 (as expected) although I cannot see the actual output.

The expected output would be an 8-bit binary number as a string but the actual output is a quotation mark and the "output" does not stop unless I manually interrupt it.

What could be a possible reason for this behaviour?

type Nibble = (Bool, Bool, Bool, Bool)
type Byte = (Nibble, Nibble)

nand :: Bool -> Bool -> Bool
nand a b = not (a && b)

xor :: Bool -> Bool -> Bool
xor a b = nand( nand a (nand a b)) (nand b (nand a b))

fulladder :: Bool -> Bool -> Bool ->(Bool, Bool)
fulladder a b c =  (xor c (xor a b) , (a &&b) || ((xor a b) && c))

carrySaveAdder :: Byte -> Byte -> Byte -> ( Byte , Byte )
carrySaveAdder ((a0, a1, a2, a3),(a4,a5,a6,a7)) ((b0, b1, b2, b3),(b4,b5,b6,b7)) ((c0, c1, c2, c3),(c4,c5,c6,c7)) =
  let (r7,c7) = fulladder a7 b7 c7
      (r6,c6) = fulladder a6 b6 c6
      (r5,c5) = fulladder a5 b5 c5
      (r4,c4) = fulladder a4 b4 c4
      (r3,c3) = fulladder a3 b3 c3
      (r2,c2) = fulladder a2 b2 c2
      (r1,c1) = fulladder a1 b1 c1
      (r0,c0) = fulladder a0 b0 c0
    in (((r0,r1,r2,r3),(r4,r5,r6,r7)),((c0, c1, c2, c3),(c4,c5,c6,c7)))

showNib :: Nibble -> String
showNib (a,b,c,d) =  map showIndividual ([a,b,c,d])

showBin :: Byte -> String
showBin (a,b) =  showNib a ++ showNib b

showIndividual :: Bool -> Char
showIndividual a
                  | a =  '1'
                  | not a = '0'

let x = ((True,False,True,True),(False,True,True,True)) :: Byte
let y = ((False,False,True,False),(False,True,True,True)) :: Byte
let z = ((False,False,True,False),(True,True,True,False)) :: Byte
let (sum,carry) = carrySaveAdder x y z
showBin carry

Body:
Your problem is in this line:

      (r0,c0) = fulladder a0 b0 c0

You are defining the value c0 in terms of itself.  When GHCi tries to evaluate it to show it, it gets into an infinite loop.

Note that every line in there creates that same circular dependency in its carry bit.  They're not wired together properly - a carry bit should carry from an addition into the next one, not itself.


问:
Nesting kivy widgets in python file
I'm trying to recreate the below MDCard, I wrote in kivy language, in my python file. Although I can do it fine in kivy language I'm struggling to do it in Python.

kv file:

    MDCard:
        size_hint: 1, None
        elevation: 6
        oritentation: "horizontal"
        spacing: 10
        Image:
            source: "test_image.jpeg"
            allow_stretch: True
            keep_ratio: False
            size_hint_x: 0.5
        BoxLayout:
            orientation: "vertical"
            BoxLayout:
                MDLabel:
                    text: "Test"
                MDLabel:
                    text: "Test text"
            MDLabel:
                text: "Longer text here to test wrap around of MDLabel"
```

<p>py file:</p>

<pre class="lang-py prettyprint-override"><code>    md_card = MDCard(size_hint=(1,None), elevation=6, spacing=10,
        Image(source="test_image.jpeg", allow_stretch=True, keep_ratio=False, size_hint_x=0.5),
        BoxLayout(orientation="vertical", BoxLayout(MDLabel(text="Test"), MDLabel(text="Test text")),
            MDLabel(text="Longer text here to test wrap around of MDLabel")))
</code>```

At the moment, with the py file I get a SyntaxError:

```<code>Image(source="test_image.jpeg", allow_stretch=True, keep_ratio=False, size_hint_x=0.5),
^
SyntaxError: positional argument follows keyword argument
</code>```

答:
You need to add_widget see https://kivy.org/doc/stable/guide/widgets.html

```<code>md_card = MDCard(size_hint=(1,None), elevation=6, spacing=10)
md_card.add_widget(Image(source="test_image.jpeg", allow_stretch=True, keep_ratio=False, size_hint_x=0.5))
...
</code>```

Title: Nesting kivy widgets in python file

Body:
I'm trying to recreate the below MDCard, I wrote in kivy language, in my python file. Although I can do it fine in kivy language I'm struggling to do it in Python.

kv file:

    MDCard:
        size_hint: 1, None
        elevation: 6
        oritentation: "horizontal"
        spacing: 10
        Image:
            source: "test_image.jpeg"
            allow_stretch: True
            keep_ratio: False
            size_hint_x: 0.5
        BoxLayout:
            orientation: "vertical"
            BoxLayout:
                MDLabel:
                    text: "Test"
                MDLabel:
                    text: "Test text"
            MDLabel:
                text: "Longer text here to test wrap around of MDLabel"

py file:

    md_card = MDCard(size_hint=(1,None), elevation=6, spacing=10,
        Image(source="test_image.jpeg", allow_stretch=True, keep_ratio=False, size_hint_x=0.5),
        BoxLayout(orientation="vertical", BoxLayout(MDLabel(text="Test"), MDLabel(text="Test text")),
            MDLabel(text="Longer text here to test wrap around of MDLabel")))

At the moment, with the py file I get a SyntaxError:

Image(source="test_image.jpeg", allow_stretch=True, keep_ratio=False, size_hint_x=0.5),
^
SyntaxError: positional argument follows keyword argument

Body:
You need to add_widget see https://kivy.org/doc/stable/guide/widgets.html

md_card = MDCard(size_hint=(1,None), elevation=6, spacing=10)
md_card.add_widget(Image(source="test_image.jpeg", allow_stretch=True, keep_ratio=False, size_hint_x=0.5))
...


问:
how to continue in a python script, if the program exits/crashes with pwntools?
I want to continue the python script do things, when the program crashes/exits. But it does not work. For example:

```<code>from pwn import *

p = process("./proc")

p.interactive()
<do stuff and exit>

print("Some stuff")

</code>```

But when the progam proc exits/crashes, the part below p.interactive() is not executed. Can someone help?

答:
you should use a "try except" which allows you to run code in the try part, and once the program crashes it moves on to the except. read more here.

an example:

```<code>try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")
</code>```

Body:
I want to continue the python script do things, when the program crashes/exits. But it does not work. For example:

from pwn import *

p = process("./proc")

p.interactive()
<do stuff and exit>

print("Some stuff")

But when the progam proc exits/crashes, the part below p.interactive() is not executed. Can someone help?

Body:
you should use a "try except" which allows you to run code in the try part, and once the program crashes it moves on to the except. read more here.

an example:

try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")


问:
Optimizing queries for content popularity by hits

I've done some searching for this but haven't come up with anything, maybe someone could point me in the right direction.

I have a website with lots of content in a MySQL database and a PHP script that loads the most popular content by hits. It does this by logging each content hit in a table along with the access time. Then a select query is run to find the most popular content in the past 24 hours, 7 day or maximum 30 days. A cronjob deletes anything older than 30 days in the log table.

The problem I'm facing now is as the website grows the log table has 1m+ hit records and it is really slowing down my select query (10-20s). At first I though the problem was a join I had in the query to get the content title, url, etc. But now I'm not sure as in test removing the join does not speed the query as much as I though it would.

So my question is what is best practise of doing this kind of popularity storing/selecting? Are they any good open source scripts for this? Or what would you suggest?

Table scheme

"popularity" hit log table

  nid | insert_time | tid

  nid: Node ID of the content

  insert_time: timestamp (2011-06-02 04:08:45)

  tid: Term/category ID

"node" content table

  nid | title | status | (there are more but these are the important ones)

  nid: Node ID

  title: content title

  status: is the content published (0=false, 1=true)

SQL

```<code>SELECT node.nid, node.title, COUNT(popularity.nid) AS count
FROM `node` INNER JOIN `popularity` USING (nid)
WHERE node.status = 1
  AND  popularity.insert_time >= DATE_SUB(CURDATE(),INTERVAL 7 DAY)
GROUP BY popularity.nid
ORDER BY count DESC
LIMIT 10;
</code>```

答:
you can add indexes and try tweaking your SQL but the real solution here is to cache the results.

you should really only need to caclulate the last 7/30 days of traffic once daily

and you could do the past 24 hours hourly ?

even if  you did it once every 5 minutes, that's still a huge savings over running the (expensive) query for every hit of every user.

Body:
I've done some searching for this but haven't come up with anything, maybe someone could point me in the right direction.

I have a website with lots of content in a MySQL database and a PHP script that loads the most popular content by hits. It does this by logging each content hit in a table along with the access time. Then a select query is run to find the most popular content in the past 24 hours, 7 day or maximum 30 days. A cronjob deletes anything older than 30 days in the log table.

The problem I'm facing now is as the website grows the log table has 1m+ hit records and it is really slowing down my select query (10-20s). At first I though the problem was a join I had in the query to get the content title, url, etc. But now I'm not sure as in test removing the join does not speed the query as much as I though it would.

So my question is what is best practise of doing this kind of popularity storing/selecting? Are they any good open source scripts for this? Or what would you suggest?

Table scheme

"popularity" hit log table

  nid | insert_time | tid

  nid: Node ID of the content

  insert_time: timestamp (2011-06-02 04:08:45)

  tid: Term/category ID

"node" content table

  nid | title | status | (there are more but these are the important ones)

  nid: Node ID

  title: content title

  status: is the content published (0=false, 1=true)

SQL

SELECT node.nid, node.title, COUNT(popularity.nid) AS count
FROM `node` INNER JOIN `popularity` USING (nid)
WHERE node.status = 1
  AND  popularity.insert_time >= DATE_SUB(CURDATE(),INTERVAL 7 DAY)
GROUP BY popularity.nid
ORDER BY count DESC
LIMIT 10;


问:
Excel 2016 query editor, filter/where clause
I'm struggling with probably the simplest thing. How do I filter my data using a where clause in Excel 2016, ODBC sql database source.
I'm new to Excel 2016, I used to just modify the SQL Command via the odbc properties. Now i can't even see the SQL command when I create the odbc.

So from just playing around. I gathered that there is now a series of "Applied Steps", but I struggle to find where I can find how to limit the rows to a date range. (I don't want to display the date because I'm aggregating by inventory type) But there must be somewhere I can say return only for date  '2020-05-01' for example. (where date = '2020-05-01')

the next steps will then be making that a dynamic parameter so I can have some sort of input when the data refresh.

Any tips?

答:
The SQL statement is greyed out

Right clicking a step -> view native SQL will gray out when that step cannot be query folded. Previous steps are still viewable.

You can find the sql query and server name if you choose advanced editor -- which displays all steps in one editor.

native sql

If you want raw sql, import the table as a new connection and paste your query into that box.
note: [] in powerquery is a Record literal.

```<code>// indented for readability
let
    Source = Sql.Database("server", "dbo"),
    // using parameterized queries
    RawSQL = "SELECT * FROM users as
        WHERE EnglishMonthName=@MonthName
        AND
        EnglishDayNameOfWeek=@DayName",
    TableName = Value.NativeQuery(
        Source, RawSQL
        [
            MonthName="March",
            DayName="Tuesday"
        ]
    )
in
    TableName
</code>```

I don't want to display the date because I'm aggregating by inventory type

Using the UI, you would import the table keeping the date column. Filter rows. Then choose remove column as your last step. Your model will not display removed columns.

Where clause in PowerQuery aka: Get Data

Where is the function Table.SelectRows The UI will generate the code for you

Right click your date column -> filter -> date/time -> equals

If you want 2020/05/09 It generates:

```<code>= Table.SelectRows(#"Source Table", each [Date] = #date(2020, 5, 9))
</code>```

You may use multiple conditions, like a date range

```<code>
= Table.SelectRows(#"Table Name", each
    [Date] >= #date(2020, 5, 9) and
    [Date] <= #date(2020, 6, 1)
)
</code>```

Body:
The SQL statement is greyed out

Right clicking a step -> view native SQL will gray out when that step cannot be query folded. Previous steps are still viewable.

You can find the sql query and server name if you choose advanced editor -- which displays all steps in one editor.

native sql

If you want raw sql, import the table as a new connection and paste your query into that box.
note: [] in powerquery is a Record literal.

// indented for readability
let
    Source = Sql.Database("server", "dbo"),
    // using parameterized queries
    RawSQL = "SELECT * FROM users as
        WHERE EnglishMonthName=@MonthName
        AND
        EnglishDayNameOfWeek=@DayName",
    TableName = Value.NativeQuery(
        Source, RawSQL
        [
            MonthName="March",
            DayName="Tuesday"
        ]
    )
in
    TableName

I don't want to display the date because I'm aggregating by inventory type

Using the UI, you would import the table keeping the date column. Filter rows. Then choose remove column as your last step. Your model will not display removed columns.

Where clause in PowerQuery aka: Get Data

Where is the function Table.SelectRows The UI will generate the code for you

Right click your date column -> filter -> date/time -> equals

If you want 2020/05/09 It generates:

= Table.SelectRows(#"Source Table", each [Date] = #date(2020, 5, 9))

You may use multiple conditions, like a date range

= Table.SelectRows(#"Table Name", each
    [Date] >= #date(2020, 5, 9) and
    [Date] <= #date(2020, 6, 1)
)


问:
Is there a way to automatically update a certain field after certain time?
I am creating an website using node.js, express.js, and mongoose and I have one field that needs to be updated after a certain time so my question is there a way to do that ? Or I have to use cron? Thank you for your answer.</p>

答:
You don't necessarily need to use cron.

For example, you could use setTimeout() or setInterval() (https://nodejs.org/uk/docs/guides/timers-in-node/) to achieve this functionality inside your application with the simplest means possible.

Also, there are libraries like cron (https://www.npmjs.com/package/cron) which handle these timeouts/intervals for you and are nice if you prefer cron-style syntax without having to deal with os-side infrastructure or don't have any access to it.


问:
How to recursively program a multiplication algorithms
I started a new course in algorithms. The professor is trying to create a multiplication algorithm with other rules.

He divides the digits of the numbers we are trying to multiply into two groups for example. x = 3452 then a = 34, b = 52 (the same applies for y).

According to him, the base operation would be:

If you're given two numbers that have the just one digit each. Then
  you just multiply them in one basic operation and return the result.

How would you compute ac, ad, bc and bd recursively if those are very simple operations?

答:
Here's how you would write the code (in python) for karatsuba (this assumes x and y always have the same number of even digits):

```<code>def numDigits(x):
  """
  Returns the number of digits in x
  """
  if x == 0:
    return 1

  digits = 0
  while x >= 1:
    x = int(x / 10)
    digits+=1
  return digits

def multiply(x, y):
  x_digits = numDigits(x)
  y_digits = numDigits(y)

  if x_digits != y_digits:
    return -1                    # not valid

  n = x_digits

  if n == 1:                     # checks if x (and y) are only 1 digit
    return x*y                   # single digit multiplication

  half_n = int(n / 2)

  a = int(x / (10**half_n))
  b = x - (a*(10**half_n))
  c = int(y / (10**half_n))
  d = y - (c*(10**half_n))

  ac = multiply(a, c)
  ad = multiply(a, d)
  bc = multiply(b, c)
  bd = multiply(b, d)

  return (10**n)*ac + (10**half_n)*(ad + bc) + bd

assert multiply(1, 2) == 2
assert multiply(10, 20) == 200
assert multiply(15, 21) == 315
assert multiply(1710, 2450) == 4189500
print("all pass!")
</code>```

You can modify the code to allow x and y to have odd number of digits and to be of different lengths with a little more work.

Body:
Here's how you would write the code (in python) for karatsuba (this assumes x and y always have the same number of even digits):

def numDigits(x):
  """
  Returns the number of digits in x
  """
  if x == 0:
    return 1

  digits = 0
  while x >= 1:
    x = int(x / 10)
    digits+=1
  return digits

def multiply(x, y):
  x_digits = numDigits(x)
  y_digits = numDigits(y)

  if x_digits != y_digits:
    return -1                    # not valid

  n = x_digits

  if n == 1:                     # checks if x (and y) are only 1 digit
    return x*y                   # single digit multiplication

  half_n = int(n / 2)

  a = int(x / (10**half_n))
  b = x - (a*(10**half_n))
  c = int(y / (10**half_n))
  d = y - (c*(10**half_n))

  ac = multiply(a, c)
  ad = multiply(a, d)
  bc = multiply(b, c)
  bd = multiply(b, d)

  return (10**n)*ac + (10**half_n)*(ad + bc) + bd

assert multiply(1, 2) == 2
assert multiply(10, 20) == 200
assert multiply(15, 21) == 315
assert multiply(1710, 2450) == 4189500
print("all pass!")

You can modify the code to allow x and y to have odd number of digits and to be of different lengths with a little more work.


问:
cron (reboot job) and wget (extract files) don't "get" along
I'm trying really hard to get this to work, but I just can't seem to get it right.

I got this Raspberry Pi that I want to download photos from a dropbox link into a specific folder on reboot.

sudo crontab -e

```<code>@reboot /home/pi/path/to/dir/with/photos/scripts.sh
</code>```

scripts.sh

```<code>#!/bin/bash
set -x
cd /home/pi/path/to/dir/with/photos/

# delete all photos and download and convert them again
rm -f /home/pi/crontab.refresh.log || true
sh /home/pi/path/to/dir/with/photos/refreshPhotos.sh > /home/pi/crontab.refresh.log

# convert all photos to bmp (and scale them)
rm -f /home/pi/crontab.convert.log || true
/usr/bin/python2.7 /home/pi/path/to/dir/with/photos/convertPhotos.py > /home/pi/crontab.convert.log

</code>```

refreshPhotos.sh

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

# clear the "old" ones
rm -f *.JPG || true
rm -f *.jpg || true

# Get the "fresh" ones
wget -qO- https://www.dropbox.com/sh/AAA/BB -P /home/pi/path/to/dir/with/photos/ | bsdtar -xvf-
</code>```

The wget looks a bit funky with the -qO- and | bsdtar -xvf- - it's in order avoid getting them into folder AAA and BBB.

Running the script from

```<code>/home/pi/path/to/dir$ bash /with/photos/scripts.sh
</code>```

works just fine. BUT rebooting does not seem to work (it only deletes the old photos and does not download the new ones.

ANY help that will solve my issue will be highly appreciated!

答:
@Philippe suggestion helped me figuring out that it's because that the wifi connection is established once the cron job starts.

This did the trick:

scripts.sh

```<code>#!/bin/bash
set -x
cd /home/pi/path/to/dir/with/photos/

# remove all old logs first
rm -f /home/pi/crontab.*.log || true
rm -f /home/pi/crontab.log || true

# delete all photos and download and convert them again
rm -f /home/pi/crontab.refresh.log || true
while ! ping -c1 dropbox.com >> /home/pi/crontab.wifi.log # Need to make sure that the internet connection is there before starting
  do echo "no connection to dropbox yet"
done
sh /home/pi/path/to/dir/with/photos/refreshPhotos.sh >& /home/pi/crontab.refresh.log
</code>```

Thank you VERY much @Philippe !

Body:
I'm trying really hard to get this to work, but I just can't seem to get it right.

I got this Raspberry Pi that I want to download photos from a dropbox link into a specific folder on reboot.

sudo crontab -e

@reboot /home/pi/path/to/dir/with/photos/scripts.sh

scripts.sh

#!/bin/bash
set -x
cd /home/pi/path/to/dir/with/photos/

# delete all photos and download and convert them again
rm -f /home/pi/crontab.refresh.log || true
sh /home/pi/path/to/dir/with/photos/refreshPhotos.sh > /home/pi/crontab.refresh.log

# convert all photos to bmp (and scale them)
rm -f /home/pi/crontab.convert.log || true
/usr/bin/python2.7 /home/pi/path/to/dir/with/photos/convertPhotos.py > /home/pi/crontab.convert.log

refreshPhotos.sh

#!/bin/bash

# clear the "old" ones
rm -f *.JPG || true
rm -f *.jpg || true

# Get the "fresh" ones
wget -qO- https://www.dropbox.com/sh/AAA/BB -P /home/pi/path/to/dir/with/photos/ | bsdtar -xvf-

The wget looks a bit funky with the -qO- and | bsdtar -xvf- - it's in order avoid getting them into folder AAA and BBB.

Running the script from

/home/pi/path/to/dir$ bash /with/photos/scripts.sh

works just fine. BUT rebooting does not seem to work (it only deletes the old photos and does not download the new ones.

ANY help that will solve my issue will be highly appreciated!

Body:
@Philippe suggestion helped me figuring out that it's because that the wifi connection is established once the cron job starts.

This did the trick:

scripts.sh

#!/bin/bash
set -x
cd /home/pi/path/to/dir/with/photos/

# remove all old logs first
rm -f /home/pi/crontab.*.log || true
rm -f /home/pi/crontab.log || true

# delete all photos and download and convert them again
rm -f /home/pi/crontab.refresh.log || true
while ! ping -c1 dropbox.com >> /home/pi/crontab.wifi.log # Need to make sure that the internet connection is there before starting
  do echo "no connection to dropbox yet"
done
sh /home/pi/path/to/dir/with/photos/refreshPhotos.sh >& /home/pi/crontab.refresh.log

Thank you VERY much @Philippe !


问:
Converting strings to boolean gives only False value
Trying to convert data (string format from a csv file) to boolean (in a dataframe), I have 'lost' information on their original value, so now all the values are boolean False.

The columns that I am trying to change into boolean are the following:

```<code>df['Col1'] =df['Col1'].astype('bool')
df['Col2'] =df['Col2'].astype('bool')
</code>```

I have also tried with

```<code>df.Col1 = np.where(df.Col1.eq('true'), True, False)
df. Col2 = np.where(df.Col2.eq('true') | df.Col2.eq('tbc'), True, False)
</code>```

The unique values for each column, Col1 and Col2 are:

```<code>Col1: array([true, false, nan], dtype=object)

Col2: array(['true', 'false', 'tbc', nan], dtype=object)
</code>```

My original dataset has the following values.

```<code>Col1      Col2
true      true
true      true
false     false
nan       false
false     true
true      tbc
</code>```

Though they were converted into boolean, all the values are False:

```<code>Col1      Col2
False     False
False     False
False     False
False     False
False     False
False     False
</code>```

I would like to treat TBC as True. Why am I getting only False values? Any idea on how I could fix it?

Sample of original dataset and code:

```<code>Date                 Checked             Verified
2018-05-23           FALSE                TRUE
2018-05-24           TRUE                 TBC
2018-05-26           FALSE                TBC
2018-05-31            nan                 nan
2019-12-01           TRUE                 TRUE
2019-12-05           TRUE                 TBC
2019-12-15           TRUE                 FALSE
2019-12-23           FALSE                nan
</code>```

Code

Read the file csv:

```<code>df=pd.read_csv(path, sep=';', engine='python')
</code>```

Transform to lower case

```<code>df= df.apply(lambda x: x.astype(str).str.lower())
</code>```

Transform string to boolean

```<code>df['Checked'] = np.where(df['Checked'].eq('true'), True, False)
df['Verified'] = np.where(df['Verified'].eq('true') | df['Verified'].eq('tbc'), True, False)
</code>```

Then I test how many rows have value Checked = True:

```<code>len(df[df['Checked']=='true'])
</code>```

output: 153

Convert to boolean Checked:

```<code>df['Checked'] = np.where(df['Checked'].eq('true'), True, False)
len(df[df['Checked']==True])
</code>```

output: 153

Convert Verified to boolean:

```<code>df['Verified'] = np.where(df['Verified'].eq('true') | df['Verified'].eq('tbc'), True, False)

len(df[df['Verified']==True])
</code>```

output: 0 (expected 60)

答:
You can do this for both columns via regular expressions and df.replace:

```<code>df.astype(str).replace({'(?i)True|TBC': True, '(?i)False|nan': False}, regex=True)

    Col1   Col2
0   True   True
1   True   True
2  False  False
3  False  False
4  False   True
5   True   True
</code>```

The pattern is case insensitive.

Body:
Trying to convert data (string format from a csv file) to boolean (in a dataframe), I have 'lost' information on their original value, so now all the values are boolean False.

The columns that I am trying to change into boolean are the following:

df['Col1'] =df['Col1'].astype('bool')
df['Col2'] =df['Col2'].astype('bool')

I have also tried with

df.Col1 = np.where(df.Col1.eq('true'), True, False)
df. Col2 = np.where(df.Col2.eq('true') | df.Col2.eq('tbc'), True, False)

The unique values for each column, Col1 and Col2 are:

Col1: array([true, false, nan], dtype=object)

Col2: array(['true', 'false', 'tbc', nan], dtype=object)

My original dataset has the following values.

Col1      Col2
true      true
true      true
false     false
nan       false
false     true
true      tbc

Though they were converted into boolean, all the values are False:

Col1      Col2
False     False
False     False
False     False
False     False
False     False
False     False

I would like to treat TBC as True. Why am I getting only False values? Any idea on how I could fix it?

Sample of original dataset and code:

Date                 Checked             Verified
2018-05-23           FALSE                TRUE
2018-05-24           TRUE                 TBC
2018-05-26           FALSE                TBC
2018-05-31            nan                 nan
2019-12-01           TRUE                 TRUE
2019-12-05           TRUE                 TBC
2019-12-15           TRUE                 FALSE
2019-12-23           FALSE                nan

Code

Read the file csv:

df=pd.read_csv(path, sep=';', engine='python')

Transform to lower case

df= df.apply(lambda x: x.astype(str).str.lower())

Transform string to boolean

df['Checked'] = np.where(df['Checked'].eq('true'), True, False)
df['Verified'] = np.where(df['Verified'].eq('true') | df['Verified'].eq('tbc'), True, False)

Then I test how many rows have value Checked = True:

len(df[df['Checked']=='true'])

output: 153

Convert to boolean Checked:

df['Checked'] = np.where(df['Checked'].eq('true'), True, False)
len(df[df['Checked']==True])

output: 153

Convert Verified to boolean:

df['Verified'] = np.where(df['Verified'].eq('true') | df['Verified'].eq('tbc'), True, False)

len(df[df['Verified']==True])

output: 0 (expected 60)

Body:
You can do this for both columns via regular expressions and df.replace:

df.astype(str).replace({'(?i)True|TBC': True, '(?i)False|nan': False}, regex=True)

    Col1   Col2
0   True   True
1   True   True
2  False  False
3  False  False
4  False   True
5   True   True

The pattern is case insensitive.


问:
Can not retrieve a jpg image using php
I am retrieving a jpg file from an oracle db, and trying to output it with the echo command.  The jpg file is stored as a blob inside the database, and displays properly when I access it from the database.  Here is the relevant code:

```<code>$query = 'select * from answer where answer_id = :answer_id';

$stmt = oci_parse($conn, $query);

oci_bind_by_name($stmt, ':answer_id', $answer_id);

oci_execute($stmt);

if ($row = oci_fetch_array($stmt, OCI_BOTH)){

    header('Content-type: image/jpeg');

    $mylob =  $row['ANS_PICTURE']->load();
    echo $mylob;

}
</code>```

This sends out an amount of data that is consistent with the size of the file, but the browser is completely unable to interpret it as an image.

Strangely, when I use

```<code>$fp = fopen('test.jpg', 'w');
fwrite($fp, $mylob);
</code>```

I can save the file and it has no trouble displaying the image, even using the browser to open the image through the server.

If I add a file-disposition header and prompt the user to save the image, it still does not display the image when I open it.

So it seems like there is a problem between printing the data and the browser receiving the data, though I have no idea what the problem could be.

Anyone have an idea?

答:
Try adding Content-Length header. You should retrieve $mylob_length from database because checking it's every time can be a slowdown:</p>

```<code>header('Content-Length: ' . $mylob_length);
</code>```

Title: Can not retrieve a jpg image using php

Body:
I am retrieving a jpg file from an oracle db, and trying to output it with the echo command.  The jpg file is stored as a blob inside the database, and displays properly when I access it from the database.  Here is the relevant code:

$query = 'select * from answer where answer_id = :answer_id';

$stmt = oci_parse($conn, $query);

oci_bind_by_name($stmt, ':answer_id', $answer_id);

oci_execute($stmt);

if ($row = oci_fetch_array($stmt, OCI_BOTH)){

    header('Content-type: image/jpeg');

    $mylob =  $row['ANS_PICTURE']->load();
    echo $mylob;

}

This sends out an amount of data that is consistent with the size of the file, but the browser is completely unable to interpret it as an image.

Strangely, when I use

$fp = fopen('test.jpg', 'w');
fwrite($fp, $mylob);

I can save the file and it has no trouble displaying the image, even using the browser to open the image through the server.

If I add a file-disposition header and prompt the user to save the image, it still does not display the image when I open it.

So it seems like there is a problem between printing the data and the browser receiving the data, though I have no idea what the problem could be.

Anyone have an idea?

Body:
Try adding Content-Length header. You should retrieve $mylob_length from database because checking it's every time can be a slowdown:

header('Content-Length: ' . $mylob_length);


问:
Setting environment variable in Jenkins pipeline stage from build parameter
I would like to configure an environment variable for my Jenkins pipeline, but dynamically based on an input parameter to the build. I'm trying to configure my pipeline to set the KUBECONFIG environment variable for kubectl commands.

My pipeline is as follows (slightly changed):

```<code>pipeline {

    parameters {
        choice(name: 'CLUSTER_NAME', choices: 'cluster1/cluster2')
    }

    stages {
        // Parallel stages since only one environment variable should be set, based on input
        stage ('Set environment variable') {
            parallel {
                stage ('Set cluster1') {
                    when {
                        expression {
                            params.CLUSTER_NAME == "cluster1"
                        }
                    }
                    environment {
                        KUBECONFIG = "~/kubeconf/cluster1.conf"
                    }
                    steps {
                        echo "Using KUBECONFIG: ${env.KUBECONFIG}"
                    }
                }

                stage ('Set cluster2') {
                    when {
                        expression {
                            params.CLUSTER_NAME == "cluster2"
                        }
                    }
                    environment {
                        KUBECONFIG = "~/kubeconf/cluster2.conf"
                    }
                    steps {
                        echo "Using KUBECONFIG: ${env.KUBECONFIG}"
                    }
                }
            }
        }

        stage ('Test env') {
            steps {
                sh "cat ${env.KUBECONFIG}"
            }
        }
    }
}
</code>```

However, while the stage where I set the environment variable can print it, once I move to another stage I only get null.

Is there some way of sharing env variables between stages? Since I'd like to use the default KUBECONFIG command (and not specify a file/context in my kubectl commands), it would be much easier to find a way to dynamically set the env variable.

I've seen the EnvInject plugin mentioned, but was unable to get it working for a pipeline, and was struggling with the documentation.

答:
I guess that with the environment{} you are setting the environment variable only for the stage where it runs - it is not affecting the context of environment of the pipeline itself. Set environment variables like below to affect the main context. Works for me.

```<code>pipeline {

    agent any

    parameters {
        choice(name: 'CLUSTER_NAME', choices: 'cluster1\ncluster2')
    }

    stages {
        // Parallel stages since only one environment variable should be set, based on input
        stage ('Set environment variable') {
            parallel {
                stage ('Set cluster1') {
                    when {
                        expression {
                            params.CLUSTER_NAME == "cluster1"
                        }
                    }
                    steps {
                        script{
                            env.KUBECONFIG = "~/kubeconf/cluster1.conf"
                            echo "Using KUBECONFIG: ${env.KUBECONFIG}"
                        }
                    }
                }

                stage ('Set cluster2') {
                    when {
                        expression {
                            params.CLUSTER_NAME == "cluster2"
                        }
                    }
                    steps {
                        script{
                            env.KUBECONFIG = "~/kubeconf/cluster2.conf"
                            echo "Using KUBECONFIG: ${env.KUBECONFIG}"
                        }
                    }
                }
            }
        }
        stage ('Test env') {
            steps {
                sh "cat ${env.KUBECONFIG}"
            }
        }
    }
}
</code>```

Body:
I would like to configure an environment variable for my Jenkins pipeline, but dynamically based on an input parameter to the build. I'm trying to configure my pipeline to set the KUBECONFIG environment variable for kubectl commands.

My pipeline is as follows (slightly changed):

pipeline {

    parameters {
        choice(name: 'CLUSTER_NAME', choices: 'cluster1/cluster2')
    }

    stages {
        // Parallel stages since only one environment variable should be set, based on input
        stage ('Set environment variable') {
            parallel {
                stage ('Set cluster1') {
                    when {
                        expression {
                            params.CLUSTER_NAME == "cluster1"
                        }
                    }
                    environment {
                        KUBECONFIG = "~/kubeconf/cluster1.conf"
                    }
                    steps {
                        echo "Using KUBECONFIG: ${env.KUBECONFIG}"
                    }
                }

                stage ('Set cluster2') {
                    when {
                        expression {
                            params.CLUSTER_NAME == "cluster2"
                        }
                    }
                    environment {
                        KUBECONFIG = "~/kubeconf/cluster2.conf"
                    }
                    steps {
                        echo "Using KUBECONFIG: ${env.KUBECONFIG}"
                    }
                }
            }
        }

        stage ('Test env') {
            steps {
                sh "cat ${env.KUBECONFIG}"
            }
        }
    }
}

However, while the stage where I set the environment variable can print it, once I move to another stage I only get null.

Is there some way of sharing env variables between stages? Since I'd like to use the default KUBECONFIG command (and not specify a file/context in my kubectl commands), it would be much easier to find a way to dynamically set the env variable.

I've seen the EnvInject plugin mentioned, but was unable to get it working for a pipeline, and was struggling with the documentation.

Body:
I guess that with the environment{} you are setting the environment variable only for the stage where it runs - it is not affecting the context of environment of the pipeline itself. Set environment variables like below to affect the main context. Works for me.

pipeline {

    agent any

    parameters {
        choice(name: 'CLUSTER_NAME', choices: 'cluster1\ncluster2')
    }

    stages {
        // Parallel stages since only one environment variable should be set, based on input
        stage ('Set environment variable') {
            parallel {
                stage ('Set cluster1') {
                    when {
                        expression {
                            params.CLUSTER_NAME == "cluster1"
                        }
                    }
                    steps {
                        script{
                            env.KUBECONFIG = "~/kubeconf/cluster1.conf"
                            echo "Using KUBECONFIG: ${env.KUBECONFIG}"
                        }
                    }
                }

                stage ('Set cluster2') {
                    when {
                        expression {
                            params.CLUSTER_NAME == "cluster2"
                        }
                    }
                    steps {
                        script{
                            env.KUBECONFIG = "~/kubeconf/cluster2.conf"
                            echo "Using KUBECONFIG: ${env.KUBECONFIG}"
                        }
                    }
                }
            }
        }
        stage ('Test env') {
            steps {
                sh "cat ${env.KUBECONFIG}"
            }
        }
    }
}


问:
selenium.common.exceptions.InvalidSelectorException: Message: Given xpath expression is invalid using xpath within scrollIntoView through Selenium
I use Python to scrape a website with a filter pane that needs to be scrolled.
I found a code that helps to scroll through the list of elements, that actually find a list and move through a loop.

recentList = driver.find_elements_by_xpath("/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li")
for list in recentList:
    driver.execute_script('arguments[0].scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"})', list)
```
<p>I have code that already contains a for loop and I would like to add only an element that needs to be scrolled to.
With the logic of the above I've written (a loop is simplified):</p>
<pre class="lang-js prettyprint-override"><code>for p in range(1,15):
    list = driver.find_element_by_xpath(str('/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li[[' + str(p) + ']'))
    driver.execute_script('arguments[0].scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"})', list)
</code>```

I can't figure out why it doesn't work.
Here is an Error I got:

selenium.common.exceptions.InvalidSelectorException: Message: Given xpath expression "/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li[[1]" is invalid: SyntaxError: The expression is not a legal expression.
```

Does anyone know what needs to be fixed?
The XPath in the last code is correct and was already in use.

I tried to replace my current loop with the "list in recentList" but then code stops when it needs to scroll through pages on a filter.

答:
This error message...

selenium.common.exceptions.InvalidSelectorException: Message: Given xpath expression "/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li[[1]" is invalid: SyntaxError: The expression is not a legal expression.
```
<p>...implies that the <em>XPath</em> expression was not a valid/legal expression.</p>
<p>If you observe the effective xpath within the error, there is an extra third bracket opening within the expression:</p>
```/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li[[1]
```
<hr />
<h2>Solution</h2>
<p>To remove the extra third bracket opening, you need to adjust the <em>xpath expression</em> as:</p>
<pre class="lang-js prettyprint-override"><code>list = driver.find_element_by_xpath(str('/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li[' + str(p) + ']'))
</code>```

References

You can find a couple of relevant discussions in:

InvalidSelectorError: invalid selector: Unable to locate an element with the xpath expression

Message “org.openqa.selenium.InvalidSelectorException: invalid selector: Unable to locate an element with the XPath expression” using sendKeys

Send whatsapp message to contacts using Python but getting an error: InvalidSelectorException: Message: invalid selector: Unable to locate an element

Body:
I use Python to scrape a website with a filter pane that needs to be scrolled.
I found a code that helps to scroll through the list of elements, that actually find a list and move through a loop.

recentList = driver.find_elements_by_xpath("/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li")
for list in recentList:
    driver.execute_script('arguments[0].scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"})', list)

I have code that already contains a for loop and I would like to add only an element that needs to be scrolled to.
With the logic of the above I've written (a loop is simplified):

for p in range(1,15):
    list = driver.find_element_by_xpath(str('/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li[[' + str(p) + ']'))
    driver.execute_script('arguments[0].scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"})', list)

I can't figure out why it doesn't work.
Here is an Error I got:

selenium.common.exceptions.InvalidSelectorException: Message: Given xpath expression "/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li[[1]" is invalid: SyntaxError: The expression is not a legal expression.

Does anyone know what needs to be fixed?
The XPath in the last code is correct and was already in use.

I tried to replace my current loop with the "list in recentList" but then code stops when it needs to scroll through pages on a filter.

Body:
This error message...

selenium.common.exceptions.InvalidSelectorException: Message: Given xpath expression "/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li[[1]" is invalid: SyntaxError: The expression is not a legal expression.

...implies that the XPath expression was not a valid/legal expression.

If you observe the effective xpath within the error, there is an extra third bracket opening within the expression:

/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li[[1]

Solution

To remove the extra third bracket opening, you need to adjust the xpath expression as:

list = driver.find_element_by_xpath(str('/html/body/div[3]/main/div/div/div/div[1]/div/form/div[2]/fieldset[3]/div/ul/li[' + str(p) + ']'))

References

You can find a couple of relevant discussions in:

InvalidSelectorError: invalid selector: Unable to locate an element with the xpath expression

Message “org.openqa.selenium.InvalidSelectorException: invalid selector: Unable to locate an element with the XPath expression” using sendKeys

Send whatsapp message to contacts using Python but getting an error: InvalidSelectorException: Message: invalid selector: Unable to locate an element


问:
Provide Custom Value Binder in Handlebars.NET
I'm trying to build a code generation framework using .net core and handlebars and I would need to customize how expressions are mapped to values in handlebars.net. Is it something that is possible? The closest I've been to is to transform my input object to a dictionary, but it does not give me the flexibility I need, is there any interfaces I can implement to achieve that?</p>

答:
If I get your intent right you can have a look at Handlebars.CSharp > IObjectDescriptorProvider (usage example).

P.S. Handlebars.CSharp is a fork of Handlebars.Net maintained by me.

Update:

Mentioned functionality is already merged to Handlebars.Net


问:
Android button setBackgroundColor change the size of the button
I create android button programmatically, and I put this butons in a TableRow, every thing work fine, but when I change the backgroudColor the colored button not respect the size as it do without the color:

My code is:

```<code>val btn = Button(this)
btn.isEnabled = false
btn.setBackgroundColor(Color.RED)
btn.layoutParams = TableRow.LayoutParams(150, 150)
</code>```

When I don't use the setBackgroundColor the size is correct.

I don't understand why the size is changes, is there any way to change only the default gray color of the button, without the size is changes.

答: if your app theme is material-theme then there is a default paddings applied to the button. that's why the color fills the whole canvas of the button after you apply it. try to restore the padding (I believe it's 8dp for all edges).

Body:
I create android button programmatically, and I put this butons in a TableRow, every thing work fine, but when I change the backgroudColor the colored button not respect the size as it do without the color:

My code is:

val btn = Button(this)
btn.isEnabled = false
btn.setBackgroundColor(Color.RED)
btn.layoutParams = TableRow.LayoutParams(150, 150)

When I don't use the setBackgroundColor the size is correct.

I don't understand why the size is changes, is there any way to change only the default gray color of the button, without the size is changes.


问:
How do I rotate around a certain point but stop at a certain angle?
I am trying to rotate a camera around an object but stop when the angle hits 90 degrees in the y-axis.

I have found options like "RotateTowards": https://docs.unity3d.com/ScriptReference/Quaternion.RotateTowards.html, and options like "RotateAround": https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html, but I am trying to find a way to combine both.

Code I have tried but that hasn't successfully worked:

```<code>void Update()
{
    if (cameraChange && transform.rotation.y != 90)
    {
        // transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0, 90f, 0), Time.deltaTime * speed);
           transform.rotation.RotateAround(player.transform.position, new Vector3(0, 1, 0), Time.deltaTime * speed);

    }
}

void GameOver()
{
    cameraChange = true;
    transform.LookAt(player.transform);
}
</code>```

答:
The problem you're having is transform.rotation returns a quaternion, the y component of a quaternion does not correspond to the y-axis, in fact, it's advised you don't touch those values directly at all unless you're really very familiar with quaternions.

Try:

```<code>transform.rotation.eulerAngles.y != 90 // this will correspond to the y-axis
</code>```

Assuming your code to do the rotation works, this should fix your issue

Body:
I am trying to rotate a camera around an object but stop when the angle hits 90 degrees in the y-axis.

I have found options like "RotateTowards": https://docs.unity3d.com/ScriptReference/Quaternion.RotateTowards.html, and options like "RotateAround": https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html, but I am trying to find a way to combine both.

Code I have tried but that hasn't successfully worked:

void Update()
{
    if (cameraChange && transform.rotation.y != 90)
    {
        // transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0, 90f, 0), Time.deltaTime * speed);
           transform.rotation.RotateAround(player.transform.position, new Vector3(0, 1, 0), Time.deltaTime * speed);

    }
}

void GameOver()
{
    cameraChange = true;
    transform.LookAt(player.transform);
}

Body:
The problem you're having is transform.rotation returns a quaternion, the y component of a quaternion does not correspond to the y-axis, in fact, it's advised you don't touch those values directly at all unless you're really very familiar with quaternions.

Try:

transform.rotation.eulerAngles.y != 90 // this will correspond to the y-axis

Assuming your code to do the rotation works, this should fix your issue


问:
How to use %p with additional lines in Haml
I am receiving the following error:

```<code>Illegal nesting: content can't be both given on the same line as %p and nested within it.
</code>```

This is my code:

```<code>- @docs.each do |doc|
%h2= link_to doc.title, doc
%p= time_ago_in_words(doc.created_at)
%p= truncate(doc.content, length:50)

    = link_to "Create Doc", new_doc_path
</code>```

答:
When you supply content on the same line as a tag in Haml, you are saying "The content of this tag will only be whatever is in this line, and close the tag immediately".

So

```<code>%p hello
</code>```

becomes

```<code><p>hello</p>
</code>```

In situations where you have more than one line for a tag, use a newline and indentation to indicate the content for that block:

```<code>%p
  Hello
  World
</code>```

Which results in:

```<code><p>Hello\nWorld</p>
</code>```

You are trying to use both of them here. You are supplying the content for the short form tag, but also indenting as if you plan on continuing to add content to your p tag.

To fix this you need to use the multiline syntax, if that is your intent, or remove the indentation from your link_to:

```<code>- @docs.each do |doc|
  %h2= link_to doc.title, doc
  %p= time_ago_in_words(doc.created_at)
  %p
    = truncate(doc.content, length:50)
    = link_to "Create Doc", new_doc_path
</code>```

Body:
I am receiving the following error:

Illegal nesting: content can't be both given on the same line as %p and nested within it.

This is my code:

- @docs.each do |doc|
%h2= link_to doc.title, doc
%p= time_ago_in_words(doc.created_at)
%p= truncate(doc.content, length:50)

    = link_to "Create Doc", new_doc_path

Body:
When you supply content on the same line as a tag in Haml, you are saying "The content of this tag will only be whatever is in this line, and close the tag immediately".

So

%p hello

becomes

<p>hello</p>

In situations where you have more than one line for a tag, use a newline and indentation to indicate the content for that block:

%p
  Hello
  World

Which results in:

<p>Hello\nWorld</p>

You are trying to use both of them here. You are supplying the content for the short form tag, but also indenting as if you plan on continuing to add content to your p tag.

To fix this you need to use the multiline syntax, if that is your intent, or remove the indentation from your link_to:

- @docs.each do |doc|
  %h2= link_to doc.title, doc
  %p= time_ago_in_words(doc.created_at)
  %p
    = truncate(doc.content, length:50)
    = link_to "Create Doc", new_doc_path


问:
For a large project, what planning should be done before coding and how should it be approached?
What is your method of "mapping out" an idea before creating it?

Say I wanted to take on a big project, for example at the scale of a site like Facebook or MySpace.  What planning/design steps should I take before I start the actual work?

For example, should I map everything out page by page (their functionalities, data, etc.)?

答: I always start with the user interface design. I figure out what the user should be able to do and what controls I will give them to do it. Once I get that laid out in a way I like it, then I start with the code "wiring".</p>

OwnerDisplayName: sarmenhb

LastEditorDisplayName: Hanno Fietz

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: gnovice


问:
Postgres - get midnight from a given timestamp
I have three timestamptz columns: due_at, starts_at, and ends_at. I need to update starts_at and ends_at such that they will have the same date as due_at except the times will be 12:00 AM and 11:59 PM respectively.

UPDATE table SET starts_at = due_at;

答:
Consider:

```<code>update mytable set
    starts_at = date_trunc('day', due_at),
    ends_at   = date_trunc('day', due_at) + interval '1' day - interval '1' minute
</code>```

You could also phrase this as:

```<code>update mytable set
    starts_at = date_trunc('day', due_at),
    ends_at   = date_trunc('day', due_at) + interval '23 hours 59 minutes'
</code>```

Body:
Consider:

update mytable set
    starts_at = date_trunc('day', due_at),
    ends_at   = date_trunc('day', due_at) + interval '1' day - interval '1' minute

You could also phrase this as:

update mytable set
    starts_at = date_trunc('day', due_at),
    ends_at   = date_trunc('day', due_at) + interval '23 hours 59 minutes'


问:
Does anyone know how to fetch WASDE (World Agricultural supply and demand estimates) report fundamental data by using API in python or R?
https://usda.library.cornell.edu/apidoc/index.html The website has provided the API doc. Can somebody tell me the required steps to fetch the data either in R or Python..</p>

答:
Here's how you can do it in R.

First, create variables containing the email address and password you created when you signed up:

```<code>my_email    <- "Niket_Chauhan@somewhere.com"
my_password <- "Passw0rd!"
</code>```

You are going to need to send these inside a json string as a POST request to get an authorization code to use the service. We'll create the json now:

```<code>my_json <- paste0('{"auth": {"email":"', my_email,'","password":"', my_password, '"}}')
</code>```

Now we'll request an authorization token using httr::POST:

```<code>library(httr)

auth <- POST("https://usda.library.cornell.edu/user_token",
             body = my_json, encode = "raw",
             add_headers(`Content-Type` = "application/json"))
</code>```

If everything went well, auth now contains our authorization token. We will use this token inside an 'Authorization' header for every subsequent request to the server:

```<code>token <- add_headers("Authorization" = paste("Bearer", content(auth, "parsed")$jwt))
</code>```

So now we can just send http requests to the API using GET and POST. For most of these we can just use the url we want, and ensure we have included our header.

```<code>res <- GET("https://usda.library.cornell.edu/api/v1/agency/findAll", token)
</code>```

Here, res is an http response object, so we'll extract its contents as text to get our json string:

cat(content(res, "text"))
#> [{"id":"waob_agency","title":["World Agricultural Outlook Board"],
#> "acronym":["WAOB"],"contact_email":["oce@oce.usda.gov"],"contact_phone":
#> ["202-720-5447"],"location_city":["Washington"],"location_state":
#> ["DC"],"homepage_url":["http://www.usda.gov/oce/commodity/"]},
#> {"id":"ers_agency","title":["Economic Research Service"],"acronym":
#> ["ERS"],"contact_email":["ers@ers.usda.gov"],"contact_phone":
#> ["202-694-5139"],"location_city":["Washington"],"location_state":
#> ["DC"],"homepage_url":["http://www.ers.usda.gov/"]},
#> {"id":"nass_agency","title":["National Agricultural Statistics Service"],
#> "acronym":["NASS"],"contact_email":["nass@nass.usda.gov"],
#> "contact_phone":["800-727-9540"],"location_city":["Washington"],
#> "location_state":["DC"],"homepage_url":["http://www.nass.usda.gov/"]},
#> {"id":"fas_agency","title":["Foreign Agricultural Service"],"acronym":
#> ["FAS"],"contact_email":["fas@fas.usda.gov"],"location_city":
#> ["Washington"],"location_state":["DC"],"homepage_url":
#> ["http://www.fas.usda.gov/"]},{"id":"ams_agency","title":
#> ["Agricultural Marketing Service"],"acronym":["AMS"],"contact_email":
#> ["ams@ams.usda.gov"],"contact_phone":["202-720-8998"],"location_city":
#> ["Washington"],"location_state":["DC"],"homepage_url":
#> ["http://www.ams.usda.gov/"]}]
```

Body:
Here's how you can do it in R.

First, create variables containing the email address and password you created when you signed up:

my_email    <- "Niket_Chauhan@somewhere.com"
my_password <- "Passw0rd!"

You are going to need to send these inside a json string as a POST request to get an authorization code to use the service. We'll create the json now:

my_json <- paste0('{"auth": {"email":"', my_email,'","password":"', my_password, '"}}')

Now we'll request an authorization token using httr::POST:

library(httr)

auth <- POST("https://usda.library.cornell.edu/user_token",
             body = my_json, encode = "raw",
             add_headers(`Content-Type` = "application/json"))

If everything went well, auth now contains our authorization token. We will use this token inside an 'Authorization' header for every subsequent request to the server:

token <- add_headers("Authorization" = paste("Bearer", content(auth, "parsed")$jwt))

So now we can just send http requests to the API using GET and POST. For most of these we can just use the url we want, and ensure we have included our header.

res <- GET("https://usda.library.cornell.edu/api/v1/agency/findAll", token)

Here, res is an http response object, so we'll extract its contents as text to get our json string:

cat(content(res, "text"))
#> [{"id":"waob_agency","title":["World Agricultural Outlook Board"],
#> "acronym":["WAOB"],"contact_email":["oce@oce.usda.gov"],"contact_phone":
#> ["202-720-5447"],"location_city":["Washington"],"location_state":
#> ["DC"],"homepage_url":["http://www.usda.gov/oce/commodity/"]},
#> {"id":"ers_agency","title":["Economic Research Service"],"acronym":
#> ["ERS"],"contact_email":["ers@ers.usda.gov"],"contact_phone":
#> ["202-694-5139"],"location_city":["Washington"],"location_state":
#> ["DC"],"homepage_url":["http://www.ers.usda.gov/"]},
#> {"id":"nass_agency","title":["National Agricultural Statistics Service"],
#> "acronym":["NASS"],"contact_email":["nass@nass.usda.gov"],
#> "contact_phone":["800-727-9540"],"location_city":["Washington"],
#> "location_state":["DC"],"homepage_url":["http://www.nass.usda.gov/"]},
#> {"id":"fas_agency","title":["Foreign Agricultural Service"],"acronym":
#> ["FAS"],"contact_email":["fas@fas.usda.gov"],"location_city":
#> ["Washington"],"location_state":["DC"],"homepage_url":
#> ["http://www.fas.usda.gov/"]},{"id":"ams_agency","title":
#> ["Agricultural Marketing Service"],"acronym":["AMS"],"contact_email":
#> ["ams@ams.usda.gov"],"contact_phone":["202-720-8998"],"location_city":
#> ["Washington"],"location_state":["DC"],"homepage_url":
#> ["http://www.ams.usda.gov/"]}]


问:
Selecting multiple cells of special format on website and importing the result back to excel
I am new to Excel VBA. I have written some code with the help of online videos but I am stuck to resolve a problem of selecting two cells as Range values separated by commas. However, If I just use one of the selected cells, the compiling error does not occur.

```<code>Sub elevation_finder()
Dim elevation As Long
Dim ieobject As InternetExplorer
Dim htmlElement As IHTMLElement
Dim i As Integer

i = 1

Set ieobject = New InternetExplorer
ieobject.Visible = True
ieobject.navigate "https://www.freemaptools.com/elevation-finder.htm"

Application.Wait Now + TimeValue("00:00:05")

ieobject.document.getElementById("locationSearchTextBox").Value = ActiveWorkbook.Sheets("Header").Range("C2").Value

End Sub
</code>```

My next step after entering the numbers (coordinates as integers) is to import the result back into new column.

Help and suggestion is appreciated to improve the code in automating the coordinates to find respective elevations.
enter image description here

Kind regards.

答:
Should be able to use something like:</p>

```<code>With ActiveWorkbook.Sheets("Header")
    ieobject.document.getElementById("locationSearchTextBox").Value = _
           .Range("B2").Value & "," & .Range("C2").Value
End with
</code>```

Body:
I am new to Excel VBA. I have written some code with the help of online videos but I am stuck to resolve a problem of selecting two cells as Range values separated by commas. However, If I just use one of the selected cells, the compiling error does not occur.

Sub elevation_finder()
Dim elevation As Long
Dim ieobject As InternetExplorer
Dim htmlElement As IHTMLElement
Dim i As Integer

i = 1

Set ieobject = New InternetExplorer
ieobject.Visible = True
ieobject.navigate "https://www.freemaptools.com/elevation-finder.htm"

Application.Wait Now + TimeValue("00:00:05")

ieobject.document.getElementById("locationSearchTextBox").Value = ActiveWorkbook.Sheets("Header").Range("C2").Value

End Sub

My next step after entering the numbers (coordinates as integers) is to import the result back into new column.

Help and suggestion is appreciated to improve the code in automating the coordinates to find respective elevations.
enter image description here

Kind regards.

Body:
Should be able to use something like:

With ActiveWorkbook.Sheets("Header")
    ieobject.document.getElementById("locationSearchTextBox").Value = _
           .Range("B2").Value & "," & .Range("C2").Value
End with