问:
How to specify the delimiter when importing CSV files via OLEDB in C#
I need to perform a complex import in a Microsoft SQL Server 2000.

Since doing it in a DTS is too complicated, I'm trying to do it with a little C# program, but I'm having problems when I need to import a CSV files: this file is using semicolons as field delimiters instead of commas and I can't get the .NET's OLE DB provider to recognize it.

I already found various "solutions" on the net like using Extended Properties="Text; Format=Delimited" or ``Extended Properties="Text; Format=Delimited(;)"in the connection string or using aschema.ini` file to no avail.

This is the actual code I'm using:

```<code>DataTable Table = new DataTable();

using (OleDbConnection Connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Extended Properties=\"Text;HDR=Yes;Format=Delimited\""))
{
    Connection.Open();

    using (OleDbCommand Command = Connection.CreateCommand())
    {
        Command.CommandText = "select [Field 1], [Field 2] from [file.csv]";

        using (OleDbDataAdapter Adapter = new OleDbDataAdapter(Command))
        {
            Adapter.Fill(Table);
        }
    }
}

using (SqlConnection Connection = new SqlConnection("Data Source=server; Initial Catalog=database; User Id=user; Password=password;"))
{
    Connection.Open();

    using (SqlCommand Command = Connection.CreateCommand())
    {
        Command.CommandText = "insert into [table] ([field_1], [field_2], ...) values (@field_1, @field_2, ...)";

        Command.Parameters.Add("field_1", SqlDbType.Date, 0, "Field 1");
        Command.Parameters.Add("field_2", SqlDbType.VarChar, 100, "Field 2");
        ...

        using (SqlDataAdapter Adapter = new SqlDataAdapter())
        {
            Adapter.InsertCommand = Command;

            Adapter.Update(Table);
        }
    }
}
</code>```

Any ideas on how to achieve using the semicolon as the field separator without relying on external libriaries?

Notes:

The "without relying on external libriaries" bit is because I need to import the file directly into the database and no library I found can do this (they return strings), and our PHB won't drop even a penny for a commercial solution.

I know I can import the file via a DTS, but I need to perform complex branching on the workflow and file alterations before and after the import, and that would result in jumping in and out of the DTS.

Doing everything inside the DTS would not be practical for me, as I'm not that skilled in ActiveX and VBScript coding.

Thanks in advance, Andrea.

Edit 1 - @andyb:
Test program code for schema.ini approach:

```<code>String ConnectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Extended Properties=\"Text\"", Environment.CurrentDirectory);

DataTable Table = new DataTable();

using (OleDbConnection Connection = new OleDbConnection(ConnectionString))
{
    Connection.Open();

    using (OleDbCommand Command = Connection.CreateCommand())
    {
        Command.CommandText = "select * from [file.csv]";

        using (OleDbDataAdapter Adapter = new OleDbDataAdapter(Command))
        {
            Adapter.Fill(Table);
        }
    }
}
</code>```

答:
The schema.ini file has to be saved in Unicode or ANSI, not as UTF-8.

Your data file must also be saved as Unicode not UTF-8.

Body:
I need to perform a complex import in a Microsoft SQL Server 2000.

Since doing it in a DTS is too complicated, I'm trying to do it with a little C# program, but I'm having problems when I need to import a CSV files: this file is using semicolons as field delimiters instead of commas and I can't get the .NET's OLE DB provider to recognize it.

I already found various "solutions" on the net like using Extended Properties="Text; Format=Delimited" or ``Extended Properties="Text; Format=Delimited(;)"in the connection string or using aschema.ini` file to no avail.

This is the actual code I'm using:

DataTable Table = new DataTable();

using (OleDbConnection Connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Extended Properties=\"Text;HDR=Yes;Format=Delimited\""))
{
    Connection.Open();

    using (OleDbCommand Command = Connection.CreateCommand())
    {
        Command.CommandText = "select [Field 1], [Field 2] from [file.csv]";

        using (OleDbDataAdapter Adapter = new OleDbDataAdapter(Command))
        {
            Adapter.Fill(Table);
        }
    }
}

using (SqlConnection Connection = new SqlConnection("Data Source=server; Initial Catalog=database; User Id=user; Password=password;"))
{
    Connection.Open();

    using (SqlCommand Command = Connection.CreateCommand())
    {
        Command.CommandText = "insert into [table] ([field_1], [field_2], ...) values (@field_1, @field_2, ...)";

        Command.Parameters.Add("field_1", SqlDbType.Date, 0, "Field 1");
        Command.Parameters.Add("field_2", SqlDbType.VarChar, 100, "Field 2");
        ...

        using (SqlDataAdapter Adapter = new SqlDataAdapter())
        {
            Adapter.InsertCommand = Command;

            Adapter.Update(Table);
        }
    }
}

Any ideas on how to achieve using the semicolon as the field separator without relying on external libriaries?

Notes:

The "without relying on external libriaries" bit is because I need to import the file directly into the database and no library I found can do this (they return strings), and our PHB won't drop even a penny for a commercial solution.

I know I can import the file via a DTS, but I need to perform complex branching on the workflow and file alterations before and after the import, and that would result in jumping in and out of the DTS.

Doing everything inside the DTS would not be practical for me, as I'm not that skilled in ActiveX and VBScript coding.

Thanks in advance, Andrea.

Edit 1 - @andyb:
Test program code for schema.ini approach:

String ConnectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Extended Properties=\"Text\"", Environment.CurrentDirectory);

DataTable Table = new DataTable();

using (OleDbConnection Connection = new OleDbConnection(ConnectionString))
{
    Connection.Open();

    using (OleDbCommand Command = Connection.CreateCommand())
    {
        Command.CommandText = "select * from [file.csv]";

        using (OleDbDataAdapter Adapter = new OleDbDataAdapter(Command))
        {
            Adapter.Fill(Table);
        }
    }
}


来源: stackexchange

问:
execute a command with each list from a text file
I would like to execute a command with each list from a text file. I tried doing this code but it is not giving me any output. Can you help me? Thank you!

```<code>for i in $(cat list_of_text.txt)
do
    commandtool some_input_file $i> new_"$i".fa

    cat > final.list
    echo -e "new_"$i"\t+" >> final.list
done
</code>```

list_of_text.txt looks like this

```<code>nameabc
namedef
nameghi
namejkl
</code>```

while final.list looks like this

```<code>new_nameabc.fa  +
new_namedef.fa  +
new_nameghi.fa  +
new_namejkl.fa  +
</code>```

In summary
the long version of the code is like this and I'm trying to make a shortcut:

```<code>commandtool some_input_file nameabc> new_nameabc.fa
commandtool some_input_file namedef> new_namedef.fa
commandtool some_input_file nameghi> new_nameghi.fa
commandtool some_input_file namejkl> new_namejkl.fa

echo -e "new_nameabc.fa\t+" > final.list
echo -e "new_namedef.fa\t+" >> final.list
echo -e "new_nameghi.fa\t+" >> final.list
echo -e "new_namejkl.fa\t+" >> final.list
</code>```

Edit: It is working now. I just replaced cat > final.list to echo > final.list and moved it at the beginning as suggested in the answer.

答:
Perhaps something like this to calculate the output filename only once and to use printf instead of echo -e for portability

```<code>#!/bin/bash
true > final.list
for i in $(< list_of_text.txt)
do
    out="new_${i}.fa"
    commandtool some_input_file "$i" > "$out"
    printf '%s\t+\n' "$out" >> final.list
done
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to execute a command with each list from a text file. I tried doing this code but it is not giving me any output. Can you help me? Thank you!

for i in $(cat list_of_text.txt)
do
    commandtool some_input_file $i> new_"$i".fa

    cat > final.list
    echo -e "new_"$i"\t+" >> final.list
done

list_of_text.txt looks like this

nameabc
namedef
nameghi
namejkl

while final.list looks like this

new_nameabc.fa  +
new_namedef.fa  +
new_nameghi.fa  +
new_namejkl.fa  +

In summary
the long version of the code is like this and I'm trying to make a shortcut:

commandtool some_input_file nameabc> new_nameabc.fa
commandtool some_input_file namedef> new_namedef.fa
commandtool some_input_file nameghi> new_nameghi.fa
commandtool some_input_file namejkl> new_namejkl.fa

echo -e "new_nameabc.fa\t+" > final.list
echo -e "new_namedef.fa\t+" >> final.list
echo -e "new_nameghi.fa\t+" >> final.list
echo -e "new_namejkl.fa\t+" >> final.list

Edit: It is working now. I just replaced cat > final.list to echo > final.list and moved it at the beginning as suggested in the answer.

Body:
Perhaps something like this to calculate the output filename only once and to use printf instead of echo -e for portability

#!/bin/bash
true > final.list
for i in $(< list_of_text.txt)
do
    out="new_${i}.fa"
    commandtool some_input_file "$i" > "$out"
    printf '%s\t+\n' "$out" >> final.list
done


问:
Nodejs module.exports - Change variable value from other js file
I export a variable value from file1.js to file2.js and it works okay, but if I want to change the value of that variable from file2.js in file1.js it doesn't work.
Does this work for reading only, if so how can I connect these two files that I can change value from one to another file and vice versa?

Update:
If in file1.js I have let count = 0, and from file2.js I want to change the count value to count = 2, how do I change it cause it doesn't change for file1..

Update 2 - SOLVED:

file1.js

```<code>let var1 = 55 ;
    function testFunk(reVar, i){
       console.log(var1, 'file1')
      if( reVar == 'read' ){
        return var1
      } else if( reVar == 'change' ){
        console.log(' change ')
        var1 = var1 + i ;
        return var1
      }
    }

    module.exports = {  testFunk , var1 }
</code>```

file2.js

```<code> var file1 = require("./file1.js") ;
let var1 ;

testFunk1( )
function testFunk1( ){
   setTimeout(() => {
     var1 = file1.testFunk( 'read') ;
     testFunk1( )
    }, 20);
}

 setInterval(() => {
    file1.testFunk('change', 1 ) ;
   console.log(  var1 , 'file1'  ) ;
  }, 1000);
</code>```

This way I can read variable values from file1, change them, then read the changed value again. This is what I asked, hope you understand now. If you have any other better solution please show it..

答:
In node js, you can read and change variables declared in other js files by using the process object. It works similar to the window object in the browser.

let us look at an example below

file1.js

```<code>module.exports = process.myGlobals = {name: "prince david", age: 45, married: true}
</code>```

file2.js
we can access the variables declared in file1.js in file2.js as follows

```<code>let globals = require("./file1.js")

console.log(globals) // the output will be {name: "prince david", age: 45, married: true}
console.log(globals.name) // the output will be prince, david
console.log(globals.age) // the output will be, 45
// to change any of the properties which was defined in file1.js, we can do the following

globals.name = "some other name"
console.log(globals.name) // the output will be, some other name
globals = {programmer: true}
console.log(globals) // the output will be {programmer: true}
</code>```

All of this is working because when we export a variable declared using the process object, we even pass its reference so if we change that variable in any other files, its initial value will also change

Body:
I export a variable value from file1.js to file2.js and it works okay, but if I want to change the value of that variable from file2.js in file1.js it doesn't work.
Does this work for reading only, if so how can I connect these two files that I can change value from one to another file and vice versa?

Update:
If in file1.js I have let count = 0, and from file2.js I want to change the count value to count = 2, how do I change it cause it doesn't change for file1..

Update 2 - SOLVED:

file1.js

let var1 = 55 ;
    function testFunk(reVar, i){
       console.log(var1, 'file1')
      if( reVar == 'read' ){
        return var1
      } else if( reVar == 'change' ){
        console.log(' change ')
        var1 = var1 + i ;
        return var1
      }
    }

    module.exports = {  testFunk , var1 }

file2.js

 var file1 = require("./file1.js") ;
let var1 ;

testFunk1( )
function testFunk1( ){
   setTimeout(() => {
     var1 = file1.testFunk( 'read') ;
     testFunk1( )
    }, 20);
}

 setInterval(() => {
    file1.testFunk('change', 1 ) ;
   console.log(  var1 , 'file1'  ) ;
  }, 1000);

This way I can read variable values from file1, change them, then read the changed value again. This is what I asked, hope you understand now. If you have any other better solution please show it..

Body:
In node js, you can read and change variables declared in other js files by using the process object. It works similar to the window object in the browser.

let us look at an example below

file1.js

module.exports = process.myGlobals = {name: "prince david", age: 45, married: true}

file2.js
we can access the variables declared in file1.js in file2.js as follows

let globals = require("./file1.js")

console.log(globals) // the output will be {name: "prince david", age: 45, married: true}
console.log(globals.name) // the output will be prince, david
console.log(globals.age) // the output will be, 45
// to change any of the properties which was defined in file1.js, we can do the following

globals.name = "some other name"
console.log(globals.name) // the output will be, some other name
globals = {programmer: true}
console.log(globals) // the output will be {programmer: true}

All of this is working because when we export a variable declared using the process object, we even pass its reference so if we change that variable in any other files, its initial value will also change


问:
what is wrong with python my python code in while loop?
I don't know what is the error of my code can anyone help  me to fix this code.</p>
```<code>age = ""
while int(len(age)) == 0:
    age = int(input("Enter your age: "))
print("Your age is " + age)
</code>```

答:
In Python, "" and 0 (and values like None and empty containers) are considered "falsey". Not necessarily the same thing as False but logically treated like False.

So you can simplify your while loop:

age = ""
while not age:
    age = input("Enter your age: ")
print("Your age is " + age)
```

Body:
I don't know what is the error of my code can anyone help  me to fix this code.

age = ""
while int(len(age)) == 0:
    age = int(input("Enter your age: "))
print("Your age is " + age)


问:
How to compare two tables having record type column in BigQuery
I have two nested tables one is source and another is target table. I wanted to compare nested columns of source and target table. I am comparing two tables to check weather data is being updated in source table or not. Is there any sql in BigQuery to achieve the same?

Here are my approaches which I was previously doing to compare two tables with nested record:

1. This is the first approach:

```<code>SELECT to_json_string(info) FROM database.nested_table_source
except distinct
SELECT to_json_string(info) FROM nested_table_target
</code>```

to_json_string() is not working, since this function returns different sequence of source rows and target rows sometimes, even though data is same in both tables, it results out different records.

2. This is the second approach:

```<code>select name
from dataset.nested_table_source a
join dataset.nested_table_target b
using(name)
where
a.name!=b.name  and
(select string_agg(format('%t', s) order by key) from a.info s)
!= (select string_agg(format('%t', s) order by key ) from b.info s)
</code>```

In this approach I am using string_agg function to compare two nested records. But I am not sure if that is the correct way to compare record fields.

What should I do in this case?

答:
Here is an approach in which you basically stringify an ordered set of objects (or the info column in your tables), and then compare them against each other.

Here is an example with some dummy data:

```<code>with source_data as (
    select
    "VICTOR" as name,
     array[
        struct("A" as key, 3 as value),
        struct("B" as key, 5 as value)
    ] as info

    union all

    select
    "MAX" as name,
     array[
        struct("A" as key, 0 as value),
        struct("B" as key, 1 as value)
    ] as info

    union all

    select
    "SAIF" as name,
     array[
        struct("A" as key, 0 as value),
        struct("B" as key, 1 as value)
    ] as info
),
target_data as (
    select
    "VICTOR" as name,
     array[
        struct("A" as key, 3 as value),
        struct("B" as key, 15 as value)
    ] as info

    union all

    select
    "MAX" as name,
     array[
        struct("A" as key, 0 as value),
        struct("B" as key, 1 as value)
    ] as info
)

select name, stringified_source_set as info from (
    select
        s.name,
        array_to_string(array(select concat(cast(x.key as string), '|', cast(x.value as string)) from unnest(t.info) as x order by x.key), '|') AS stringified_target_set,
        array_to_string(array(select concat(cast(x.key as string), '|', cast(x.value as string)) from unnest(s.info) as x order by x.key), '|') AS stringified_source_set
    from source_data s
    left join target_data t on t.name = s.name
)
where (stringified_source_set != stringified_target_set) or (name is null)

</code>```

Note that the above approach does achieve both "horizontal comparison" (i.e. comparing both info objects) and "vertical comparison" (i.e. comparing missing entries in the target table which exist in the source table).

Body:
I have two nested tables one is source and another is target table. I wanted to compare nested columns of source and target table. I am comparing two tables to check weather data is being updated in source table or not. Is there any sql in BigQuery to achieve the same?

Here are my approaches which I was previously doing to compare two tables with nested record:

1. This is the first approach:

SELECT to_json_string(info) FROM database.nested_table_source
except distinct
SELECT to_json_string(info) FROM nested_table_target

to_json_string() is not working, since this function returns different sequence of source rows and target rows sometimes, even though data is same in both tables, it results out different records.

2. This is the second approach:

select name
from dataset.nested_table_source a
join dataset.nested_table_target b
using(name)
where
a.name!=b.name  and
(select string_agg(format('%t', s) order by key) from a.info s)
!= (select string_agg(format('%t', s) order by key ) from b.info s)

In this approach I am using string_agg function to compare two nested records. But I am not sure if that is the correct way to compare record fields.

What should I do in this case?

Body:
Here is an approach in which you basically stringify an ordered set of objects (or the info column in your tables), and then compare them against each other.

Here is an example with some dummy data:

with source_data as (
    select
    "VICTOR" as name,
     array[
        struct("A" as key, 3 as value),
        struct("B" as key, 5 as value)
    ] as info

    union all

    select
    "MAX" as name,
     array[
        struct("A" as key, 0 as value),
        struct("B" as key, 1 as value)
    ] as info

    union all

    select
    "SAIF" as name,
     array[
        struct("A" as key, 0 as value),
        struct("B" as key, 1 as value)
    ] as info
),
target_data as (
    select
    "VICTOR" as name,
     array[
        struct("A" as key, 3 as value),
        struct("B" as key, 15 as value)
    ] as info

    union all

    select
    "MAX" as name,
     array[
        struct("A" as key, 0 as value),
        struct("B" as key, 1 as value)
    ] as info
)

select name, stringified_source_set as info from (
    select
        s.name,
        array_to_string(array(select concat(cast(x.key as string), '|', cast(x.value as string)) from unnest(t.info) as x order by x.key), '|') AS stringified_target_set,
        array_to_string(array(select concat(cast(x.key as string), '|', cast(x.value as string)) from unnest(s.info) as x order by x.key), '|') AS stringified_source_set
    from source_data s
    left join target_data t on t.name = s.name
)
where (stringified_source_set != stringified_target_set) or (name is null)

Note that the above approach does achieve both "horizontal comparison" (i.e. comparing both info objects) and "vertical comparison" (i.e. comparing missing entries in the target table which exist in the source table).


问:
Fitbit App sideload fails with Internal error
I am trying to develop an app for Fitbit Versa 3. I am able to connect from my VS code to Fitbit OS simulator, but when I try to install the app using the following two commands:

```<code>npx fitbit
bi
</code>```

I get an error

```<code>Loaded appID:c25295d1-e4d6-43e5-a93a-b8d3bef90830 buildID:0x097ede643c977ca5
App requires a device, connecting...
Auto-connecting only known device: Versa 3 Simulator
App requires a phone, connecting...
Auto-connecting only known phone: Simulator
Sideloading app: starting...
Install failed: Internal Error
</code>```

There are no details on what the Internal error is for. Has someone encountered this error before?

Things I have tried:

Restarting Fitbit OS Simulator and VS code

Generate a new App Id for the Fitbit app

Ensuring that both the Fitbit OS simulator and VS code are connected to same Fitbit account

答:
See: https://community.fitbit.com/t5/SDK-Development/Simulator-SSL-Problem/m-p/5003032/highlight/true#M16148

It is a simulation problem, I believe. You have to delete the cacert.pem in the simulator, and replace with a new and updated version of cacert.pem in the simulator folder for Versa 3 . Click on this forum discussion to find the cacert.pem download and instructions. The simulator has been broken for a while as announced in November on the Fitbit Development Twitter.

Body:
I am trying to develop an app for Fitbit Versa 3. I am able to connect from my VS code to Fitbit OS simulator, but when I try to install the app using the following two commands:

npx fitbit
bi

I get an error

Loaded appID:c25295d1-e4d6-43e5-a93a-b8d3bef90830 buildID:0x097ede643c977ca5
App requires a device, connecting...
Auto-connecting only known device: Versa 3 Simulator
App requires a phone, connecting...
Auto-connecting only known phone: Simulator
Sideloading app: starting...
Install failed: Internal Error

There are no details on what the Internal error is for. Has someone encountered this error before?

Things I have tried:

Restarting Fitbit OS Simulator and VS code

Generate a new App Id for the Fitbit app

Ensuring that both the Fitbit OS simulator and VS code are connected to same Fitbit account


问:
How to build sqlite3.dll with the command line in Windows with Visual C++?
The source sqlite3.c has very few if at all, _declspec(dllexport) functions thus building it to a DLL in Windows produces an empty DLL!

My cmd line is:

cl sqlite3.c -link -dll -out:sqlite3.dll

where is the export  file? How do I export the functions to the DLL?

Regards,
Juan

答:
Just define the SQLITE_API preprocessing symbol with the value __declspec(dllexport), by adding the appropriate option to the command line (before the other options):

cl sqlite3.c -DSQLITE_API=__declspec(dllexport) -link -dll -out:sqlite3.dll


问:
DB Transaction not rolling back [Laravel 7.3]
I'm running Laravel 7.3 on an app, and I feel like this is potentially a Laravel framework bug because I'm racking my brain on this...

I've got a DB Transaction with model saves within it, all within a try/catch but it's still saving the model updates, and I just can't see why because it hits the catch() and the response json hits, so I assume the rollback is running, yet the database is still updating.

```<code>try {
    DB::beginTransaction();

    foreach ($models as $model) {
        $model->rungroup_id = $rungroup->id;
        $model->zone_id = $rungroup->getFirstZoneID();
        $model->delivery_status = 'next';
        $model->save();
    }

    DB::commit();

    return response()->json(['status' => 'success']);
} catch (Throwable | Exception $e) {
    DB::rollBack();

    Log::error($e);

    return response()->json([
        'status' => 'error',
        'message' => $e->getMessage(),
    ], 500);
}
</code>```

Any ideas?

答: After updating Laravel and many other attempts at rewriting the code to see if I made a silly mistake, I ended up finding that the person who created the database tables set the Table engine to MyISAM rather than InnoDB which is required for the DB transactions... I wish Laravel threw an error so I would've known, but this has definitely saved my sanity, and hope it helps others.

Body:
I'm running Laravel 7.3 on an app, and I feel like this is potentially a Laravel framework bug because I'm racking my brain on this...

I've got a DB Transaction with model saves within it, all within a try/catch but it's still saving the model updates, and I just can't see why because it hits the catch() and the response json hits, so I assume the rollback is running, yet the database is still updating.

try {
    DB::beginTransaction();

    foreach ($models as $model) {
        $model->rungroup_id = $rungroup->id;
        $model->zone_id = $rungroup->getFirstZoneID();
        $model->delivery_status = 'next';
        $model->save();
    }

    DB::commit();

    return response()->json(['status' => 'success']);
} catch (Throwable | Exception $e) {
    DB::rollBack();

    Log::error($e);

    return response()->json([
        'status' => 'error',
        'message' => $e->getMessage(),
    ], 500);
}

Any ideas?


问:
JavaScript Super.prop in object literals
```<code>let proto = {
    whoami() { console.log('I am proto'); }
};
let obj = {
    whoami() {
        Object.getPrototypeOf( obj ).whoami.call( this ); // super.whoami();
        console.log('I am obj');
    }
};
Object.setPrototypeOf( obj, proto );
</code>```

This code lets obj inherit the proto.
I got confused about this code Object.getPrototypeOf( obj ).whoami.call( this ); which is equvalent to super.whoami(). Can anyone explain how this code works?

答:
You may want to first read about the following topics in my answer below before skipping to the explanation:

Prototypes

(Prototype-chain)

Property shadowing

Functions

(Pure and impure functions)

Closures

this context

Prototypes

Prototype-chain

In JavaScript, objects can have prototypes. An object inherits all the properties of its prototype. Since prototypes themselves are objects, they too can have prototypes. This is called the prototype-chain.

Accessing an object's property will cause JS to first try to find it on the object itself, and then on each of its prototypes consecutively.

Example

Let's define both a person and their prototype human:

const human = { isSelfAware: true };
const person = { name: "john" };
Object.setPrototypeOf(person, human);
```
<p>If we try to access <code>person.name</code>, then JS will return the property of <code>person</code> because it has this property defined.</p>
<p>If we however try to access <code>person.isSelfAware</code>, JS will return the property of <code>human</code> because <code>person</code> doesn't have the property defined but its prototype does.</p>
<h2>Property shadowing</h2>
<p>If an object has a similarly named property as one of its prototypes, the prototype's property is shadowed, because JS will return the earliest defined property.</p>
<p>Shadowing is useful because objects can define different property values without affecting the prototype.</p>
<h3>Example</h3>
<pre class="lang-js prettyprint-override"><code>const lightBulbProto = { serialNumber: 12345, isFunctional: true };
const oldLightBulb = { isFunctional: false };
const newLightBulb = {};
Object.setPrototypeOf(oldLightBulb , lightBulbProto);
Object.setPrototypeOf(newLightBulb, lightBulbProto);
</code>```

By default, all light bulbs are functional. But now we defined an old light bulb to be non-functional (isFunctional: false).

This doesn't affect newLightBulb because we didn't define the functionality on the prototype, but on the specific object oldLightBulb.

Functions

First off: By "function" I only mean functions and function expressions function() {}. Method definitions are syntactic sugar for function expressions, so they are considered the same. Arrow function expressions () => {} are excluded.

Types of functions

If a function is deterministic (same input results in same output) and self-enclosed (no side-effects), it is a pure function; otherwise it is an impure function.

Pure functions are usually easy to understand and debug, since all relevant code is contained in its definition.

const array = [];
function addToArray(o) { // Impure function
  array.push(o);
}

function add(a, b) { // Pure function
  return a + b;
}
```
<h2>Scope and closures</h2>
<p>JS tries to bundle your function with the smallest possible scope. If your function uses variables outside of its own scope, a closure is created at function creation during runtime. This means, the surrounding scope is kept alive for as long as the dependent function is accessible.</p>
<p>Closures aren't inherently bad, but may be confusing or cause of a memory-leak.</p>
<h3>Example</h3>
<p><code>createGet</code> initializes <code>object</code> in its scope, and then returns a getter for the object:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function createGet() {
  const object = {};
  return function() {
    return object;
  }
}

let get1 = createGet();
let get2 = createGet();

// They are independent!
get1().name = "get1";
get2().number = 2;

console.log(get1()); // { "name": "get1" }
console.log(get2()); // { "number": 2 }

// Release the closures!
get1 = undefined;
get2 = undefined;</code>```

The code looks as if each getter function returns the same object. This is not true, because every call of createGet initializes a different object each time. Because of this, each getter function refers to a different object, making each getter independent.

Since closures may bundle a different scope at every creation, they may be a memory-leak. Only when no further reference to a closure exists, it may be garbage-collected. In our example we do this with these lines:

get1 = undefined;
get2 = undefined;
```
<h2>Strict-mode</h2>
<p>Apart from the default "sloppy mode", JS also features a strict mode.</p>
<h2><code>this</code> context</h2>
<p>The current context is effectively the value of <code>this</code> in the current scope.</p>
<p>The context of a function is determined by how the function is called. A function may be called standalone (e.g. <code>aFunc()</code>) or as a method (e.g. <code>obj.aMethod()</code>).</p>
<p>If a function is called on its own, it inherits the surrounding context. If there is no surrounding function context, the surrounding context will either be <code>globalThis</code> in "sloppy mode", or be <code>undefined</code> in strict mode.</p>
<p>If the function is called as a method <code>obj.aMethod()</code>, <code>this</code> will refer to <code>obj</code>.</p>
<p>Additionally, the first argument of the functions <code>Function.prototype.bind</code>, <code>Function.prototype.call</code> and <code>Function.prototype.apply</code> can specify the context of the underlying function.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log("Global context:");
(function() {
  console.log("- Sloppy: this == globalThis? " + (this === globalThis));
  // In browsers: globalThis == window
})();
(function() {
  "use strict";
  console.log("- Strict: this == undefined? " + (this === undefined));
})();

const compareThis = function(o) {
  return this === o;
};
const obj = { compareThis };

console.log("As function:");
console.log("- Default: this == obj? " + compareThis(obj));
console.log("- With call(obj): this == obj? " + compareThis.call(obj, obj));

console.log("As method:");
console.log("- Default: this == obj? " + obj.compareThis(obj));
console.log("- With call(undefined): this == obj? " + obj.compareThis.call(undefined, obj));</code>```

.as-console-wrapper{max-height:unset !important}```

Finally: The explanation

First, two objects (obj and proto) are initialized. proto will be the prototype of obj.

Because both objects have the property whoami defined, the prototype's property will be shadowed. Since we still want to access the prototype's property, we have to access it directly. To do this, we first get the prototype of obj (Object.getPrototypeOf(obj), or "super"), and then access its property (.whoami, or "super.whoami").

Since whoami was originally called on obj, it would make sense to use obj as the context. For this reason, we call whoami.call(this) (with this equal to obj; effectively "super.whoami()") on the prototype's whoami method, because if we didn't the method would use the prototype as its context.

Because obj is part of the surrounding lexical scope instead of the scope of obj.whoami, whoami creates a closure because of it using the identifier obj in Object.getPrototypeOf(obj). Ideally we would get the prototype using this instead, to not have an unnecessary closure: Object.getPrototypeOf(this).

Body:
let proto = {
    whoami() { console.log('I am proto'); }
};
let obj = {
    whoami() {
        Object.getPrototypeOf( obj ).whoami.call( this ); // super.whoami();
        console.log('I am obj');
    }
};
Object.setPrototypeOf( obj, proto );

This code lets obj inherit the proto.
I got confused about this code Object.getPrototypeOf( obj ).whoami.call( this ); which is equvalent to super.whoami(). Can anyone explain how this code works?

Body:
You may want to first read about the following topics in my answer below before skipping to the explanation:

Prototypes

(Prototype-chain)

Property shadowing

Functions

(Pure and impure functions)

Closures

this context

Prototypes

Prototype-chain

In JavaScript, objects can have prototypes. An object inherits all the properties of its prototype. Since prototypes themselves are objects, they too can have prototypes. This is called the prototype-chain.

Accessing an object's property will cause JS to first try to find it on the object itself, and then on each of its prototypes consecutively.

Example

Let's define both a person and their prototype human:

const human = { isSelfAware: true };
const person = { name: "john" };
Object.setPrototypeOf(person, human);

If we try to access person.name, then JS will return the property of person because it has this property defined.

If we however try to access person.isSelfAware, JS will return the property of human because person doesn't have the property defined but its prototype does.

Property shadowing

If an object has a similarly named property as one of its prototypes, the prototype's property is shadowed, because JS will return the earliest defined property.

Shadowing is useful because objects can define different property values without affecting the prototype.

Example

const lightBulbProto = { serialNumber: 12345, isFunctional: true };
const oldLightBulb = { isFunctional: false };
const newLightBulb = {};
Object.setPrototypeOf(oldLightBulb , lightBulbProto);
Object.setPrototypeOf(newLightBulb, lightBulbProto);

By default, all light bulbs are functional. But now we defined an old light bulb to be non-functional (isFunctional: false).

This doesn't affect newLightBulb because we didn't define the functionality on the prototype, but on the specific object oldLightBulb.

Functions

First off: By "function" I only mean functions and function expressions function() {}. Method definitions are syntactic sugar for function expressions, so they are considered the same. Arrow function expressions () => {} are excluded.

Types of functions

If a function is deterministic (same input results in same output) and self-enclosed (no side-effects), it is a pure function; otherwise it is an impure function.

Pure functions are usually easy to understand and debug, since all relevant code is contained in its definition.

const array = [];
function addToArray(o) { // Impure function
  array.push(o);
}

function add(a, b) { // Pure function
  return a + b;
}

Scope and closures

JS tries to bundle your function with the smallest possible scope. If your function uses variables outside of its own scope, a closure is created at function creation during runtime. This means, the surrounding scope is kept alive for as long as the dependent function is accessible.

Closures aren't inherently bad, but may be confusing or cause of a memory-leak.

Example

createGet initializes object in its scope, and then returns a getter for the object:

function createGet() {
  const object = {};
  return function() {
    return object;
  }
}

let get1 = createGet();
let get2 = createGet();

// They are independent!
get1().name = "get1";
get2().number = 2;

console.log(get1()); // { "name": "get1" }
console.log(get2()); // { "number": 2 }

// Release the closures!
get1 = undefined;
get2 = undefined;

The code looks as if each getter function returns the same object. This is not true, because every call of createGet initializes a different object each time. Because of this, each getter function refers to a different object, making each getter independent.

Since closures may bundle a different scope at every creation, they may be a memory-leak. Only when no further reference to a closure exists, it may be garbage-collected. In our example we do this with these lines:

get1 = undefined;
get2 = undefined;

Strict-mode

Apart from the default "sloppy mode", JS also features a strict mode.

this context

The current context is effectively the value of this in the current scope.

The context of a function is determined by how the function is called. A function may be called standalone (e.g. aFunc()) or as a method (e.g. obj.aMethod()).

If a function is called on its own, it inherits the surrounding context. If there is no surrounding function context, the surrounding context will either be globalThis in "sloppy mode", or be undefined in strict mode.

If the function is called as a method obj.aMethod(), this will refer to obj.

Additionally, the first argument of the functions Function.prototype.bind, Function.prototype.call and Function.prototype.apply can specify the context of the underlying function.

console.log("Global context:");
(function() {
  console.log("- Sloppy: this == globalThis? " + (this === globalThis));
  // In browsers: globalThis == window
})();
(function() {
  "use strict";
  console.log("- Strict: this == undefined? " + (this === undefined));
})();

const compareThis = function(o) {
  return this === o;
};
const obj = { compareThis };

console.log("As function:");
console.log("- Default: this == obj? " + compareThis(obj));
console.log("- With call(obj): this == obj? " + compareThis.call(obj, obj));

console.log("As method:");
console.log("- Default: this == obj? " + obj.compareThis(obj));
console.log("- With call(undefined): this == obj? " + obj.compareThis.call(undefined, obj));

.as-console-wrapper{max-height:unset !important}

Finally: The explanation

First, two objects (obj and proto) are initialized. proto will be the prototype of obj.

Because both objects have the property whoami defined, the prototype's property will be shadowed. Since we still want to access the prototype's property, we have to access it directly. To do this, we first get the prototype of obj (Object.getPrototypeOf(obj), or "super"), and then access its property (.whoami, or "super.whoami").

Since whoami was originally called on obj, it would make sense to use obj as the context. For this reason, we call whoami.call(this) (with this equal to obj; effectively "super.whoami()") on the prototype's whoami method, because if we didn't the method would use the prototype as its context.

Because obj is part of the surrounding lexical scope instead of the scope of obj.whoami, whoami creates a closure because of it using the identifier obj in Object.getPrototypeOf(obj). Ideally we would get the prototype using this instead, to not have an unnecessary closure: Object.getPrototypeOf(this).


问:
numpy vectorization(accumulate variable)
I have a dataframe.
Witch contain a few columns. It's look like this:

A
B
C
D

1
10
a
Nan

2
11
b
Nan

3
12
c
Nan

So if I have 'b' in column C, I should do A+B.
In other cases A*B.
But with that I have variable that accumulate value(You will see code and it will be cleare).
So I write this code

```<code>z = 0
for i, row in df.iterrows():
    a = df['A']
    b = df['B']
    c = df['C']
    if c == 'b':
        d = a + b + z
        z = z + 2
    else:
        d = a*b
    df.at[i, 'D'] = d
</code>```

But df.iterrows() is antipattern and I should avoid this string in my code.
Because if my data set increase it will be a problem
I have tried to use vectorization but I can't figure out how to accumulate.
Code look like this:

```<code>z = 0
con = (df['C'] == 'b',
      df['C'] != 'b')
choise = (
    (df['A'] + dfs['B'], z + 2),
    (df['A'] * dfs['B'], )
)

dfs['D'], z = np.select(con, choise)
</code>```

Can someone help me with that? How to accumulate variable z?

答:
I'm puzzled as to what that first code block is supposed to be doing:

```<code>z = 0
for i, row in df.iterrows():
    a = df['A']
    b = df['B']
    c = df['C']
    if c == 'b':
        d = a + b + z
        z = z + 2
    else:
        d = a*b
    df.at[i, 'D'] = d
</code>```

i and rows are the iteration variables, but you don't use rows, and only use i at the end to set something in the original df.

Do you understand what iterrows does (other than all it an "antipattern"):

Look at a small df:

```<code>In [168]: df = pd.DataFrame(np.arange(6).reshape(2,3), columns=['A','B','C'])
In [169]: df
Out[169]:
   A  B  C
0  0  1  2
1  3  4  5
</code>```

and do iterrows with a lots of prints:

```<code>In [170]: for i, row in df.iterrows():
     ...:     print('==========')
     ...:     print(i, type(row));print(row)
     ...:     a = df['A']
     ...:     print('a', type(a));print(a)
     ...:
==========
0 <class 'pandas.core.series.Series'>
A    0
B    1
C    2
Name: 0, dtype: int64
a <class 'pandas.core.series.Series'>
0    0
1    3
Name: A, dtype: int64
==========
1 <class 'pandas.core.series.Series'>
A    3
B    4
C    5
Name: 1, dtype: int64
a <class 'pandas.core.series.Series'>
0    0
1    3
Name: A, dtype: int64
</code>```

rows is a pandas Series (e.g. one column of a dataframe), with data from one row.  It's like it turn the row into a column. df['A'] is also a Series, but one of the df columns.

That whole:

```<code>a = df['A']
b = df['B']
c = df['C']
if c == 'b':
    d = a + b + z
    z = z + 2
else:
    d = a*b
</code>```

block of code is working with the columns of the frame - whole columns, not values from one row.  There's no point in repeating those calculations again and again in the loop.

c is a Series, so if c=='b with raise an error.  Using the a from my example:

The '==' test produces a Series
In [172]: a==3
Out[172]:
0    False
1     True
Name: A, dtype: bool

Using that Series in an if raises an ambiguity error.

```<code>In [173]: if a==3: print('yes')
Traceback (most recent call last):
  File "<ipython-input-173-1ccc6f02d1f6>", line 1, in <module>
    if a==3: print('yes')
  File "/usr/local/lib/python3.8/dist-packages/pandas/core/generic.py", line 1537, in __nonzero__
    raise ValueError(
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

So your use of iterrows is more than a "anti-pattern".  The code that uses is just plain wrong.  I gone into a lot of detail because I think you need more than "quick" answer.  You need to understand what is happening in your code.

Body:
I have a dataframe.
Witch contain a few columns. It's look like this:

A
B
C
D

1
10
a
Nan

2
11
b
Nan

3
12
c
Nan

So if I have 'b' in column C, I should do A+B.
In other cases A*B.
But with that I have variable that accumulate value(You will see code and it will be cleare).
So I write this code

z = 0
for i, row in df.iterrows():
    a = df['A']
    b = df['B']
    c = df['C']
    if c == 'b':
        d = a + b + z
        z = z + 2
    else:
        d = a*b
    df.at[i, 'D'] = d

But df.iterrows() is antipattern and I should avoid this string in my code.
Because if my data set increase it will be a problem
I have tried to use vectorization but I can't figure out how to accumulate.
Code look like this:

z = 0
con = (df['C'] == 'b',
      df['C'] != 'b')
choise = (
    (df['A'] + dfs['B'], z + 2),
    (df['A'] * dfs['B'], )
)

dfs['D'], z = np.select(con, choise)

Can someone help me with that? How to accumulate variable z?

Body:
I'm puzzled as to what that first code block is supposed to be doing:

z = 0
for i, row in df.iterrows():
    a = df['A']
    b = df['B']
    c = df['C']
    if c == 'b':
        d = a + b + z
        z = z + 2
    else:
        d = a*b
    df.at[i, 'D'] = d

i and rows are the iteration variables, but you don't use rows, and only use i at the end to set something in the original df.

Do you understand what iterrows does (other than all it an "antipattern"):

Look at a small df:

In [168]: df = pd.DataFrame(np.arange(6).reshape(2,3), columns=['A','B','C'])
In [169]: df
Out[169]:
   A  B  C
0  0  1  2
1  3  4  5

and do iterrows with a lots of prints:

In [170]: for i, row in df.iterrows():
     ...:     print('==========')
     ...:     print(i, type(row));print(row)
     ...:     a = df['A']
     ...:     print('a', type(a));print(a)
     ...:
==========
0 <class 'pandas.core.series.Series'>
A    0
B    1
C    2
Name: 0, dtype: int64
a <class 'pandas.core.series.Series'>
0    0
1    3
Name: A, dtype: int64
==========
1 <class 'pandas.core.series.Series'>
A    3
B    4
C    5
Name: 1, dtype: int64
a <class 'pandas.core.series.Series'>
0    0
1    3
Name: A, dtype: int64

rows is a pandas Series (e.g. one column of a dataframe), with data from one row.  It's like it turn the row into a column. df['A'] is also a Series, but one of the df columns.

That whole:

a = df['A']
b = df['B']
c = df['C']
if c == 'b':
    d = a + b + z
    z = z + 2
else:
    d = a*b

block of code is working with the columns of the frame - whole columns, not values from one row.  There's no point in repeating those calculations again and again in the loop.

c is a Series, so if c=='b with raise an error.  Using the a from my example:

The '==' test produces a Series
In [172]: a==3
Out[172]:
0    False
1     True
Name: A, dtype: bool

Using that Series in an if raises an ambiguity error.

In [173]: if a==3: print('yes')
Traceback (most recent call last):
  File "<ipython-input-173-1ccc6f02d1f6>", line 1, in <module>
    if a==3: print('yes')
  File "/usr/local/lib/python3.8/dist-packages/pandas/core/generic.py", line 1537, in __nonzero__
    raise ValueError(
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

So your use of iterrows is more than a "anti-pattern".  The code that uses is just plain wrong.  I gone into a lot of detail because I think you need more than "quick" answer.  You need to understand what is happening in your code.


问:
Unusual way of using java constructor
At some part of the code that I've been working on I am tempted to use the constructor in an unusual way. The goal is to have minimal to none sensitive values inside string pool.

public class MyClass{
    private String mySafeString;

    public MyClass(char[] aCharArray, String salt) {
         this.mySafeString = Encrypt.encrypt(new String(aCharArray), salt);
    }

    public String getMySafeString(){
         return this.mySafeString;
    }
}

...
public static void main(String[] args){
    String salt = getSaltFromSomewhere();
    char[] someKey = new char[]{'c', 'x'};
    var myObject = new MyClass(someKey, salt);
    var encryptedSafeString = myObject.getMySafeString();
}
```

By creating the String object like that I am avoiding the value's presence inside the string pool. Thereby, intending to leave it to GC to perish the object.

However, I fail to find any resource that forbids the usage of constructor like the way I used it. I am keen to know if it is a bad practice in any way?

Could you please be so kind and advise me on my approach?

答:
That's a standard way to convert a char[] to a String.

You might also want to see if your encryption library can work from a char[] or InputStream, so that you can avoid creating any String.

Title: Unusual way of using java constructor

Body:
At some part of the code that I've been working on I am tempted to use the constructor in an unusual way. The goal is to have minimal to none sensitive values inside string pool.

public class MyClass{
    private String mySafeString;

    public MyClass(char[] aCharArray, String salt) {
         this.mySafeString = Encrypt.encrypt(new String(aCharArray), salt);
    }

    public String getMySafeString(){
         return this.mySafeString;
    }
}

...
public static void main(String[] args){
    String salt = getSaltFromSomewhere();
    char[] someKey = new char[]{'c', 'x'};
    var myObject = new MyClass(someKey, salt);
    var encryptedSafeString = myObject.getMySafeString();
}

By creating the String object like that I am avoiding the value's presence inside the string pool. Thereby, intending to leave it to GC to perish the object.

However, I fail to find any resource that forbids the usage of constructor like the way I used it. I am keen to know if it is a bad practice in any way?

Could you please be so kind and advise me on my approach?


问:
My button is getting override by an material ui avatar image onClick
Whenever making a simple category filter which should include images, I keep getting a bug. When I console log, it turns out with the button my img is being clicked and being fired as an image, but when clicked around the edges the button is being fired and doing what I want it to do.
I can't have users experiencing this bug, please help.

My code:

```<code>...
                <Fab
                    key={id}
                    variant="extended"
                    size="medium"
                    color="info"
                    aria-label="add"
                    value={id}
                    onClick={(e) => handleChange(e.target.value)}
                >
                    <Avatar alt={name} src={icon} />
                </Fab>

...
</code>```

Is there a better way to design this ui? Or is there something I'm missing?

答:
Perhaps you are having issues that the image is capturing the events. I'd suggest you test something on CSS.

1 - Create a class avatar in your CSS file.

```<code>.avatar {
  pointer-events: none;
}
</code>```

2 - Add this class to your component.

```<code><Avatar className="avatar" ...
</code>```

When you set that CSS pointer-events to none it means the Avatar component won't register it and it will let the events pass through.

Body:
Whenever making a simple category filter which should include images, I keep getting a bug. When I console log, it turns out with the button my img is being clicked and being fired as an image, but when clicked around the edges the button is being fired and doing what I want it to do.
I can't have users experiencing this bug, please help.

My code:

...
                <Fab
                    key={id}
                    variant="extended"
                    size="medium"
                    color="info"
                    aria-label="add"
                    value={id}
                    onClick={(e) => handleChange(e.target.value)}
                >
                    <Avatar alt={name} src={icon} />
                </Fab>

...

Is there a better way to design this ui? Or is there something I'm missing?

Body:
Perhaps you are having issues that the image is capturing the events. I'd suggest you test something on CSS.

1 - Create a class avatar in your CSS file.

.avatar {
  pointer-events: none;
}

2 - Add this class to your component.

<Avatar className="avatar" ...

When you set that CSS pointer-events to none it means the Avatar component won't register it and it will let the events pass through.


问:
This document requires 'TrustedScriptURL' assignment in Google Sheets
I have a Google Spreadsheet where I have the following information on specific cells in the sheet:

Cell B1: Has the URL http://www.google.com.co/search?q=NASA+watching+now%3A+site%3Awww.youtube.com

Cell B2: has the following formula: =IMPORTXML(B1,"//title")

Here is the link of the Google spreadsheet - if you want to test from your side.

And here is the Google Spreadsheet I'm working on - which, I want to get the specific data:

Title: Text (in the h3 HTML tag of the result item).

Url: Link (in the  HTML tag of the result item)

Description: Text next to the thumbnail of the result item.

See screenshot with the data to get using IMPORTXML:

The previous code returns the title of the given URL - in this case, the URL stored in the B1 cell.

It was working without problems (since 12/02/2022 - dd/MM/yyyy) until today (13/02/2022 - dd/mm/yyyy).

I checked the Chrome console "F12 Developer tools" and I get this error:

This document requires 'TrustedScript' assignment.

injectIntoContentWindow @ VM364:27

By clicking the @ VM364:27 line, the following code is shown:

```<code>  function injectIntoContentWindow(contentWindow)
  {
    if (contentWindow && !injectedFramesHas(contentWindow))
    {
      injectedFramesAdd(contentWindow);
      try
      {
        contentWindow[eventName] = checkRequest;
        contentWindow.eval( /* ERROR with and (X) is shown here. */
          "(" + injectedToString() + ")('" + eventName + "', true);"
        );
        delete contentWindow[eventName];
      }
      catch (e) {}
    }
  }
</code>```

Searching on the internet, I barely could get the causes of this error:

Google Chrome update - making security stricter.

Chrome extensions - try to disable such extensions and try again.

CPS (Content-Security-Policy) - must be honest = I don't understand this point; it's from the website to scrape the data OR from Google Sheets the CPS is the root cause?

The solutions given to this problem are in Python - with the use of DOMPurify - as is described in this answer, but, I don't know and neither have found any clues about this problem and its solution in Google Spreadsheets.

I've tried:

Recover previous working Google Spreadsheet version - the result is that the formula re-evaluates and no result is returned; looking in Console, the This document requires 'TrustedScriptURL' assignment message shows.

Disable Google Chrome installed extensions - I only have AdBlock (this code was working without issues), anyway, I turned off, reload the spreadsheet and the error mentioned above raises in Console.

Using another page - I tried with Wikipedia and Wiki.fandom and it works - i.e. data is returned. Probably in this case, Google injected in their searcher an script for avoid injection? - I'm really not sure, only speculating/rambling here.

Another possible cause I consider is maybe my IP was blacklisted or blocked, but, I'm not sure.

My browser information:

Chrome version: 98.0.4758.82 (Build oficial) (64 bits) (cohort: Stable)

Windows 10 Version 21H2 (Build 19044.1466)

Is there any way to solve this error in Google Sheets?

PS: I'm interested in know the workaround using google sheets and/or custom scripts - via script editor/Apps Script. The use of IMPORTXML function is not mandatory - I find curious that it was working and then today, not anymore.

答:
I will just leave this here:

```<code>=INDEX(UNIQUE(REGEXREPLACE(QUERY(IMPORTXML(A1, "//a/@href"),
 "where Col1 contains 'youtube.com/'"), "\/url\?q=|&sa=.*", )))
</code>```

```<code>=IMPORTXML(A1, "//title")
</code>```

```<code>=IMPORTXML(A1, "//h3")
</code>```

Body:
I have a Google Spreadsheet where I have the following information on specific cells in the sheet:

Cell B1: Has the URL http://www.google.com.co/search?q=NASA+watching+now%3A+site%3Awww.youtube.com

Cell B2: has the following formula: =IMPORTXML(B1,"//title")

Here is the link of the Google spreadsheet - if you want to test from your side.

And here is the Google Spreadsheet I'm working on - which, I want to get the specific data:

Title: Text (in the h3 HTML tag of the result item).

Url: Link (in the  HTML tag of the result item)

Description: Text next to the thumbnail of the result item.

See screenshot with the data to get using IMPORTXML:

The previous code returns the title of the given URL - in this case, the URL stored in the B1 cell.

It was working without problems (since 12/02/2022 - dd/MM/yyyy) until today (13/02/2022 - dd/mm/yyyy).

I checked the Chrome console "F12 Developer tools" and I get this error:

This document requires 'TrustedScript' assignment.

injectIntoContentWindow @ VM364:27

By clicking the @ VM364:27 line, the following code is shown:

  function injectIntoContentWindow(contentWindow)
  {
    if (contentWindow && !injectedFramesHas(contentWindow))
    {
      injectedFramesAdd(contentWindow);
      try
      {
        contentWindow[eventName] = checkRequest;
        contentWindow.eval( /* ERROR with and (X) is shown here. */
          "(" + injectedToString() + ")('" + eventName + "', true);"
        );
        delete contentWindow[eventName];
      }
      catch (e) {}
    }
  }

Searching on the internet, I barely could get the causes of this error:

Google Chrome update - making security stricter.

Chrome extensions - try to disable such extensions and try again.

CPS (Content-Security-Policy) - must be honest = I don't understand this point; it's from the website to scrape the data OR from Google Sheets the CPS is the root cause?

The solutions given to this problem are in Python - with the use of DOMPurify - as is described in this answer, but, I don't know and neither have found any clues about this problem and its solution in Google Spreadsheets.

I've tried:

Recover previous working Google Spreadsheet version - the result is that the formula re-evaluates and no result is returned; looking in Console, the This document requires 'TrustedScriptURL' assignment message shows.

Disable Google Chrome installed extensions - I only have AdBlock (this code was working without issues), anyway, I turned off, reload the spreadsheet and the error mentioned above raises in Console.

Using another page - I tried with Wikipedia and Wiki.fandom and it works - i.e. data is returned. Probably in this case, Google injected in their searcher an script for avoid injection? - I'm really not sure, only speculating/rambling here.

Another possible cause I consider is maybe my IP was blacklisted or blocked, but, I'm not sure.

My browser information:

Chrome version: 98.0.4758.82 (Build oficial) (64 bits) (cohort: Stable)

Windows 10 Version 21H2 (Build 19044.1466)

Is there any way to solve this error in Google Sheets?

PS: I'm interested in know the workaround using google sheets and/or custom scripts - via script editor/Apps Script. The use of IMPORTXML function is not mandatory - I find curious that it was working and then today, not anymore.

Body:
I will just leave this here:

=INDEX(UNIQUE(REGEXREPLACE(QUERY(IMPORTXML(A1, "//a/@href"),
 "where Col1 contains 'youtube.com/'"), "\/url\?q=|&sa=.*", )))

=IMPORTXML(A1, "//title")

=IMPORTXML(A1, "//h3")


问:
Android Studio can't login to GitHub
I'm getting this issue while logging in on GitHub on Android Studio:

Can't login: Can't get user info 404: Not found

Has someone faced this issue? How can I get around this?

答:
Use SSH (forget https) (E.g., don't use https url for cloning)

Use Personal Access Token (PAT) (forget username/password)

(e.g., Settings > Developer Settings > Personal Access Token)

Update git to latest version (e.g., 2.35.1)  //I think this is important

In Github, Uncheck Settings > Developer Settings > Keep my email addresses private

Conclusion: You add Personal Access token in Github. Then from any IDE (e.g., Android Studio, IntelliJ IDEA etc.) you can add remote using ssh (e.g.,  name: origin, URL: git@github.com:your_github_username/your_git_repo.git. That's it

If not already done,

Configure git global username and email

git config --global user.name "your_username" && git config --global user.email "your_email"

If in windows, you can add windows credentials for your user, control panel > users > manage your credential > Windows Credentials > Add a generic credential >

Internet address will be git:https://github.com and you need to type
in your username and password will be your GitHub Personal Access
Token => Click Ok and you are done

ContentLicense: CC BY-SA 3.0

Title: Android Studio can't login to GitHub


问:
Invalid port. Exiting... org.openqa.selenium.os.OsProcess checkForError while launching chrome using selenium
I am using selenium server standalone jar- 3.11.0, latest ChromeDriver-2.36 and
 Chrome version 66.0.3359.139

My code

```<code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class WebDriverBasics {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "C:\\Users\\surya\\Downloads\\Compressed\\chromedriver_win32_2\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.get("http://www.facebook.com");
        driver.manage().window().maximize();
    }
}
</code>```

But i am unable to launch chrome.its giving below error

```<code>Invalid port. Exiting...
?? ??, ???? ??:??:?? ????????? org.openqa.selenium.os.OsProcess checkForError
SEVERE: org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)
Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
Build info: version: '3.11.0', revision: 'e59cfb3', time: '2018-03-11T20:33:15.31Z'
System info: host: 'DESKTOP-5GVJDVR', ip: '192.168.0.104', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_171'
Driver info: driver.version: ChromeDriver
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:192)
    at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:178)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:545)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:209)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:132)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
    at WebDriverBasics.main(WebDriverBasics.java:12)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:????/status] to be available after ????? ms
    at
</code>```

答:
that working after i use

```<code> WebDriver dev= new ChromeDriver(new ChromeDriverService.Builder().usingPort(YOUR PORT).build());
</code>```

you can get your port by open WebDriver app
NOTE: keep ChromeDriver running

Body:
I am using selenium server standalone jar- 3.11.0, latest ChromeDriver-2.36 and
 Chrome version 66.0.3359.139

My code

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class WebDriverBasics {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "C:\\Users\\surya\\Downloads\\Compressed\\chromedriver_win32_2\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.get("http://www.facebook.com");
        driver.manage().window().maximize();
    }
}

But i am unable to launch chrome.its giving below error

Invalid port. Exiting...
?? ??, ???? ??:??:?? ????????? org.openqa.selenium.os.OsProcess checkForError
SEVERE: org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)
Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
Build info: version: '3.11.0', revision: 'e59cfb3', time: '2018-03-11T20:33:15.31Z'
System info: host: 'DESKTOP-5GVJDVR', ip: '192.168.0.104', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_171'
Driver info: driver.version: ChromeDriver
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:192)
    at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:178)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:545)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:209)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:132)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
    at WebDriverBasics.main(WebDriverBasics.java:12)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:????/status] to be available after ????? ms
    at

Body:
that working after i use

 WebDriver dev= new ChromeDriver(new ChromeDriverService.Builder().usingPort(YOUR PORT).build());

you can get your port by open WebDriver app
NOTE: keep ChromeDriver running


问:
How can I detect https redirects using only built in node modules?
I don't want to actually follow the re-direct as seen here, I simply want to detect a redirect.

Here is my current code.  Please note I want to simply detect a redirect and not do anything with it.  The code works fine but downloads gibberish on a redirect.

I don't want to use any external modules.  I believe there is a thing called headers that might come in use.

```<code>const https = require('https');
const fs = require('fs');

function download(entry, destination, callback) {
  const writeStream = fs.createWriteStream(destination);
  const request = https.get(entry, (response) => {
    response.pipe(writeStream);
  }).on('error', (error) => {
    console.log('DEBUG:', error);
  });
}
</code>```

A good example of a redirect is here:

https://www.imdb.com/favicon.ico

答:
You can do something like this

if (
    response.statusCode >= 300 &&
    response.statusCode < 400 &&
    'location' in response.headers
  ) {
    console.log('redirect detected');
  }
```
<p>full code:</p>
<pre class="lang-js prettyprint-override"><code>const https = require('https');
const fs = require('fs');

function download(entry, destination, callback) {
  const writeStream = fs.createWriteStream(destination);
  const request = https.get(entry, (response) => {
    if (
      response.statusCode >= 300 &&
      response.statusCode < 400 &&
      'location' in response.headers
    ) {
      console.log('redirect detected');
    }

    response.pipe(writeStream);
  }).on('error', (error) => {
    console.log('DEBUG:', error);
  });
}
</code>```

According to https://github.com/request/request/blob/86b99b671a3c86f4f963a6c67047343fd8edae8f/request.js#L762

Body:
I don't want to actually follow the re-direct as seen here, I simply want to detect a redirect.

Here is my current code.  Please note I want to simply detect a redirect and not do anything with it.  The code works fine but downloads gibberish on a redirect.

I don't want to use any external modules.  I believe there is a thing called headers that might come in use.

const https = require('https');
const fs = require('fs');

function download(entry, destination, callback) {
  const writeStream = fs.createWriteStream(destination);
  const request = https.get(entry, (response) => {
    response.pipe(writeStream);
  }).on('error', (error) => {
    console.log('DEBUG:', error);
  });
}

A good example of a redirect is here:

https://www.imdb.com/favicon.ico

Body:
You can do something like this

if (
    response.statusCode >= 300 &&
    response.statusCode < 400 &&
    'location' in response.headers
  ) {
    console.log('redirect detected');
  }

full code:

const https = require('https');
const fs = require('fs');

function download(entry, destination, callback) {
  const writeStream = fs.createWriteStream(destination);
  const request = https.get(entry, (response) => {
    if (
      response.statusCode >= 300 &&
      response.statusCode < 400 &&
      'location' in response.headers
    ) {
      console.log('redirect detected');
    }

    response.pipe(writeStream);
  }).on('error', (error) => {
    console.log('DEBUG:', error);
  });
}

According to https://github.com/request/request/blob/86b99b671a3c86f4f963a6c67047343fd8edae8f/request.js#L762


问:
Prevent Visual Studio Code or IDE From Revealing Python Class Private Methods
just want to ask a quick question;

Essentially, I want to know if it's possible to hide Python class private methods from the list of suggestions that Visual Studio Code or other IDEs provide.

For instance, suppose that we have a class "A":

```<code># Creating a class
class A:

    # Declaring public method
    def fun(self):
        print("Public method")

    # Declaring private method
    def __fun(self):
        print("Private method")

    # Calling private method via
    # another method
    def Help(self):
        self.fun()
        self.__fun()
</code>```

Now, we don't want Visual Studio Code or other IDEs to show the method "__fun" in the list of suggestions provided by the IDE, how can we do that?

I can see that even though "__fun" has been declared as private method inside class "A", Visual Studio code will still suggest it in its snippet:

Would it be possible to get rid of this?

答:
I may have found a partial solution to your question, which may help

There is a python language setting in vscode that, if enabled, reports an usage of 'protected' function (started with underscore) outside of the class.

Press CTRL+SHIFT+P, type "Configure Language Specific Settings" and select Python. In JSON object add the following property:

```<code>"python.analysis.diagnosticSeverityOverrides": {
    "reportPrivateUsage": "error"
}
</code>```

source: code.visualstudio.com/docs/python/settings-reference

Body:
just want to ask a quick question;

Essentially, I want to know if it's possible to hide Python class private methods from the list of suggestions that Visual Studio Code or other IDEs provide.

For instance, suppose that we have a class "A":

# Creating a class
class A:

    # Declaring public method
    def fun(self):
        print("Public method")

    # Declaring private method
    def __fun(self):
        print("Private method")

    # Calling private method via
    # another method
    def Help(self):
        self.fun()
        self.__fun()

Now, we don't want Visual Studio Code or other IDEs to show the method "__fun" in the list of suggestions provided by the IDE, how can we do that?

I can see that even though "__fun" has been declared as private method inside class "A", Visual Studio code will still suggest it in its snippet:

Would it be possible to get rid of this?

Body:
I may have found a partial solution to your question, which may help

There is a python language setting in vscode that, if enabled, reports an usage of 'protected' function (started with underscore) outside of the class.

Press CTRL+SHIFT+P, type "Configure Language Specific Settings" and select Python. In JSON object add the following property:

"python.analysis.diagnosticSeverityOverrides": {
    "reportPrivateUsage": "error"
}

source: code.visualstudio.com/docs/python/settings-reference


问:
Python Tkinter Frame Destroy to display new data
App works fine when first loaded. I need to update data on each frame to display what the user has changed.
I know I need to somehow destroy the frame to reload the data. Any suggestions on how to edit switch_frame to destroy to previous frame?</p>
```<code>class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand="true")
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0,weight=1)

        self.frames = {}

        for F in (homepage, page2, page3):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.switch_frame("homepage")

    def switch_frame(self, frame_class):
        frame = self.frames[frame_class]
        frame.tkraise()
</code>```

答:
You can:

destroy current shown frame (need an instance variable to hold it)

create the frame when it is to be shown

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        # used instance variable so that it can be accessed in other class functions
        self.container = tk.Frame(self)
        self.container.pack(side="top", fill="both", expand="true")
        self.container.grid_rowconfigure(0, weight=1)
        self.container.grid_columnconfigure(0,weight=1)

        self.frames = {}
        self.frame = None  # hold the current frame shown

        for F in (homepage, page2, page3):
            page_name = F.__name__
            self.frames[page_name] = F
        self.switch_frame("homepage")

    def switch_frame(self, frame_class):
        # destroy current frame shown if any
        if self.frame:
            self.frame.destroy()
        # create the required frame and show it
        self.frame = self.frames[frame_class](self.container, self)
        self.frame.grid(row=0, column=0, sticky="nsew")
```

Body:
App works fine when first loaded. I need to update data on each frame to display what the user has changed.
I know I need to somehow destroy the frame to reload the data. Any suggestions on how to edit switch_frame to destroy to previous frame?

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand="true")
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0,weight=1)

        self.frames = {}

        for F in (homepage, page2, page3):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.switch_frame("homepage")

    def switch_frame(self, frame_class):
        frame = self.frames[frame_class]
        frame.tkraise()


问:
Failed to login Github for Android Studio
I want to share my Android Studio project on Github but when I click to share, it appear to

http://127.0.0.1:63342/api/github/oauth/authorization_code?code=14c943d3435fe66a54f7

and it ask for username and password. I try to log in using my Github username and password but failed.

*Just started programming for 2 weeks

答:
I solved this problem following these steps:

Use SSH (forget https) (E.g., don't use https url for cloning)

Use Personal Access Token (PAT) (forget username/password)

(e.g., Settings > Developer Settings > Personal Access Token)

Update git to latest version (e.g., 2.35.1)  //I think this is important

In Github, Uncheck Settings > Developer Settings > Keep my email addresses private

Conclusion: You add Personal Access token in Github. Then from any IDE (e.g., Android Studio, IntelliJ IDEA etc.) you can add remote using ssh (e.g.,  name: origin, URL: git@github.com:your_github_username/your_git_repo.git. That's it

If not already done,

Configure git global username and email

git config --global user.name "your_username" && git config --global user.email "your_email"

If in windows, you can add windows credentials for your user, control panel > users > manage your credential > Windows Credentials > Add a generic credential >

Internet address will be git:https://github.com and you need to type
in your username and password will be your GitHub Personal Access
Token => Click Ok and you are done


问:
Uncaught TypeError: theme.palette.common is undefined
I'm using MUI. I have a container and inside it I have two child components a Box and another container. here is the code:

```<code>import { Button, Container } from "@mui/material";
import React from "react";
import {Box} from "@mui/systems"
import MovieCard from "./MovieCard";
const MovieList = () => {

  return (
   <Container>
      <Box
        sx={(theme) => ({
          mb: theme.spacing(2),
          width: "40vw",
          mr: "auto",
          ml: "auto",
          bgcolor: theme.palette.common.white, // here is the problem!!!!!!!!!!!!!!
        })}
      >
        <Button>Show Movies</Button>
      </Box>
      <Container
        sx={(theme) => ({
          width: "40vw",
          border: "1px solid black",
          borderRadius: theme.shape.borderRadius,
          padding: theme.spacing(2),
          bgcolor: theme.palette.common.white, // here the same line of code without problem
        })}
      >
        <MovieCard />
        <MovieCard />
        <MovieCard />
      </Container>
</Container>
)
</code>```

If I add that bgcolor to the box sx prop I get the "Uncaught TypeError: theme.palette.common is undefined" error and everything crashes. under the Box component, I have a container with exactly same bgcolor and same value but get no error. can someone please explain the problem?

答:
If you import Box from @mui/system instead of @mui/material, then it won't have access to the full default theme provided by @mui/material unless you explicitly provide it via ThemeProvider.

theme.spacing(2) still worked because @mui/system provides a simple default theme which includes the spacing function, but the default palette in @mui/system is nearly empty.

Body:
I'm using MUI. I have a container and inside it I have two child components a Box and another container. here is the code:

import { Button, Container } from "@mui/material";
import React from "react";
import {Box} from "@mui/systems"
import MovieCard from "./MovieCard";
const MovieList = () => {

  return (
   <Container>
      <Box
        sx={(theme) => ({
          mb: theme.spacing(2),
          width: "40vw",
          mr: "auto",
          ml: "auto",
          bgcolor: theme.palette.common.white, // here is the problem!!!!!!!!!!!!!!
        })}
      >
        <Button>Show Movies</Button>
      </Box>
      <Container
        sx={(theme) => ({
          width: "40vw",
          border: "1px solid black",
          borderRadius: theme.shape.borderRadius,
          padding: theme.spacing(2),
          bgcolor: theme.palette.common.white, // here the same line of code without problem
        })}
      >
        <MovieCard />
        <MovieCard />
        <MovieCard />
      </Container>
</Container>
)

If I add that bgcolor to the box sx prop I get the "Uncaught TypeError: theme.palette.common is undefined" error and everything crashes. under the Box component, I have a container with exactly same bgcolor and same value but get no error. can someone please explain the problem?


问:
Get the span class name using BeautifulSoup
I am using BeautifulSoup to scrape a website. The retrieved resultset looks like this:

```<code><td><span class="I_Want_This_Class_Name"></span><span class="other_name">Text Is Here</span></td>
</code>```

From here, I want to retrieve the class name "I_Want_This_Class_Name". I can get the "Text Is Here" part no problem, but the class name itself is proving to be difficult.

Is there a way to do this using BeautifulSoup resultset or do I need to convert to a dictionary?

Thank you

答:
```<code>from bs4 import BeautifulSoup

doc = '''<td><span class="I_Want_This_Class_Name"></span><span class="other_name">Text Is Here</span></td>
'''
soup = BeautifulSoup(doc, 'html.parser')

res = soup.find('td')
out = {}
for each in res:
  if each.has_attr('class'):
    out[each['class'][0]] = each.text
print(out)
</code>```

output will be like:

{'I_Want_This_Class_Name': '', 'other_name': 'Text Is Here'}

Body:
I am using BeautifulSoup to scrape a website. The retrieved resultset looks like this:

Text Is Here

From here, I want to retrieve the class name "I_Want_This_Class_Name". I can get the "Text Is Here" part no problem, but the class name itself is proving to be difficult.

Is there a way to do this using BeautifulSoup resultset or do I need to convert to a dictionary?

Thank you

Body:
from bs4 import BeautifulSoup

doc = '''<td><span class="I_Want_This_Class_Name"></span><span class="other_name">Text Is Here</span></td>
'''
soup = BeautifulSoup(doc, 'html.parser')

res = soup.find('td')
out = {}
for each in res:
  if each.has_attr('class'):
    out[each['class'][0]] = each.text
print(out)

output will be like:

{'I_Want_This_Class_Name': '', 'other_name': 'Text Is Here'}


问:
Extracting filesnames in bash with regex
Can please someone help me to set up a regular expression.

I have a large LaTeX3 TeXDoc file.  LaTeX3 TeXDoc defines the macro \TestFiles{}, which should be used, to list the names of files, which itself should be used as an unit tests.  You can name more than one file between the braces.  So \TestFiles{foo-bar} and \TestFiles{foo-bar, bar+baz,foo_bar_baz} are syntactical correct use cases for this macro.

I would like to write a bash script, to extract all the uni test files, named in the \TestFiles{} macros, to compile them with pdflatex and check, if pdflatex will be able to produce an output file successfully.

I have something like this in my script:

function get_filenames () {
  ## This regex works but is not sensible enough
  # regex='\\TestFiles{(.*)}'
  ## This works also, but is again not precise enough
  regex='\\TestFiles{([0-9a-zA-Z+-_, ]*)}'
  ## This should give more than one matching group
  ## (separated by ", " or ","), but this regex doesn't
  ## work.  I have no idea why or how to modify, to get
  ## it working

  while read -r line ; do
    if [[ $line =~ $regex ]] ; then
      i=1
        while [ $i -le 3 ]; do
          echo "Match $i: \"${BASH_REMATCH[$i]}\""
          i=$(( i + 1 ))
        done
      echo
    fi
  done < mystyle.dtx
}
```
<p>Here is an excerpt of the DTX file</p>
<pre class="lang-latex prettyprint-override"><code>\TestFiles{foo-bar}

\TestFiles{foo-bar, bar+baz,foo_bar_baz}
</code>```

(You can store this as mystyle.dtx, in order to reproduce the next example.)

Using the above noted examples, my script gives me the following results:

get_filenames
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar, bar+baz,foo_bar_baz"
Match 2: ""
Match 3: ""

```
<p>I wasn't able, to modify my <code>regex</code> expression, to split the content of the last <code>\TestFiles{foo-bar, bar+baz,foo_bar_baz}</code> example into three matching results.</p>
<p>I tried a regular expression like this <code>regex='\\TestFiles{([[:alnum:]+-_]*)[,]+[ ]*}'</code>.  I thought the <code>[:alnum:]+-_]*</code> would match the filenames.  As far as I understand regular expressions, the <code>(...)</code> should form a group, that should be listed afterwards in the bash array <code>BASH_REMATCH[$i]</code>.</p>
<p>The part <code>[,]+</code> should reflect that every file name must be separated by at least one comma.  Between the filenames there might be some white space, so something like <code>[[:space:]]*</code> or at least <code>[ ]*</code> should represent this.  The quantifier <code>*</code> means any repetition, ranging from 0 to ..., while <code>+</code> should at least appear one or more times.</p>
<p>But that regular expression did not work at all, if had no matching results.</p>
<p>How must <code>regex</code> be defined, to store each filenames as a matching group?  I am searching for the correct regular expression, to get this result:</p>
<pre class="lang-sh prettyprint-override"><code>get_filenames
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar"
Match 2: "bar+baz"
Match 3: "foo_bar_baz"

</code>```

EDIT: in my real world files, there may be (and are) more than tree test files.

Thanks in advance.

答:
Suggesting an awk script that would do the trick on one or more files.

get_filenames.awk

```<code>/\\TestFiles{[^}]*}/ { # handle only lines matching regex filter
  filesCount = split($0, fileNamesArr, "\\\\TestFiles{[ ]*|[ ]*,[ ]*|[ ]*}"); # parse line to array fileNamesArr
  for (i = 2; i < filesCount; i++) { # read elements 2 --> filesCount - 1
    printf("Match %d in %s: \"%s\"\n", i - 1, FILENAME, fileNamesArr[i]); # format print fileNames
  }
  print"";
}
</code>```

test file: input.1.txt

```<code>some text line 1
\TestFiles{foo-bar0}
some text \TestFiles{foo-bar1, bar+baz1, foo_bar_baz1}
some text \TestFiles{foo-bar2 ,bar+baz2 ,foo_bar_baz2 }
some text \TestFiles{ foo-bar3 , bar+baz3 , foo_bar_baz3 } some text
line 4
</code>```

test file: input.2.txt

```<code>    \TestFiles{file10, file11}
text
text \TestFiles{  file20 } some text
text\TestFiles{file30,file31,file32   }text
text
</code>```

testingget_filenames.awk

```<code>awk -f get_filenames.awk input.1.txt input.2.txt

Match 1 in input.1.txt: "foo-bar0"

Match 1 in input.1.txt: "foo-bar1"
Match 2 in input.1.txt: "bar+baz1"
Match 3 in input.1.txt: "foo_bar_baz1"

Match 1 in input.1.txt: "foo-bar2"
Match 2 in input.1.txt: "bar+baz2"
Match 3 in input.1.txt: "foo_bar_baz2"

Match 1 in input.1.txt: "foo-bar3"
Match 2 in input.1.txt: "bar+baz3"
Match 3 in input.1.txt: "foo_bar_baz3"

Match 1 in input.2.txt: "file10"
Match 2 in input.2.txt: "file11"

Match 1 in input.2.txt: "file20"

Match 1 in input.2.txt: "file30"
Match 2 in input.2.txt: "file31"
Match 3 in input.2.txt: "file32"
</code>```

Body:
Can please someone help me to set up a regular expression.

I have a large LaTeX3 TeXDoc file.  LaTeX3 TeXDoc defines the macro \TestFiles{}, which should be used, to list the names of files, which itself should be used as an unit tests.  You can name more than one file between the braces.  So \TestFiles{foo-bar} and \TestFiles{foo-bar, bar+baz,foo_bar_baz} are syntactical correct use cases for this macro.

I would like to write a bash script, to extract all the uni test files, named in the \TestFiles{} macros, to compile them with pdflatex and check, if pdflatex will be able to produce an output file successfully.

I have something like this in my script:

function get_filenames () {
  ## This regex works but is not sensible enough
  # regex='\\TestFiles{(.*)}'
  ## This works also, but is again not precise enough
  regex='\\TestFiles{([0-9a-zA-Z+-_, ]*)}'
  ## This should give more than one matching group
  ## (separated by ", " or ","), but this regex doesn't
  ## work.  I have no idea why or how to modify, to get
  ## it working

  while read -r line ; do
    if [[ $line =~ $regex ]] ; then
      i=1
        while [ $i -le 3 ]; do
          echo "Match $i: \"${BASH_REMATCH[$i]}\""
          i=$(( i + 1 ))
        done
      echo
    fi
  done < mystyle.dtx
}

Here is an excerpt of the DTX file

\TestFiles{foo-bar}

\TestFiles{foo-bar, bar+baz,foo_bar_baz}

(You can store this as mystyle.dtx, in order to reproduce the next example.)

Using the above noted examples, my script gives me the following results:

get_filenames
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar, bar+baz,foo_bar_baz"
Match 2: ""
Match 3: ""

I wasn't able, to modify my regex expression, to split the content of the last \TestFiles{foo-bar, bar+baz,foo_bar_baz} example into three matching results.

I tried a regular expression like this regex='\\TestFiles{([[:alnum:]+-_]*)[,]+[ ]*}'.  I thought the [:alnum:]+-_]* would match the filenames.  As far as I understand regular expressions, the (...) should form a group, that should be listed afterwards in the bash array BASH_REMATCH[$i].

The part [,]+ should reflect that every file name must be separated by at least one comma.  Between the filenames there might be some white space, so something like [[:space:]]* or at least [ ]* should represent this.  The quantifier * means any repetition, ranging from 0 to ..., while + should at least appear one or more times.

But that regular expression did not work at all, if had no matching results.

How must regex be defined, to store each filenames as a matching group?  I am searching for the correct regular expression, to get this result:

get_filenames
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar"
Match 2: "bar+baz"
Match 3: "foo_bar_baz"

EDIT: in my real world files, there may be (and are) more than tree test files.

Thanks in advance.

Body:
Suggesting an awk script that would do the trick on one or more files.

get_filenames.awk

/\\TestFiles{[^}]*}/ { # handle only lines matching regex filter
  filesCount = split($0, fileNamesArr, "\\\\TestFiles{[ ]*|[ ]*,[ ]*|[ ]*}"); # parse line to array fileNamesArr
  for (i = 2; i < filesCount; i++) { # read elements 2 --> filesCount - 1
    printf("Match %d in %s: \"%s\"\n", i - 1, FILENAME, fileNamesArr[i]); # format print fileNames
  }
  print"";
}

test file: input.1.txt

some text line 1
\TestFiles{foo-bar0}
some text \TestFiles{foo-bar1, bar+baz1, foo_bar_baz1}
some text \TestFiles{foo-bar2 ,bar+baz2 ,foo_bar_baz2 }
some text \TestFiles{ foo-bar3 , bar+baz3 , foo_bar_baz3 } some text
line 4

test file: input.2.txt

    \TestFiles{file10, file11}
text
text \TestFiles{  file20 } some text
text\TestFiles{file30,file31,file32   }text
text

testingget_filenames.awk

awk -f get_filenames.awk input.1.txt input.2.txt

Match 1 in input.1.txt: "foo-bar0"

Match 1 in input.1.txt: "foo-bar1"
Match 2 in input.1.txt: "bar+baz1"
Match 3 in input.1.txt: "foo_bar_baz1"

Match 1 in input.1.txt: "foo-bar2"
Match 2 in input.1.txt: "bar+baz2"
Match 3 in input.1.txt: "foo_bar_baz2"

Match 1 in input.1.txt: "foo-bar3"
Match 2 in input.1.txt: "bar+baz3"
Match 3 in input.1.txt: "foo_bar_baz3"

Match 1 in input.2.txt: "file10"
Match 2 in input.2.txt: "file11"

Match 1 in input.2.txt: "file20"

Match 1 in input.2.txt: "file30"
Match 2 in input.2.txt: "file31"
Match 3 in input.2.txt: "file32"


问:
Message "Support for password authentication was removed. Please use a personal access token instead."
I got this error on my console when I tried to use git pull:

remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.

remote: Please see https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/ for more information.

fatal: unable to access "..." : The requested URL returned error: 403

It's very weird, because I just followed the documentation and created a token two weeks ago on GitHub. The token expires on Tue, Oct 26, 2021. Why has this been removed today?

答:
Use SSH (forget https) (E.g., don't use https url for cloning)

Use Personal Access Token (PAT) (forget username/password)

(e.g., Settings > Developer Settings > Personal Access Token)

Update git to latest version (e.g., 2.35.1)  //I think this is important

In Github, Uncheck Settings > Developer Settings > Keep my email addresses private

Conclusion: You add Personal Access token in Github. Then from any IDE (e.g., Android Studio, IntelliJ IDEA etc.) you can add remote using ssh (e.g.,  name: origin, URL: git@github.com:your_github_username/your_git_repo.git. That's it

If not already done,

Configure git global username and email

git config --global user.name "your_username" && git config --global user.email "your_email"

If in windows, you can add windows credentials for your user, control panel > users > manage your credential > Windows Credentials > Add a generic credential >

Internet address will be git:https://github.com and you need to type
in your username and password will be your GitHub Personal Access
Token => Click Ok and you are done

After this I was able to use git (fetch/push/pull etc.)


问:
Using return redirect makes authentication data changes Laravel
So below here, notice that I use return redirect('/home').

```<code>public function login(Request $request)
{
    $credentials = $request->validate([
        'email' => 'filled|email',
        'password' => ['filled', Password::min(8)->numbers()]
    ]);

    if (Auth::guard('account')->attempt($credentials)) {
        return redirect('/home');
    }

    return redirect('/login')->withErrors('User not found');
}
</code>```

However, when I dd(Auth::guard('account')->user()); it shows like this:
attributes list

Notice that the account_id is "ABC", but actually, it is supposed to be "mdd" as I log in with "mdd" email and password. This, however, doesn't happen if I use this (use return view instead of return redirect):

```<code>public function login(Request $request)
{
    $credentials = $request->validate([
        'email' => 'filled|email',
        'password' => ['filled', Password::min(8)->numbers()]
    ]);

    if (Auth::guard('account')->attempt($credentials)) {
        return view('home', [
            'title' => 'Home'
        ]);
    }

    return redirect('/login')->withErrors('User not found');
}
</code>```

And this is my route for redirecting to '/home'.

```<code>Route::get('/home', [AccountController::class, 'viewHome']);
</code>```

The viewHome():

```<code>public function viewHome()
{
    // dd(Auth::guard('account')->user());
    return view('home', [
        'title' => 'Home'
    ]);
}
</code>```

Why is this happening? How can I solve this issue?

答:
try this</p>
```<code>public function login(Request $request)
    {
            $input = $request->all();

            $this->validate($request, [
                'email' => 'required|email',
                'password' => 'required',
            ]);

            $fieldType = filter_var($request->email, FILTER_VALIDATE_EMAIL) ? 'email' : 'email';
            if(auth()->attempt(array($fieldType => $input['email'], 'password' => $input['password'])))
            {
                return redirect('home');
            }else{
                return redirect()->route('login')->with('message', 'User not found');
            }

        }
</code>```

Body:
So below here, notice that I use return redirect('/home').

public function login(Request $request)
{
    $credentials = $request->validate([
        'email' => 'filled|email',
        'password' => ['filled', Password::min(8)->numbers()]
    ]);

    if (Auth::guard('account')->attempt($credentials)) {
        return redirect('/home');
    }

    return redirect('/login')->withErrors('User not found');
}

However, when I dd(Auth::guard('account')->user()); it shows like this:
attributes list

Notice that the account_id is "ABC", but actually, it is supposed to be "mdd" as I log in with "mdd" email and password. This, however, doesn't happen if I use this (use return view instead of return redirect):

public function login(Request $request)
{
    $credentials = $request->validate([
        'email' => 'filled|email',
        'password' => ['filled', Password::min(8)->numbers()]
    ]);

    if (Auth::guard('account')->attempt($credentials)) {
        return view('home', [
            'title' => 'Home'
        ]);
    }

    return redirect('/login')->withErrors('User not found');
}

And this is my route for redirecting to '/home'.

Route::get('/home', [AccountController::class, 'viewHome']);

The viewHome():

public function viewHome()
{
    // dd(Auth::guard('account')->user());
    return view('home', [
        'title' => 'Home'
    ]);
}

Why is this happening? How can I solve this issue?

Body:
try this

public function login(Request $request)
    {
            $input = $request->all();

            $this->validate($request, [
                'email' => 'required|email',
                'password' => 'required',
            ]);

            $fieldType = filter_var($request->email, FILTER_VALIDATE_EMAIL) ? 'email' : 'email';
            if(auth()->attempt(array($fieldType => $input['email'], 'password' => $input['password'])))
            {
                return redirect('home');
            }else{
                return redirect()->route('login')->with('message', 'User not found');
            }

        }