问:
How can I solve this Fetch problem in React.js?
I have this fetch where I'm trying to post a form in MongoDB.

When I fill the form I get this back:
SyntaxError: Unexpected end of input at ContactRequest.js:3:1

And I don't know why, because the fetch receives the data from the form and testing the endpoint in postman it works perfectly.

The fetch should works because I used the same Fetch in other projects.

This is the fetch component.

```<code>
const contactRequest = (params) => {
  console.log(`Test ${JSON.stringify(params)}`);
  fetch(`http://localhost:4000/contact`, {
      method: "POST",
      body: JSON.stringify(params),
      mode: "no-cors",
      headers: {
        'Content-Type': 'application/json'
      }})
      .then(res => res.json())
      .catch((e) => console.error(e));
};

export default contactRequest;

</code>```

This is the form component:

```<code>import React, {useState} from 'react';
import contactRequest from '../Request/ContactRequest';
import './Contact.css';

const initialState = {
    nameAndSurname: "",
    email: "",
    phoneNumber: "",
    message: "",
};

const Contact = () => {

    const [contactData, setContactData] = useState(initialState);

    const handlerInput = (e) => {
        setContactData({
            ...contactData,
            [e.target.name] : e.target.value
        });
    };

    const handlerSubmit = (e) => {
        e.preventDefault();
        setContactData(initialState);
        contactRequest(contactData);
        alert("Hemos recibido tu mensaje.");
    }

    return (
            <div>
                <form onSubmit={handlerSubmit}>
                    <label className="nameAndSurname-label">
                        Nombre y Apellido: <br/>
                        <input
                            id="nameAndSurname"
                            type="text"
                            name="nameAndSurname"
                            placeholder="Ingrese su nombre y apellido"
                            onChange={handlerInput}
                            value={contactData.nameAndSurname}
                            required/> <br/>
                    </label>
                    <div className="email-phoneNumber-div">
                    <label>
                        Email: <br/>
                        <input
                            id="email"
                            type="email"
                            name="email"
                            placeholder="Ingrese su email"
                            onChange={handlerInput}
                            value={contactData.email}
                            required/> <br/>
                    </label>
                    <label>
                        Numero de teléfono: <br/>
                        <input
                            id="phoneNumber"
                            type="number"
                            name="phoneNumber"
                            placeholder="Ingrese su numero de teléfono"
                            onChange={handlerInput}
                            value={contactData.phoneNumber}
                            required/> <br/>
                    </label>
                    </div>
                    <label>
                        Mensaje: <br/>
                        <input
                            id="message"
                            type="text"
                            name="message"
                            placeholder="Ingrese su mensaje"
                            onChange={handlerInput}
                            value={contactData.message}
                            required/> <br/>
                    </label>
                    <label>
                        Al enviar este formulario, acepto los terminos y condiciones.
                    </label>
                    <button
                        id="submit-btn"
                        type="submit"
                        value="Submit">Enviar</button>
                </form>
            </div>
        </div>
    )
}

export default Contact;

</code>```

This is the Endpoint.

```<code>

const express = require('express');
const router = express.Router();
const Contact = require('../models/Contact.js');

router.post('/contact', (req, res) => {
  console.log(req.body);
  console.log(req.text);
  let contact = new Contact()
  contact.nameAndSurname = req.body.nameAndSurname
  contact.email = req.body.email
  contact.phoneNumber = req.body.phoneNumber
  contact.message = req.body.message

  contact.save((err, contactStored) => {
    if(err) {
      res.status(500).send({message: `Error ${err}`})
    }else {
      res.status(200).send({contact: contactStored})
    }
  })
})

module.exports = router;

</code>```

答: Why are you using mode: "no-cors"? This results in an "opaque" response, without body, so without anything to convert to json

Body:
I have this fetch where I'm trying to post a form in MongoDB.

When I fill the form I get this back:
SyntaxError: Unexpected end of input at ContactRequest.js:3:1

And I don't know why, because the fetch receives the data from the form and testing the endpoint in postman it works perfectly.

The fetch should works because I used the same Fetch in other projects.

This is the fetch component.

const contactRequest = (params) => {
  console.log(`Test ${JSON.stringify(params)}`);
  fetch(`http://localhost:4000/contact`, {
      method: "POST",
      body: JSON.stringify(params),
      mode: "no-cors",
      headers: {
        'Content-Type': 'application/json'
      }})
      .then(res => res.json())
      .catch((e) => console.error(e));
};

export default contactRequest;

This is the form component:

import React, {useState} from 'react';
import contactRequest from '../Request/ContactRequest';
import './Contact.css';

const initialState = {
    nameAndSurname: "",
    email: "",
    phoneNumber: "",
    message: "",
};

const Contact = () => {

    const [contactData, setContactData] = useState(initialState);

    const handlerInput = (e) => {
        setContactData({
            ...contactData,
            [e.target.name] : e.target.value
        });
    };

    const handlerSubmit = (e) => {
        e.preventDefault();
        setContactData(initialState);
        contactRequest(contactData);
        alert("Hemos recibido tu mensaje.");
    }

    return (

                <form onSubmit={handlerSubmit}>

                        Nombre y Apellido:

                        <input
                            id="nameAndSurname"
                            type="text"
                            name="nameAndSurname"
                            placeholder="Ingrese su nombre y apellido"
                            onChange={handlerInput}
                            value={contactData.nameAndSurname}
                            required/>

                        Email:

                        <input
                            id="email"
                            type="email"
                            name="email"
                            placeholder="Ingrese su email"
                            onChange={handlerInput}
                            value={contactData.email}
                            required/>

                        Numero de teléfono:

                        <input
                            id="phoneNumber"
                            type="number"
                            name="phoneNumber"
                            placeholder="Ingrese su numero de teléfono"
                            onChange={handlerInput}
                            value={contactData.phoneNumber}
                            required/>

                        Mensaje:

                        <input
                            id="message"
                            type="text"
                            name="message"
                            placeholder="Ingrese su mensaje"
                            onChange={handlerInput}
                            value={contactData.message}
                            required/>

                        Al enviar este formulario, acepto los terminos y condiciones.

                    <button
                        id="submit-btn"
                        type="submit"
                        value="Submit">Enviar</button>
                </form>

    )
}

export default Contact;

This is the Endpoint.

const express = require('express');
const router = express.Router();
const Contact = require('../models/Contact.js');

router.post('/contact', (req, res) => {
  console.log(req.body);
  console.log(req.text);
  let contact = new Contact()
  contact.nameAndSurname = req.body.nameAndSurname
  contact.email = req.body.email
  contact.phoneNumber = req.body.phoneNumber
  contact.message = req.body.message

  contact.save((err, contactStored) => {
    if(err) {
      res.status(500).send({message: `Error ${err}`})
    }else {
      res.status(200).send({contact: contactStored})
    }
  })
})

module.exports = router;


来源: stackexchange

问:
How can I make this show the bluetooth devices list?
I want to list available Bluetooth devices and found this code in another question

I try to test it but it does not work

mainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
    ListView listView;
    private BluetoothAdapter BA;
    private ArrayList<String> mDeviceList = new ArrayList<String>();
    private Set<BluetoothDevice> pairedDevices;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=(ListView)findViewById(R.id.devicesList);

        BA = BluetoothAdapter.getDefaultAdapter();
        BA.startDiscovery();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);

    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mDeviceList.add(device.getName() + "\n" + device.getAddress());
                Log.i("BT1", device.getName() + "\n" + device.getAddress());
                listView.setAdapter(new ArrayAdapter<String>(context,
                        android.R.layout.simple_list_item_1, mDeviceList));
            }
        }
    };

    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/devicesList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="visible" />

</LinearLayout>
</code>```

It looks like this on my phone
Screenshot

Is there anything else I should do to make it work?

答:
Solved now, a kind predecessor helped me.

Maybe it's because of the system version

The old code worked for the old version of Android

And for new version try to add these ask for permission

```<code> protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        permissionRequire();
...

</code>```
```<code> private void permissionRequire() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to list available Bluetooth devices and found this code in another question

I try to test it but it does not work

mainActivity.java

public class MainActivity extends AppCompatActivity {
    ListView listView;
    private BluetoothAdapter BA;
    private ArrayList<String> mDeviceList = new ArrayList<String>();
    private Set<BluetoothDevice> pairedDevices;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=(ListView)findViewById(R.id.devicesList);

        BA = BluetoothAdapter.getDefaultAdapter();
        BA.startDiscovery();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);

    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mDeviceList.add(device.getName() + "\n" + device.getAddress());
                Log.i("BT1", device.getName() + "\n" + device.getAddress());
                listView.setAdapter(new ArrayAdapter<String>(context,
                        android.R.layout.simple_list_item_1, mDeviceList));
            }
        }
    };

    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/devicesList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="visible" />

</LinearLayout>

It looks like this on my phone
Screenshot

Is there anything else I should do to make it work?

Body:
Solved now, a kind predecessor helped me.

Maybe it's because of the system version

The old code worked for the old version of Android

And for new version try to add these ask for permission

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        permissionRequire();
...

 private void permissionRequire() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    }


问:
Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class in angular 8
ERROR in node_modules/@angular/common/http/http.d.ts:2801:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class</p>

```<code>2801 export declare class HttpClientModule {
</code>```

答: I had the same problem, it seems like there is a lot of ways to trigger the problem. I recommend trying to verify the .component, .module and the app.module declarations. Mine was triggered because I've declared the .component in app.module instead of the .module.

Body:
ERROR in node_modules/@angular/common/http/http.d.ts:2801:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

2801 export declare class HttpClientModule {


问:
Get current desktop wallpaper in ctypes
I try to get path to current wallpaper in Python using ctypes module. But as a result program returns value 1.</p>
```<code>import ctypes

SPI_GETDESKWALLPAPER = 0x0073

path = ctypes.create_unicode_buffer(260)
a = ctypes.windll.user32.SystemParametersInfoW(SPI_GETDESKWALLPAPER, 100, path, 0)
print(a)
</code>```

答:
Try this code if you want, maybe it will help you :)</p>
```<code>from os import path, getenv, getcwd
from ctypes import windll
import ctypes
from shutil import copyfile
from PIL import Image
from tempfile import NamedTemporaryFile

SPI_GETDESKWALLPAPER = 0x0073

path = ctypes.create_unicode_buffer(260)
returnImgObj = ctypes.windll.user32.SystemParametersInfoW(SPI_GETDESKWALLPAPER, 100, path, 0)

currentWallpaper = getenv(
            'APPDATA') + "\\Microsoft\\Windows\\Themes\\TranscodedWallpaper"   #this is path manuel

if returnImgObj == True:

        a= Image.open(currentWallpaper)
        a.show()
        print(str(currentWallpaper))

else:
        tempFile = NamedTemporaryFile(mode="wb", suffix='.jpg').name
        copyfile(currentWallpaper, tempFile)
        a= Image.open(currentWallpaper)
        a.show()
        print(str(currentWallpaper))

</code>```

Title: Get current desktop wallpaper in ctypes

Body:
I try to get path to current wallpaper in Python using ctypes module. But as a result program returns value 1.

import ctypes

SPI_GETDESKWALLPAPER = 0x0073

path = ctypes.create_unicode_buffer(260)
a = ctypes.windll.user32.SystemParametersInfoW(SPI_GETDESKWALLPAPER, 100, path, 0)
print(a)

Body:
Try this code if you want, maybe it will help you :)

from os import path, getenv, getcwd
from ctypes import windll
import ctypes
from shutil import copyfile
from PIL import Image
from tempfile import NamedTemporaryFile

SPI_GETDESKWALLPAPER = 0x0073

path = ctypes.create_unicode_buffer(260)
returnImgObj = ctypes.windll.user32.SystemParametersInfoW(SPI_GETDESKWALLPAPER, 100, path, 0)

currentWallpaper = getenv(
            'APPDATA') + "\\Microsoft\\Windows\\Themes\\TranscodedWallpaper"   #this is path manuel

if returnImgObj == True:

        a= Image.open(currentWallpaper)
        a.show()
        print(str(currentWallpaper))

else:
        tempFile = NamedTemporaryFile(mode="wb", suffix='.jpg').name
        copyfile(currentWallpaper, tempFile)
        a= Image.open(currentWallpaper)
        a.show()
        print(str(currentWallpaper))


问:
Is it possible to trigger a FCM push notification based on an expiry date in Firestore Database?
I am trying to build an Android app using Kotlin that sends a push notification to the user's device using FCM in Firebase when one of their items are expiring soon. However, I have not been able to figure out how to trigger the notification based on the expiry date stored in the Firestore Database for a specific item. In Firebase -> Engage -> Cloud Messaging -> Notifications -> New Notification, it seems like you can only schedule a notification based on a fixed date.

Is there a way to trigger the notification based on a value stored in the Firestore Database instead?

Logic should be:
If current_date > expiry_date then trigger push notification.

Thanks in advance.

答:
Cloud Firestore does not feature any such event, but one can schedule a Cloud Function:

https://firebase.google.com/docs/functions/schedule-functions


问:
Calculate Median Sales for each Customer in Array of Customers (Neophyte)
I have an array of customer objects generated from a csv file:

Date, Name, Sales

03/01, Alpha, 110

03/23, Alpha, 25

01/02, Beta, 135

...

and require an efficient way to create a new array of unique customers with median sales and export them back to csv. There could be as many as 500,000 records and 100,000 unique customers!

答:
-Split your source data into collections for each customer.

For each customer:

--Sort by sales

--if record count is odd, return the sales at the middle index

--if record count is even, return the avg of the records on either side of the middle

-Drop the returned record into your results array.

ContentLicense: CC BY-SA 3.0


问:
Poetry NoCompatiblePythonVersionFound
I understand that the Poetry project is working with a different version of Python than I have installed.

How might I rectify this issue though? Preferably, Poetry and the project can use the latest Python version.

Terminal

cd /mnt/c/Users/me/Documents/GitHub/project
poetry run python -m project

python3 --version
```
<h3>Output</h3>
<pre class="lang-none prettyprint-override"><code>The currently activated Python version 3.8.10 is not supported by the project (3.8.8).
Trying to find and use a compatible version.

  NoCompatiblePythonVersionFound

  Poetry was unable to find a compatible version. If you have one, you can explicitly use it via the "env use" command.

  at ~/.poetry/lib/poetry/utils/env.py:768 in create_venv
       764│                     python_minor = ".".join(python_patch.split(".")[:2])
       765│                     break
       766│
       767│             if not executable:
    →  768│                 raise NoCompatiblePythonVersionFound(
       769│                     self._poetry.package.python_versions
       770│                 )
       771│
       772│         if root_venv:

Python 3.8.10
</code>```

答:
I need to set up a virtual environment.

To do this in Conda:

conda create -n env_name python=3.8.8
```

Title: Poetry NoCompatiblePythonVersionFound

Body:
I understand that the Poetry project is working with a different version of Python than I have installed.

How might I rectify this issue though? Preferably, Poetry and the project can use the latest Python version.

Terminal

cd /mnt/c/Users/me/Documents/GitHub/project
poetry run python -m project

python3 --version

Output

The currently activated Python version 3.8.10 is not supported by the project (3.8.8).
Trying to find and use a compatible version.

  NoCompatiblePythonVersionFound

  Poetry was unable to find a compatible version. If you have one, you can explicitly use it via the "env use" command.

  at ~/.poetry/lib/poetry/utils/env.py:768 in create_venv
       764│                     python_minor = ".".join(python_patch.split(".")[:2])
       765│                     break
       766│
       767│             if not executable:
    →  768│                 raise NoCompatiblePythonVersionFound(
       769│                     self._poetry.package.python_versions
       770│                 )
       771│
       772│         if root_venv:

Python 3.8.10


问:
How to transform a column with an array of json to separate columns based on the json keys in Spark?
I have a column like this:

column

[{"key":1,"value":"aaaaa"},{"key":2,"value":"bbbbb"},{"key":3,"value":"ccccc"}]

[{"key":1,"value":"abcde"},{"key":2,"value":"bcdef"}]

[{"key":1,"value":"edcba"},{"key":3,"value":"zxcvb"},{"key":4,"value":"qwert"}]

I want to separate such column base on the keys, with each key having their column.
I've tried something like this but it didn't work:

```<code>test_schema = ArrayType(StructType([StructField("key", IntegerType()), StructField("value", StringType())]))

teste = (hits_raw
  .withColumn("keys", get_json_object("hitsCustomDimensions", "$[*].key"))
  .withColumn("teste", explode(from_json("hitsCustomDimensions", test_schema)))
  ).display()
</code>```

The output I want is something like this:

column_1
column_2
column_3
column_4

aaaaa
bbbbb
ccccc
null

abcde
bcdef
null
null

edcba
null
zxcvb
qwert

答:
Parse into array of structs then pivot the key column. You'll need some ID column to group by for the pivot, here I used monotonically_increasing_id function to add an id before inlining the array of structs.

```<code>from pyspark.sql import functions as F

df = spark.createDataFrame([
    ('[{"key":1,"value":"aaaaa"},{"key":2,"value":"bbbbb"},{"key":3,"value":"ccccc"}]',),
    ('[{"key":1,"value":"abcde"},{"key":2,"value":"bcdef"}]',),
    ('[{"key":1,"value":"edcba"},{"key":3,"value":"zxcvb"},{"key":4,"value":"qwert"}]',)
], ["column"])

test = (df.withColumn("column", F.from_json("column",  test_schema))
        .withColumn("id", F.monotonically_increasing_id())
        .selectExpr("id", "inline(column)")
        .groupBy("id").pivot("key").agg(F.first("value"))
        .drop("id")
        )

test.show()
#+-----+-----+-----+-----+
#|    1|    2|    3|    4|
#+-----+-----+-----+-----+
#|aaaaa|bbbbb|ccccc| null|
#|abcde|bcdef| null| null|
#|edcba| null|zxcvb|qwert|
#+-----+-----+-----+-----+
</code>```

You can then rename to columns to add prefix column_* if you want:

```<code>
test = test.select(*[F.col(c).alias(f"column_{c}") for c in test.columns])
</code>```

Body:
I have a column like this:

column

[{"key":1,"value":"aaaaa"},{"key":2,"value":"bbbbb"},{"key":3,"value":"ccccc"}]

[{"key":1,"value":"abcde"},{"key":2,"value":"bcdef"}]

[{"key":1,"value":"edcba"},{"key":3,"value":"zxcvb"},{"key":4,"value":"qwert"}]

I want to separate such column base on the keys, with each key having their column.
I've tried something like this but it didn't work:

test_schema = ArrayType(StructType([StructField("key", IntegerType()), StructField("value", StringType())]))

teste = (hits_raw
  .withColumn("keys", get_json_object("hitsCustomDimensions", "$[*].key"))
  .withColumn("teste", explode(from_json("hitsCustomDimensions", test_schema)))
  ).display()

The output I want is something like this:

column_1
column_2
column_3
column_4

aaaaa
bbbbb
ccccc
null

abcde
bcdef
null
null

edcba
null
zxcvb
qwert

Body:
Parse into array of structs then pivot the key column. You'll need some ID column to group by for the pivot, here I used monotonically_increasing_id function to add an id before inlining the array of structs.

from pyspark.sql import functions as F

df = spark.createDataFrame([
    ('[{"key":1,"value":"aaaaa"},{"key":2,"value":"bbbbb"},{"key":3,"value":"ccccc"}]',),
    ('[{"key":1,"value":"abcde"},{"key":2,"value":"bcdef"}]',),
    ('[{"key":1,"value":"edcba"},{"key":3,"value":"zxcvb"},{"key":4,"value":"qwert"}]',)
], ["column"])

test = (df.withColumn("column", F.from_json("column",  test_schema))
        .withColumn("id", F.monotonically_increasing_id())
        .selectExpr("id", "inline(column)")
        .groupBy("id").pivot("key").agg(F.first("value"))
        .drop("id")
        )

test.show()
#+-----+-----+-----+-----+
#|    1|    2|    3|    4|
#+-----+-----+-----+-----+
#|aaaaa|bbbbb|ccccc| null|
#|abcde|bcdef| null| null|
#|edcba| null|zxcvb|qwert|
#+-----+-----+-----+-----+

You can then rename to columns to add prefix column_* if you want:

test = test.select(*[F.col(c).alias(f"column_{c}") for c in test.columns])


问:
Commit Without Setting User Name and Email
I try to commit like this:

git commit --author='Paul Draper <my@email.org>' -m 'My commit message'
```
<p>but I get:</p>
<pre class="lang-shell prettyprint-override"><code>*** Please tell me who you are.

Run

git config --global user.email "you@example.com"
git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.
</code>```

I can set these, but I am on a shared box, and I would have to (want to) unset them afterwards:

git config user.name 'Paul Draper'
git config user.email 'my@email.org'
git commit -m 'My commit message'
git config --unset user.name
git config --unset user.email
```

That's a lot of lines for one commit!

Is there shorter way?

答:
Here's the solution that I use on our shared box. In ~/.bashrc, add the following lines:

```<code>alias gitaspaul='alias git="git -c user.name=\"Paul Draper\" -c user.email=\"my@email.org\""'
alias gitasnone='unalias git'
</code>```

It works as follows: when you're in a shell session, run gitaspaul. From that moment on, every git command until the end of the session will use your temporary credentials. When you leave the shell, the credentials are forgotten. If you want to manually forget the credentials before the end of the session, run gitasnone.

This is a nice solution because it's not specific to any one repo, and it sticks around until a natural end of your computing session (like closing your ssh session).

Here's what it looks like:

```<code>$ git commit -m "new stuff"

*** Please tell me who you are.

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.

Omit --global to set the identity only in this repository.

$ gitaspaul
$ git commit -m "new stuff"
[master f6a17cd] new stuff
2 files changed, 28 insertions(+), 6 deletions(-)
</code>```

Body:
I try to commit like this:

git commit --author='Paul Draper <my@email.org>' -m 'My commit message'

but I get:

*** Please tell me who you are.

Run

git config --global user.email "you@example.com"
git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

I can set these, but I am on a shared box, and I would have to (want to) unset them afterwards:

git config user.name 'Paul Draper'
git config user.email 'my@email.org'
git commit -m 'My commit message'
git config --unset user.name
git config --unset user.email

That's a lot of lines for one commit!

Is there shorter way?

Body:
Here's the solution that I use on our shared box. In ~/.bashrc, add the following lines:

alias gitaspaul='alias git="git -c user.name=\"Paul Draper\" -c user.email=\"my@email.org\""'
alias gitasnone='unalias git'

It works as follows: when you're in a shell session, run gitaspaul. From that moment on, every git command until the end of the session will use your temporary credentials. When you leave the shell, the credentials are forgotten. If you want to manually forget the credentials before the end of the session, run gitasnone.

This is a nice solution because it's not specific to any one repo, and it sticks around until a natural end of your computing session (like closing your ssh session).

Here's what it looks like:

$ git commit -m "new stuff"

*** Please tell me who you are.

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.

Omit --global to set the identity only in this repository.

$ gitaspaul
$ git commit -m "new stuff"
[master f6a17cd] new stuff
2 files changed, 28 insertions(+), 6 deletions(-)


问:
Laravel8: make all dynamic inputs store into the same database table row
I've made a form with static and dynamic inputs that I need them all to be stored in the same row of a database. Right now where I input them they generate a new row in DB for the dynamic inputs. Am I supposed to do a custom_id input in order to store them properly?
Here is the code from my controller:

```<code> public function createClients(request $request){
        $clients = new Clients;
        $clients->nume=$request->nume;
        $clients->locatie=$request->locatie;
        $clients->cif=$request->cif;
        $clients->cif1=$request->cif1;
        $clients->tara=$request->tara;
        $clients->judet=$request->judet;
        $clients->rgc=$request->rgc;
        $clients->rgc1=$request->rgc1;
        $clients->rgc2=$request->rgc2;
        $clients->rgc3=$request->rgc3;
        $clients->localitate=$request->localitate;
        $clients->tip=$request->tip;
        $clients->strada=$request->strada;
        $clients->categorie=$request->categorie;

        foreach ($request->addMoreInputFields as $key => $value) {
            Clients::create($value);
        }

        return back()->with('success', 'New subject has been added.');
</code>```

Also here is my form and scripts:

```<code><form action="{{route('createClients')}}" method="POST">
  @csrf
  <div class="container-fluid">
<div class="col-6" style ="float:left;" >
<div class="row">
<input type="text" name="nume"  class="form-control" placeholder="Nume Client">
</div>
<div class="row">
<label for="">CIF</label>
    <select name="cif" size="1" class="text" style="width:200"><option value="" selected="selected"> - </option><option value="RO">RO - Romania</option><option value="CNP">CNP - Cod Numeric Personal</option><option value="PAS">PAS - Numar Pasaport</option><option value="SRV">SRV - SUA</option><option value="AT">AT - Austria</option><option value="BE">BE - Belgia</option><option value="BG">BG - Bulgaria</option><option value="CY">CY - Cipru</option><option value="CZ">CZ - Republica Ceha</option><option value="DE">DE - Germania</option><option value="DK">DK - Danemarca</option><option value="EE">EE - Estonia</option><option value="EL">EL - Grecia</option><option value="ES">ES - Spania</option><option value="FI">FI - Finlanda</option><option value="FR">FR - Franta</option><option value="GB">GB - Marea Britanie</option><option value="HU">HU - Ungaria</option><option value="IE">IE - Irlanda</option><option value="IT">IT - Italia</option><option value="LT">LT - Lituania</option><option value="LU">LU - Luxemburg</option><option value="LV">LV - Letonia</option><option value="MT">MT - Malta</option><option value="NL">NL - Olanda</option><option value="PL">PL - Polonia</option><option value="PT">PT - Portugalia</option><option value="SE">SE - Suedia</option><option value="SI">SI - Slovenia</option><option value="SK">SK - Slovacia</option><option value="TR">TR - Turcia</option><option value="UK">UK - Marea Britanie</option></select>
    <input type="text" class="text" name="cif1" value="" size="16" maxlength="13">
</div>
<div class="row">
<label for="">Reg Com</label>
      <input type="text" class="text" name="rgc" value="" size="16" maxlength="13">
      <select name="rgc1" size="1" class="text" style="width:140"><option value="" selected="selected"> - </option><option value="40">40 - BUCURESTI</option><option value="01">01 - ALBA</option><option value="02">02 - ARAD</option><option value="03">03 - ARGES</option><option value="04">04 - BACAU</option><option value="05">05 - BIHOR</option><option value="06">06 - BISTRITA-NASAUD</option><option value="07">07 - BOTOSANI</option><option value="08">08 - BRASOV</option><option value="09">09 - BRAILA</option><option value="10">10 - BUZAU</option><option value="11">11 - CARAS-SEVERIN</option><option value="12">12 - CLUJ</option><option value="13">13 - CONSTANTA</option><option value="14">14 - COVASNA</option><option value="15">15 - DIMBOVITA</option><option value="16">16 - DOLJ</option><option value="17">17 - GALATI</option><option value="18">18 - GORJ</option><option value="19">19 - HARGHITA</option><option value="20">20 - HUNEDOARA</option><option value="21">21 - IALOMITA</option><option value="22">22 - IASI</option><option value="23">23 - ILFOV</option><option value="24">24 - MARAMURES</option><option value="25">25 - MEHEDINTI</option><option value="26">26 - MURES</option><option value="27">27 - NEAMT</option><option value="28">28 - OLT</option><option value="29">29 - PRAHOVA</option><option value="30">30 - SATU MARE</option><option value="31">31 - SALAJ</option><option value="32">32 - SIBIU</option><option value="33">33 - SUCEAVA</option><option value="34">34 - TELEORMAN</option><option value="35">35 - TIMIS</option><option value="36">36 - TULCEA</option><option value="37">37 - VASLUI</option><option value="38">38 - VALCEA</option><option value="39">39 - VRANCEA</option><option value="51">51 - CALARASI</option><option value="52">52 - GIURGIU</option></select>
      <input type="text" class="text" name="rgc2" value="" size="7" maxlength="6">
      <select name="rgc3" size="1" class="text"><option value="" selected="selected"></option><option value="2022">2022</option><option value="2021">2021</option><option value="2020">2020</option><option value="2019">2019</option><option value="2018">2018</option><option value="2017">2017</option><option value="2016">2016</option><option value="2015">2015</option><option value="2014">2014</option><option value="2013">2013</option><option value="2012">2012</option><option value="2011">2011</option><option value="2010">2010</option><option value="2009">2009</option><option value="2008">2008</option><option value="2007">2007</option><option value="2006">2006</option><option value="2005">2005</option><option value="2004">2004</option><option value="2003">2003</option><option value="2002">2002</option><option value="2001">2001</option><option value="2000">2000</option><option value="1999">1999</option><option value="1998">1998</option><option value="1997">1997</option><option value="1996">1996</option><option value="1995">1995</option><option value="1994">1994</option><option value="1993">1993</option><option value="1992">1992</option><option value="1991">1991</option><option value="1990">1990</option></select>
</div>
<div class="row">
<input type="text" name="localitate" id="localitate" class="form-control" placeholder="Localitatea">
</div>
<div class="row">
<label for="">Tip Furnizor</label>
      <td class="hilite2"><select name="tip" size="1" class="text"><option value="1">Furnizor</option><option value="2">Beneficiar</option><option value="3">Ambele</option><option value="4">Transportator</option><option value="5">Casa de Expeditie</option></select></td>
</div>
<div class="row">
<label for="">Situatie</label>
        <select name="categorie" size="1" class="text"><option value="0" selected="selected">NOU</option><option value="1">BUN</option><option value="2">RAU</option><option value="7">FACTORING</option><option value="8">MOTORINA</option><option value="9">CESIUNE</option></select>
</div>
<div class="row">
<label for="">Agent</label>
        <select name="agent" size="1" class="text"><option value="0" selected="selected"></option><option value="1">admin</option><option value="21">alexandru</option><option value="20">taga</option></select>
</div>
<div class="row">
<label for="">Contract</label>
<input type="text" name="contract" class="text">
</div>
<div class="row">
<label for="obs">Observatii</label>
    <textarea name="obs" class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>

</div>
  <div class="col-6" id="dynamicTable" style ="float:right; maxlength=6;">
  <div class="row">
  <input type="text" class="text" name="tara" id="tara" placeholder="tara" value="" size="16" maxlength="13">
    <label for="">Judet</label>
    <select name="judet" id="judet" size="1" class="text"><option value="" selected="selected"></option><option value="B">BUCURESTI</option><option value="B1">SECTOR 1</option><option value="B2">SECTOR 2</option><option value="B3">SECTOR 3</option><option value="B4">SECTOR 4</option><option value="B5">SECTOR 5</option><option value="B6">SECTOR 6</option><option value="AB">ALBA</option><option value="AR">ARAD</option><option value="AG">ARGES</option><option value="BC">BACAU</option><option value="BH">BIHOR</option><option value="BN">BISTRITA-NASAUD</option><option value="BT">BOTOSANI</option><option value="BV">BRASOV</option><option value="BR">BRAILA</option><option value="BZ">BUZAU</option><option value="CS">CARAS-SEVERIN</option><option value="CL">CALARASI</option><option value="CJ">CLUJ</option><option value="CT">CONSTANTA</option><option value="CV">COVASNA</option><option value="DB">DAMBOVITA</option><option value="DJ">DOLJ</option><option value="GL">GALATI</option><option value="GR">GIURGIU</option><option value="GJ">GORJ</option><option value="HR">HARGHITA</option><option value="HD">HUNEDOARA</option><option value="IL">IALOMITA</option><option value="IS">IASI</option><option value="IF">ILFOV</option><option value="MM">MARAMURES</option><option value="MH">MEHEDINTI</option><option value="MS">MURES</option><option value="NT">NEAMT</option><option value="OT">OLT</option><option value="PH">PRAHOVA</option><option value="SM">SATU MARE</option><option value="SJ">SALAJ</option><option value="SB">SIBIU</option><option value="SV">SUCEAVA</option><option value="TR">TELEORMAN</option><option value="TM">TIMIS</option><option value="TL">TULCEA</option><option value="VS">VASLUI</option><option value="VL">VALCEA</option><option value="VN">VRANCEA</option></select>
    <label for="">Cod Postal</label>
    <input type="text" id="cp" class="text" name="cp" title="cod postal" value="" size="6" maxlength="6">
</div>
<div class="row">
<input type="text" id="strada" name="addMoreInputFields[0][strada]"  class="form-control" placeholder="Strada">
</div>
<div class="row">
<input type="text" id="telefon"  name="addMoreInputFields[0][telefon]"  class="form-control" placeholder="telefon">
  <div class="row">
  <input type="text" id="email" name="addMoreInputFields[0][email]"  class="form-control" placeholder="email">
</div>
<div class="row">
<input type="text" id="banca"  placeholder ="banca" class="form-control" name="addMoreInputFields[0][banca]" class="text">
</div>
<div class="row">
<input type="text" placeholder="iban" class="form-control"  id="iban" name="addMoreInputFields[0][iban]" class="text">
</div>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
  </div>
  </div>
  <button type="submit" class="btn btn-success">Success</button>
</form>

</div>

<script type="text/javascript">
 var i = 0;

       $("#add").click(function(){

           ++i;

           $("#dynamicTable").append('<tr><td><input type="text" name="addMoreInputFields['+i+'][banca]" placeholder="banca" class="form-control" /></td><td><input type="text" name="addMoreInputFields['+i+'][iban]" placeholder="iban" class="form-control" /></td><td><input type="text" name="addMoreInputFields['+i+'][locatie]" placeholder="locatie" class="form-control"/></td><td><input type="text" name="addMoreInputFields['+i+'][strada]" placeholder="strada" class="form-control"/></td><td><input type="text" name="addMoreInputFields['+i+'][telefon]" placeholder="telefon" class="form-control" /></td><td><button type="button" class="btn btn-danger remove-tr">Remove</button></td></tr>');
       });

       $(document).on('click', '.remove-tr', function(){
            $(this).parents('tr').remove();
       });

</script>
<script src="//code.jquery.com/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.6/handlebars.min.js"></script>
<script type="text/javascript" src="{{ asset('/chart-area-demo.js') }}"></script>
            <script type="text/javascript" src="{{ asset('/chart-bar-demo.js') }}"></script>
            <script type="text/javascript" src="{{ asset('/datatables-demo.js') }}"></script>
            <script type="text/javascript" src="{{ asset('/datatables-simple-demo.js') }}"></script>
            <script type="text/javascript" src="{{ asset('/scripts.js') }}"></script>

</code>```

And an image from my database (i inputed random letters just to see if it works, those 2 rows should be only one but because its dynamic input it doesn't add up)

Should I make a new migration to add more tables into DB such as email2, telefon2 banca2 iban2 etc? Or is there something wrong in my code.

答:
I'm not 100% sure what your trying to do here, but you are creating a new Clients every loop in the foreach

Also your are not saving the $client with the static fields

Assuming you have a column for every dynamic field and have them in your $fillable array in the Clients model
You could do something like this instead of your current foreach

```<code>foreach ($request->addMoreInputFields as $key => $value) {
        $clients->$key = $value;
    }
 $clients-save();
</code>```

You didn't show your database table so I'm not sure if it will work, remember that for each field there needs to be a column in your table, the $clients->num value will store in the num column and so on, so if a dynamic field has the same name as a static field, the dynamic field will replace the static one  if you use the code I provided. If you are trying to store several "clients" each client should be in its own row

Body:
I've made a form with static and dynamic inputs that I need them all to be stored in the same row of a database. Right now where I input them they generate a new row in DB for the dynamic inputs. Am I supposed to do a custom_id input in order to store them properly?
Here is the code from my controller:

 public function createClients(request $request){
        $clients = new Clients;
        $clients->nume=$request->nume;
        $clients->locatie=$request->locatie;
        $clients->cif=$request->cif;
        $clients->cif1=$request->cif1;
        $clients->tara=$request->tara;
        $clients->judet=$request->judet;
        $clients->rgc=$request->rgc;
        $clients->rgc1=$request->rgc1;
        $clients->rgc2=$request->rgc2;
        $clients->rgc3=$request->rgc3;
        $clients->localitate=$request->localitate;
        $clients->tip=$request->tip;
        $clients->strada=$request->strada;
        $clients->categorie=$request->categorie;

        foreach ($request->addMoreInputFields as $key => $value) {
            Clients::create($value);
        }

        return back()->with('success', 'New subject has been added.');

Also here is my form and scripts:

<form action="{{route('createClients')}}" method="POST">
  @csrf

<input type="text" name="nume"  class="form-control" placeholder="Nume Client">

CIF
    <select name="cif" size="1" class="text" style="width:200"><option value="" selected="selected"> - </option><option value="RO">RO - Romania</option><option value="CNP">CNP - Cod Numeric Personal</option><option value="PAS">PAS - Numar Pasaport</option><option value="SRV">SRV - SUA</option><option value="AT">AT - Austria</option><option value="BE">BE - Belgia</option><option value="BG">BG - Bulgaria</option><option value="CY">CY - Cipru</option><option value="CZ">CZ - Republica Ceha</option><option value="DE">DE - Germania</option><option value="DK">DK - Danemarca</option><option value="EE">EE - Estonia</option><option value="EL">EL - Grecia</option><option value="ES">ES - Spania</option><option value="FI">FI - Finlanda</option><option value="FR">FR - Franta</option><option value="GB">GB - Marea Britanie</option><option value="HU">HU - Ungaria</option><option value="IE">IE - Irlanda</option><option value="IT">IT - Italia</option><option value="LT">LT - Lituania</option><option value="LU">LU - Luxemburg</option><option value="LV">LV - Letonia</option><option value="MT">MT - Malta</option><option value="NL">NL - Olanda</option><option value="PL">PL - Polonia</option><option value="PT">PT - Portugalia</option><option value="SE">SE - Suedia</option><option value="SI">SI - Slovenia</option><option value="SK">SK - Slovacia</option><option value="TR">TR - Turcia</option><option value="UK">UK - Marea Britanie</option></select>
    <input type="text" class="text" name="cif1" value="" size="16" maxlength="13">

Reg Com
      <input type="text" class="text" name="rgc" value="" size="16" maxlength="13">
      <select name="rgc1" size="1" class="text" style="width:140"><option value="" selected="selected"> - </option><option value="40">40 - BUCURESTI</option><option value="01">01 - ALBA</option><option value="02">02 - ARAD</option><option value="03">03 - ARGES</option><option value="04">04 - BACAU</option><option value="05">05 - BIHOR</option><option value="06">06 - BISTRITA-NASAUD</option><option value="07">07 - BOTOSANI</option><option value="08">08 - BRASOV</option><option value="09">09 - BRAILA</option><option value="10">10 - BUZAU</option><option value="11">11 - CARAS-SEVERIN</option><option value="12">12 - CLUJ</option><option value="13">13 - CONSTANTA</option><option value="14">14 - COVASNA</option><option value="15">15 - DIMBOVITA</option><option value="16">16 - DOLJ</option><option value="17">17 - GALATI</option><option value="18">18 - GORJ</option><option value="19">19 - HARGHITA</option><option value="20">20 - HUNEDOARA</option><option value="21">21 - IALOMITA</option><option value="22">22 - IASI</option><option value="23">23 - ILFOV</option><option value="24">24 - MARAMURES</option><option value="25">25 - MEHEDINTI</option><option value="26">26 - MURES</option><option value="27">27 - NEAMT</option><option value="28">28 - OLT</option><option value="29">29 - PRAHOVA</option><option value="30">30 - SATU MARE</option><option value="31">31 - SALAJ</option><option value="32">32 - SIBIU</option><option value="33">33 - SUCEAVA</option><option value="34">34 - TELEORMAN</option><option value="35">35 - TIMIS</option><option value="36">36 - TULCEA</option><option value="37">37 - VASLUI</option><option value="38">38 - VALCEA</option><option value="39">39 - VRANCEA</option><option value="51">51 - CALARASI</option><option value="52">52 - GIURGIU</option></select>
      <input type="text" class="text" name="rgc2" value="" size="7" maxlength="6">
      <select name="rgc3" size="1" class="text"><option value="" selected="selected"></option><option value="2022">2022</option><option value="2021">2021</option><option value="2020">2020</option><option value="2019">2019</option><option value="2018">2018</option><option value="2017">2017</option><option value="2016">2016</option><option value="2015">2015</option><option value="2014">2014</option><option value="2013">2013</option><option value="2012">2012</option><option value="2011">2011</option><option value="2010">2010</option><option value="2009">2009</option><option value="2008">2008</option><option value="2007">2007</option><option value="2006">2006</option><option value="2005">2005</option><option value="2004">2004</option><option value="2003">2003</option><option value="2002">2002</option><option value="2001">2001</option><option value="2000">2000</option><option value="1999">1999</option><option value="1998">1998</option><option value="1997">1997</option><option value="1996">1996</option><option value="1995">1995</option><option value="1994">1994</option><option value="1993">1993</option><option value="1992">1992</option><option value="1991">1991</option><option value="1990">1990</option></select>

<input type="text" name="localitate" id="localitate" class="form-control" placeholder="Localitatea">

Tip Furnizor
      <select name="tip" size="1" class="text"><option value="1">Furnizor</option><option value="2">Beneficiar</option><option value="3">Ambele</option><option value="4">Transportator</option><option value="5">Casa de Expeditie</option></select>

Situatie
        <select name="categorie" size="1" class="text"><option value="0" selected="selected">NOU</option><option value="1">BUN</option><option value="2">RAU</option><option value="7">FACTORING</option><option value="8">MOTORINA</option><option value="9">CESIUNE</option></select>

Agent
        <select name="agent" size="1" class="text"><option value="0" selected="selected"></option><option value="1">admin</option><option value="21">alexandru</option><option value="20">taga</option></select>

Contract
<input type="text" name="contract" class="text">

Observatii
    <textarea name="obs" class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>

  <input type="text" class="text" name="tara" id="tara" placeholder="tara" value="" size="16" maxlength="13">
    Judet
    <select name="judet" id="judet" size="1" class="text"><option value="" selected="selected"></option><option value="B">BUCURESTI</option><option value="B1">SECTOR 1</option><option value="B2">SECTOR 2</option><option value="B3">SECTOR 3</option><option value="B4">SECTOR 4</option><option value="B5">SECTOR 5</option><option value="B6">SECTOR 6</option><option value="AB">ALBA</option><option value="AR">ARAD</option><option value="AG">ARGES</option><option value="BC">BACAU</option><option value="BH">BIHOR</option><option value="BN">BISTRITA-NASAUD</option><option value="BT">BOTOSANI</option><option value="BV">BRASOV</option><option value="BR">BRAILA</option><option value="BZ">BUZAU</option><option value="CS">CARAS-SEVERIN</option><option value="CL">CALARASI</option><option value="CJ">CLUJ</option><option value="CT">CONSTANTA</option><option value="CV">COVASNA</option><option value="DB">DAMBOVITA</option><option value="DJ">DOLJ</option><option value="GL">GALATI</option><option value="GR">GIURGIU</option><option value="GJ">GORJ</option><option value="HR">HARGHITA</option><option value="HD">HUNEDOARA</option><option value="IL">IALOMITA</option><option value="IS">IASI</option><option value="IF">ILFOV</option><option value="MM">MARAMURES</option><option value="MH">MEHEDINTI</option><option value="MS">MURES</option><option value="NT">NEAMT</option><option value="OT">OLT</option><option value="PH">PRAHOVA</option><option value="SM">SATU MARE</option><option value="SJ">SALAJ</option><option value="SB">SIBIU</option><option value="SV">SUCEAVA</option><option value="TR">TELEORMAN</option><option value="TM">TIMIS</option><option value="TL">TULCEA</option><option value="VS">VASLUI</option><option value="VL">VALCEA</option><option value="VN">VRANCEA</option></select>
    Cod Postal
    <input type="text" id="cp" class="text" name="cp" title="cod postal" value="" size="6" maxlength="6">

<input type="text" id="strada" name="addMoreInputFields[0][strada]"  class="form-control" placeholder="Strada">

<input type="text" id="telefon"  name="addMoreInputFields[0][telefon]"  class="form-control" placeholder="telefon">

  <input type="text" id="email" name="addMoreInputFields[0][email]"  class="form-control" placeholder="email">

<input type="text" id="banca"  placeholder ="banca" class="form-control" name="addMoreInputFields[0][banca]" class="text">

<input type="text" placeholder="iban" class="form-control"  id="iban" name="addMoreInputFields[0][iban]" class="text">

<button type="button" name="add" id="add" class="btn btn-success">Add More</button>

  <button type="submit" class="btn btn-success">Success</button>
</form>

And an image from my database (i inputed random letters just to see if it works, those 2 rows should be only one but because its dynamic input it doesn't add up)

Should I make a new migration to add more tables into DB such as email2, telefon2 banca2 iban2 etc? Or is there something wrong in my code.

Body:
I'm not 100% sure what your trying to do here, but you are creating a new Clients every loop in the foreach

Also your are not saving the $client with the static fields

Assuming you have a column for every dynamic field and have them in your $fillable array in the Clients model
You could do something like this instead of your current foreach

foreach ($request->addMoreInputFields as $key => $value) {
        $clients->$key = $value;
    }
 $clients-save();

You didn't show your database table so I'm not sure if it will work, remember that for each field there needs to be a column in your table, the $clients->num value will store in the num column and so on, so if a dynamic field has the same name as a static field, the dynamic field will replace the static one  if you use the code I provided. If you are trying to store several "clients" each client should be in its own row


问:
How to make some checkbox options selected by default in ChoiceType Symfony Form Builder?
I am building a checkbox form that has 4 possible choices.
What would be the method of making 2 and 3 (Green and Blue)
checked by default but leaving the remaining two items unchecked
by default?

I believe the "data" item of the $builder array might
be the correct answer, but I am not sure how...
Any help would be appreciated! Thank you!

```<code>$builder->add(
          "What color do you like?",
          ChoiceType::class,
          [
          'label' => "What color do you like?",
          'choices' => [1 => "Red", 2 => "Green", 3 => "Blue", 4=>"Orange"],
          'expanded' => true,
          'multiple' => true,
          'required' => true,
          'help' => "Pick as many as you like!",
      ]
                );
</code>```

I expect that I should be able to code in something like "2=1,3=1" somewhere to indicate that both of my choices should be checked by default, but it is not clear how I would indicate that those two choices should be checked by default.

答:
ChoiceType functionality can sometimes be (or seem) quite weird and can be hard to work with. It took me some time to figure out how to set default values. Here is how I did it.

DaysType.php

->add('days', ChoiceType::class, [
    'multiple' => true,
    'expanded' => true,
    'choices' => [
        "Mo" => "Mo",
        "Tu" => "Tu",
        "We" => "We",
        "Th" => "Th",
        "Fr" => "Fr",
        "Sa" => "Sa",
        "Su" => "Su",
    ],
])
```
<p><strong>Be aware</strong> that the first <code>"Mo"</code> <strong>before</strong> the <code>=></code> is the title/label you will see next to your checkbox. Like you can see in my picture.</p>
<p><img src="https://i.stack.imgur.com/SPvyH.png" alt="enter image description here" /></p>
<p>The <code>"Mo"</code> <strong>after</strong> the <code>=></code> is the data that will be send back to your controller once the user submits the form. Its also the value you can see on your input field its <code>value</code> attribute.</p>
<p><strong>Now how to make them checked by default:</strong></p>
<p>DaysController.php</p>
<pre class="lang-php prettyprint-override"><code>$days = new Days();

// Used to set the default selected values. Options are: Ma, Di, Wo, Do, Vr, Za, Zo.
$days->setDays([
    "Mo", "Tu", "We", "Sa"
]);

// Create form
$form = $this->createForm(DaysType::class, $days);
$form->handleRequest($request);

// ... render page etc.
</code>```

So now by default Mo, Tu, We and Sa are checked.

This is how the data looks like when the user submits the form without changing the checks:

-days: array:4 [▼
    0 => "Mo"
    1 => "Tu"
    2 => "We"
    3 => "Sa"
]
```

I do not know how to get an array returned with all possibilities. And with true/false but this works for me. I will probably json_encode the array and save it like that in the database.

Body:
I am building a checkbox form that has 4 possible choices.
What would be the method of making 2 and 3 (Green and Blue)
checked by default but leaving the remaining two items unchecked
by default?

I believe the "data" item of the $builder array might
be the correct answer, but I am not sure how...
Any help would be appreciated! Thank you!

$builder->add(
          "What color do you like?",
          ChoiceType::class,
          [
          'label' => "What color do you like?",
          'choices' => [1 => "Red", 2 => "Green", 3 => "Blue", 4=>"Orange"],
          'expanded' => true,
          'multiple' => true,
          'required' => true,
          'help' => "Pick as many as you like!",
      ]
                );

I expect that I should be able to code in something like "2=1,3=1" somewhere to indicate that both of my choices should be checked by default, but it is not clear how I would indicate that those two choices should be checked by default.

Body:
ChoiceType functionality can sometimes be (or seem) quite weird and can be hard to work with. It took me some time to figure out how to set default values. Here is how I did it.

DaysType.php

->add('days', ChoiceType::class, [
    'multiple' => true,
    'expanded' => true,
    'choices' => [
        "Mo" => "Mo",
        "Tu" => "Tu",
        "We" => "We",
        "Th" => "Th",
        "Fr" => "Fr",
        "Sa" => "Sa",
        "Su" => "Su",
    ],
])

Be aware that the first "Mo" before the => is the title/label you will see next to your checkbox. Like you can see in my picture.

The "Mo" after the => is the data that will be send back to your controller once the user submits the form. Its also the value you can see on your input field its value attribute.

Now how to make them checked by default:

DaysController.php

$days = new Days();

// Used to set the default selected values. Options are: Ma, Di, Wo, Do, Vr, Za, Zo.
$days->setDays([
    "Mo", "Tu", "We", "Sa"
]);

// Create form
$form = $this->createForm(DaysType::class, $days);
$form->handleRequest($request);

// ... render page etc.

So now by default Mo, Tu, We and Sa are checked.

This is how the data looks like when the user submits the form without changing the checks:

-days: array:4 [▼
    0 => "Mo"
    1 => "Tu"
    2 => "We"
    3 => "Sa"
]

I do not know how to get an array returned with all possibilities. And with true/false but this works for me. I will probably json_encode the array and save it like that in the database.


问:
Type safety in Dart using Container
I found something strange in dart. If there is a list that contains instances of a base class (in this example Super), the list can be set with a list of inherited instances. It seems that this changes the list type at runtime.

Is this intended behavior or is this a bug in Dart?

```<code>abstract class Super {}

class A extends Super {}

class B extends Super {}

class Container {
List<Super> mylist = [];
Container(this.mylist);
}

void main() {
// 1. dont't works
final container = Container(<A>[A(), A()]);
// 2. works
final container = Container([A(), A()]);
print(container.mylist.runtimeType);

container.mylist.add(B());
print(container.mylist);
}
</code>```

If case 1 is used in the code above I get the following error:

```<code>JSArray<A>
Uncaught Error: TypeError: Instance of 'B': type 'B' is not a subtype of type 'A'
</code>```

The error is at the line where I try to add an instance of B:

```<code>container.mylist.add(B());
</code>```

答:
Dart has a system called type promotion, where it can promote the type of a variable, similar to type inference.

It works as a cast. On the first example you've explicit promoted the type of your list to be of type A, so there's nothing strange about this.

Take a look at the first article that explains this mechanism.

Title: Type safety in Dart using Container

Body:
I found something strange in dart. If there is a list that contains instances of a base class (in this example Super), the list can be set with a list of inherited instances. It seems that this changes the list type at runtime.

Is this intended behavior or is this a bug in Dart?

abstract class Super {}

class A extends Super {}

class B extends Super {}

class Container {
List<Super> mylist = [];
Container(this.mylist);
}

void main() {
// 1. dont't works
final container = Container([A(), A()]);
// 2. works
final container = Container([A(), A()]);
print(container.mylist.runtimeType);

container.mylist.add(B());
print(container.mylist);
}

If case 1 is used in the code above I get the following error:

JSArray
Uncaught Error: TypeError: Instance of 'B': type 'B' is not a subtype of type 'A'

The error is at the line where I try to add an instance of B:

container.mylist.add(B());


问:
Find file in directory with the max number given a set of different file names
Problem Description

I have a list of files ["FA_1","FA_2","FB_1","FB_2","FC_1","FC_2"]. That list has 3 different file names FA, FB and FC. For each of FA, FB and FC, I am trying to retrieve the one with the max number.  The following script that I coded does that. But it's so complicated and ugly.

Is there a way to make it simpler?

A similar question was asked in Find file in directory with the highest number in the filename. But, they are only using the same file name.

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

import sys
import os
from collections import defaultdict

def load_newest_files():
    # Retrieve all files for the component in question
    list_of_files = defaultdict(list)
    new_list_of_files = []
    files = ["FA_1","FA_2","FB_1","FB_2","FC_1","FC_2"]

    # Split files and take the filename without the id.
    # The files are not separated in bucket of FA, FB and FC
    # I can now retrieve the file with the max number and put
    # it in a list
    for file in files:
        list_of_files[file.split("_")[0]].append(file)

    for key,value in list_of_files.items():
        new_list_of_files.append(max(value))

    print(new_list_of_files)

def main():
    load_newest_files()

if __name__ == "__main__":
    main()
</code>```

答:
You can use itertools.groupby and create custom grouping and maximum functions for the key arguments. Example is shown below.

```<code>from itertools import groupby

def custom_group(item):
    x, _ = item.split("_")
    return x
def custom_max(item):
    _, y = item.split("_")
    return int(y)

for _, v in groupby(files, key=custom_group):
    val = max(v, key=custom_max)
    new_list_of_files.append(val)

print(new_list_of_files)
> ['FA_2', 'FB_2', 'FC_2']
</code>```

Please make sure to read the caveats surrounding itertools.groupby regarding the sort order of your input data.

Body:
Problem Description

I have a list of files ["FA_1","FA_2","FB_1","FB_2","FC_1","FC_2"]. That list has 3 different file names FA, FB and FC. For each of FA, FB and FC, I am trying to retrieve the one with the max number.  The following script that I coded does that. But it's so complicated and ugly.

Is there a way to make it simpler?

A similar question was asked in Find file in directory with the highest number in the filename. But, they are only using the same file name.

#!/usr/bin/env python

import sys
import os
from collections import defaultdict

def load_newest_files():
    # Retrieve all files for the component in question
    list_of_files = defaultdict(list)
    new_list_of_files = []
    files = ["FA_1","FA_2","FB_1","FB_2","FC_1","FC_2"]

    # Split files and take the filename without the id.
    # The files are not separated in bucket of FA, FB and FC
    # I can now retrieve the file with the max number and put
    # it in a list
    for file in files:
        list_of_files[file.split("_")[0]].append(file)

    for key,value in list_of_files.items():
        new_list_of_files.append(max(value))

    print(new_list_of_files)

def main():
    load_newest_files()

if __name__ == "__main__":
    main()

Body:
You can use itertools.groupby and create custom grouping and maximum functions for the key arguments. Example is shown below.

from itertools import groupby

def custom_group(item):
    x, _ = item.split("_")
    return x
def custom_max(item):
    _, y = item.split("_")
    return int(y)

for _, v in groupby(files, key=custom_group):
    val = max(v, key=custom_max)
    new_list_of_files.append(val)

print(new_list_of_files)
> ['FA_2', 'FB_2', 'FC_2']

Please make sure to read the caveats surrounding itertools.groupby regarding the sort order of your input data.


问:
How can I check that the installed packages match Pipfile.lock using pipenv?
In my tests, I would like to run a command to make sure that the installed packages in my virtual environment match the packages found in Pipfile.lock.

Is there a command like this?

```<code>pipenv checkifinstalled || exit 1
</code>```

答:
This problem can be reduced down to these two steps:

Convert Pipfile.lock into a requirements.txt file (in the format generated by pip freeze).

This is easily done by running pipenv requirements (or pipenv requirements --dev). (Note that this command is supported in pipenv >= 2022.4.8)

Check that the installed packages match the generated requirements.txt file.

Solutions to this are found under this question: Check if my Python has all required packages

Implementation:

Here is how I put it all together in a test:

import pkg_resources
import subprocess
import unittest

class DependencyChecks(unittest.TestCase):
    def test_requirements_installed(self):
        requirements_lines = subprocess.check_output(["pipenv", "requirements", "--dev"], text=True).splitlines()
        req_lines = [line for line in requirements_lines if not line.startswith("-i ")]
        requirements = pkg_resources.parse_requirements(req_lines)
        for requirement in requirements:
            req = str(requirement)
            with self.subTest(requirement=req):
                pkg_resources.require(req)
```

Body:
In my tests, I would like to run a command to make sure that the installed packages in my virtual environment match the packages found in Pipfile.lock.

Is there a command like this?

pipenv checkifinstalled || exit 1


问:
Python ModuleNotFoundError while importing a module in conftest for Pytest framework
My project structure

```<code>mt-kart
     |
      --> src/data_kart
     |        |
     |         -->apis
     |        |
     |         -->__init__.py
     |        |
     |         -->main.py
      --> tests
             |
              -->__init__.py
             |
              -->conftest.py
             |
              -->test_others.py

</code>```

conftest.py has the following line.

from data_kart.main import fastapi_app

When run pytest from command line from project root(mt-kart). I get the following error

ModuleNotFoundError No module named 'data_kart'

How to make data_kart visible for conftest.py .

答:
Option 1

Use relative imports:

```<code>from ..src.data_kart.main import fastapi_app
fastapi_app()
</code>```

Please note, the above requires running conftest.py outside the project's directory, like this:

```<code>python -m mt-kart.tests.conftest
</code>```

Option 2

Use the below in conftest.py (ref):

```<code>import sys
import os

# getting the name of the directory where the this file is present.
current = os.path.dirname(os.path.realpath(__file__))

# Getting the parent directory name where the current directory is present.
parent = os.path.dirname(current)

# adding the parent directory to the sys.path.
sys.path.append(parent)

# import the module
from src.data_kart.main import fastapi_app

# call the function
fastapi_app()
</code>```

And if it happens for a module being outside the parent directory of tests, then you can get the parent of the parent direcory and add that one to the sys.path. For example:

```<code>parentparent = os.path.dirname(parent)
sys.path.append(parentparent)
</code>```

Option 3

Same as Option 2, but shorter.

```<code>import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from src.data_kart.main import fastapi_app
fastapi_app()
</code>```

Option 4

Options 2 and 3 would work for smaller projects, where only a couple of files need to be updated with the code above. However, for larger projects, you may consider including the directory containing your package directory in PYTHONPATH, as described here (Option 3).

Body:
My project structure

mt-kart
     |
      --> src/data_kart
     |        |
     |         -->apis
     |        |
     |         -->__init__.py
     |        |
     |         -->main.py
      --> tests
             |
              -->__init__.py
             |
              -->conftest.py
             |
              -->test_others.py

conftest.py has the following line.

from data_kart.main import fastapi_app

When run pytest from command line from project root(mt-kart). I get the following error

ModuleNotFoundError No module named 'data_kart'

How to make data_kart visible for conftest.py .

Body:
Option 1

Use relative imports:

from ..src.data_kart.main import fastapi_app
fastapi_app()

Please note, the above requires running conftest.py outside the project's directory, like this:

python -m mt-kart.tests.conftest

Option 2

Use the below in conftest.py (ref):

import sys
import os

# getting the name of the directory where the this file is present.
current = os.path.dirname(os.path.realpath(__file__))

# Getting the parent directory name where the current directory is present.
parent = os.path.dirname(current)

# adding the parent directory to the sys.path.
sys.path.append(parent)

# import the module
from src.data_kart.main import fastapi_app

# call the function
fastapi_app()

And if it happens for a module being outside the parent directory of tests, then you can get the parent of the parent direcory and add that one to the sys.path. For example:

parentparent = os.path.dirname(parent)
sys.path.append(parentparent)

Option 3

Same as Option 2, but shorter.

import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from src.data_kart.main import fastapi_app
fastapi_app()

Option 4

Options 2 and 3 would work for smaller projects, where only a couple of files need to be updated with the code above. However, for larger projects, you may consider including the directory containing your package directory in PYTHONPATH, as described here (Option 3).


问:
Vite.js React Build Not Redirecting On Netlify And Vercel
I made a react build with vite.js.
When building for production and testing on local host all is working fine. But when i deploy to Netlify or vercel routes that i created with react-router are not accessible via entering their  url directly, but only from the main page ('/') via using the links inside of the application.

If i click on the route link in the  application the route is working, but if i enter the url directly (for example: mypage/about) i am getting a 404 error.

I checked in with vercel support and they said that likely a redirect is missing in the configuration,  which is for example setup by default by create-react-app. In CRA it looks like this

```<code>{
  "redirects: [
    { "source": "/(.*)", "destination": "/index.html" }
  ]
}
</code>```

After going through the vite.js documentation i can't find any hints on how to setup a redirect in vite.

答:
If you are using vite
create a folder called public and add a file called _redirects to it, for the rest of the other bundlers just add the _redirects file to the public folder

put this inside the _redirects file

```<code>/* /index.html 200
</code>```

Link Here - thats the link if you want to see the project structure

Body:
I made a react build with vite.js.
When building for production and testing on local host all is working fine. But when i deploy to Netlify or vercel routes that i created with react-router are not accessible via entering their  url directly, but only from the main page ('/') via using the links inside of the application.

If i click on the route link in the  application the route is working, but if i enter the url directly (for example: mypage/about) i am getting a 404 error.

I checked in with vercel support and they said that likely a redirect is missing in the configuration,  which is for example setup by default by create-react-app. In CRA it looks like this

{
  "redirects: [
    { "source": "/(.*)", "destination": "/index.html" }
  ]
}

After going through the vite.js documentation i can't find any hints on how to setup a redirect in vite.

Body:
If you are using vite
create a folder called public and add a file called _redirects to it, for the rest of the other bundlers just add the _redirects file to the public folder

put this inside the _redirects file

/* /index.html 200

Link Here - thats the link if you want to see the project structure


问:
React: how to use onclick function in a loop in class component?
what i want is to run an onClick event handler in a loop.
what i have done is :

my component looks something like this.

```<code>import React, { Component } from "react";
import Link from 'next/link';

class VehicleSpecifications extends Component {

constructor(props) {
super(props);
this.setActiveClass = this.setActiveClass.bind(this)

this.state = {
    tabStatus: "",
};
}

setActiveClass = (e) => {
  console.log(e)
}

render() {
const vehicleSpecs = this.props.vehicleSpecs;
console.log(this.props.vehicleSpecs)
return (
  <React.Fragment>
    <div className="vertical-tabs" >
      <ul className="nav nav-tabs" role="tablist">
        {
          Object.entries(vehicleSpecs).map(function (items, car_index) {
            let typeAndName = items[0].split(':-:');
            return (
              <li className="nav-item"   onClick={ ()=> setActiveClass("#pag") }>
                <Link
                  className="nav-link active"
                  data-toggle="tab"
                  href={"#pag" + car_index}
                  role="tab"
                  aria-controls="performance">
                  {typeAndName[0].replace('_', ' ').toUpperCase()}

                </Link>
              </li>
            )
          })
        }
      </ul>

    </div>
  </React.Fragment>
);
}
}
</code>```

export default VehicleSpecifications;

i have tried things but this onclick function sometime gives _this is undefined or says function is undefined.

答:
Try this:

onClick={ ()=> { this.setActiveClass("#pag") }}

Body:
what i want is to run an onClick event handler in a loop.
what i have done is :

my component looks something like this.

import React, { Component } from "react";
import Link from 'next/link';

class VehicleSpecifications extends Component {

constructor(props) {
super(props);
this.setActiveClass = this.setActiveClass.bind(this)

this.state = {
    tabStatus: "",
};
}

setActiveClass = (e) => {
  console.log(e)
}

render() {
const vehicleSpecs = this.props.vehicleSpecs;
console.log(this.props.vehicleSpecs)
return (
  <React.Fragment>

        {
          Object.entries(vehicleSpecs).map(function (items, car_index) {
            let typeAndName = items[0].split(':-:');
            return (

 setActiveClass("#pag") }>
                <Link
                  className="nav-link active"
                  data-toggle="tab"
                  href={"#pag" + car_index}
                  role="tab"
                  aria-controls="performance">
                  {typeAndName[0].replace('_', ' ').toUpperCase()}

                </Link>

            )
          })
        }

  </React.Fragment>
);
}
}

export default VehicleSpecifications;

i have tried things but this onclick function sometime gives _this is undefined or says function is undefined.


问:
How to create many divs without actually creating them individually
I'm working on a project with html, css and js and I want to create many divs (let's say, 200) so, how can i create them without actually writing code for 200 different divs... I know I can do it with js but could I do it only with html and css..?</p>

答:
how it's going? Html or css is not a programming language. So you can't do some kind of automation or repeating code or something like that. The only way to do that sort of things is using Javascript. Here is how:

```<code><div class="container">
  <!-- let's say we trying to add divs here. -->
</div>
</code>```

And here's script:

```<code>function addMultiple (where, what, count, callBack) {
  for (let i = 0; i < count; i++) {
    // creating elements with document.createElement() method
    let item = document.createElement(what)
    // and then adding them into "where" element.
    where.appendChild(item)

   /*
    and finally we'll have a function called Callback.
    This is just gonna take our item as an argument and
    do some stuff on it according to what we want.
    (I'll show a simple usage down below)
    */
   callBack(item)
  }
}

// let's say we want to add 200 divs into "container" element
// and then we want to add class name to those divs.

const container = document.querySelector('.container')
addMultiple(container, 'div', 200, item => {
  // this code will be repeated for all divs.
  item.classList.add('what_ever_you_want')
})
</code>```

Body:
how it's going? Html or css is not a programming language. So you can't do some kind of automation or repeating code or something like that. The only way to do that sort of things is using Javascript. Here is how:

<div class="container">
  <!-- let's say we trying to add divs here. -->
</div>

And here's script:

function addMultiple (where, what, count, callBack) {
  for (let i = 0; i < count; i++) {
    // creating elements with document.createElement() method
    let item = document.createElement(what)
    // and then adding them into "where" element.
    where.appendChild(item)

   /*
    and finally we'll have a function called Callback.
    This is just gonna take our item as an argument and
    do some stuff on it according to what we want.
    (I'll show a simple usage down below)
    */
   callBack(item)
  }
}

// let's say we want to add 200 divs into "container" element
// and then we want to add class name to those divs.

const container = document.querySelector('.container')
addMultiple(container, 'div', 200, item => {
  // this code will be repeated for all divs.
  item.classList.add('what_ever_you_want')
})


问:
Ignore field when inserting with Fluent Nhibernate
In my MySql database i have a field which is a timestamp. MySQL is inserting the time when the row is created and updates the time when a row is updated.

How do I tell NHibernate don't to insert anything in that field when inserting and updating. I still want to be able to read the property.

With my current mapping:

```<code>Map(x => x.CreateDate).Column("CreateDate");
</code>```

NHibernate tries to insert 0001-01-01 00:00:00, because the field is not nullable (And it should not be nullable)

I'm using Fluent Nhibernate.

答:
I guess you should specify that property is generated by database:</p>

```<code>Map(x => x.CreateDate).Column("CreateDate").Generated.Always();
</code>```

Body:
In my MySql database i have a field which is a timestamp. MySQL is inserting the time when the row is created and updates the time when a row is updated.

How do I tell NHibernate don't to insert anything in that field when inserting and updating. I still want to be able to read the property.

With my current mapping:

Map(x => x.CreateDate).Column("CreateDate");

NHibernate tries to insert 0001-01-01 00:00:00, because the field is not nullable (And it should not be nullable)

I'm using Fluent Nhibernate.

Body:
I guess you should specify that property is generated by database:

Map(x => x.CreateDate).Column("CreateDate").Generated.Always();


问:
loop (for) in R to read separately many files (from list of files)
I have a list of Excel files that I want to read.
As they have sometimes different columns I want to read them separately, giving them their location as name.

I'm new in loops, and I cannot get to name them differently. This is what I tried, but reads only one (of 40) file.

```<code>myfiles = list.files(path="Invoices/GLS/",
                     pattern = "0_*", full.names = TRUE, recursive = T)
myfiles

for(val in myfiles) {
   val <- read_excel(val)
}
</code>```

答:
As mentioned by Ronak, you're probably better off with the sapply approach because of verbosity and ease of reading, as well as preventing your environment to be cluttered with objects (this would only make processing more labour intensive down the line, as well). For the sake of illustration, I'll show an approach using a for loop first, followed by sapply() and lapply().

The reason you only have one dataframe in your environment is because you're assigning data to the same object in each iteration. As a result, your object is overwritten whenever that line is called in your loop. At the end of the loop, val will contain the last file that was loaded via read_excel(val). To solve this, you could use the assign() approach.

for(val in seq_along(myfiles)) {
  # create name of object to assign file to
  obj_name <- paste0("df_", val)

  # Import file
  df_file <- read_excel(myfiles[val])

  # Assign it to a separate object in global environment
  assign(obj_name, df_file)

  # Ensure no df_file remains in environment when loop ends
  rm(df_file))
}
```
<p>Naturally, you could give your R objects other names than <code>df_1</code>, <code>df_2</code> and so forth. You can also write the above in less lines of code, but that would defeat the purpose of illustrating the different steps.</p>
<hr />
<p>As for <code>sapply(simplify = FALSE)</code> and <code>lapply()</code>, your data would not be loaded into separate objects in your environment. Instead your datasets would be loaded into a list. As an extra step, you can easily make 1 single dataframe out of that list if you so desire. Regardless, I'd opt for having 1 list of 40 dataframes over 40 objects sitting in my environment.</p>
<p>A convenient feature of <code>sapply()</code> is the <code>USE.NAMES</code> argument, which defaults to <code>TRUE</code>. This will set the names of the elements of the resulting list to your <code>X</code> argument (your input vector with filenames). The <code>simlify = FALSE</code> prevents the function from trying coercing your list to another structure (in this case, it would become a matrix).</p>
<pre class="lang-r prettyprint-override"><code># load excel files into a list of dataframes, retaining filenames
df_list <- sapply(myfiles, read_excel, simplify = FALSE)
</code>```

However, in my opinion, the names of your list elements can become quite messy if you're dealing with FULL filenames (as a result of full.names = TRUE in list.files(). In the two-step approach below, you first load your dataframes into a list, and then set the names of said list using some regular expression. This expression would only extract the last part of the filepath that contains the actual name of your file (e.g. invoice542.xlsx)

# load excel files into a list of dataframes
df_list <- lapply(myfiles, read_excel)

# name list elements using regex
names(val2) <- sub(r"{[\w\/]+(?:\/)}", "", myfiles, perl = TRUE)
```

Bear in mind that regex isn't my strong suit, so the above expression could probably be written more clearly/concise.

And that's it for my first ever SO contribution!

Body:
I have a list of Excel files that I want to read.
As they have sometimes different columns I want to read them separately, giving them their location as name.

I'm new in loops, and I cannot get to name them differently. This is what I tried, but reads only one (of 40) file.

myfiles = list.files(path="Invoices/GLS/",
                     pattern = "0_*", full.names = TRUE, recursive = T)
myfiles

for(val in myfiles) {
   val <- read_excel(val)
}

Body:
As mentioned by Ronak, you're probably better off with the sapply approach because of verbosity and ease of reading, as well as preventing your environment to be cluttered with objects (this would only make processing more labour intensive down the line, as well). For the sake of illustration, I'll show an approach using a for loop first, followed by sapply() and lapply().

The reason you only have one dataframe in your environment is because you're assigning data to the same object in each iteration. As a result, your object is overwritten whenever that line is called in your loop. At the end of the loop, val will contain the last file that was loaded via read_excel(val). To solve this, you could use the assign() approach.

for(val in seq_along(myfiles)) {
  # create name of object to assign file to
  obj_name <- paste0("df_", val)

  # Import file
  df_file <- read_excel(myfiles[val])

  # Assign it to a separate object in global environment
  assign(obj_name, df_file)

  # Ensure no df_file remains in environment when loop ends
  rm(df_file))
}

Naturally, you could give your R objects other names than df_1, df_2 and so forth. You can also write the above in less lines of code, but that would defeat the purpose of illustrating the different steps.

As for sapply(simplify = FALSE) and lapply(), your data would not be loaded into separate objects in your environment. Instead your datasets would be loaded into a list. As an extra step, you can easily make 1 single dataframe out of that list if you so desire. Regardless, I'd opt for having 1 list of 40 dataframes over 40 objects sitting in my environment.

A convenient feature of sapply() is the USE.NAMES argument, which defaults to TRUE. This will set the names of the elements of the resulting list to your X argument (your input vector with filenames). The simlify = FALSE prevents the function from trying coercing your list to another structure (in this case, it would become a matrix).

# load excel files into a list of dataframes, retaining filenames
df_list <- sapply(myfiles, read_excel, simplify = FALSE)

However, in my opinion, the names of your list elements can become quite messy if you're dealing with FULL filenames (as a result of full.names = TRUE in list.files(). In the two-step approach below, you first load your dataframes into a list, and then set the names of said list using some regular expression. This expression would only extract the last part of the filepath that contains the actual name of your file (e.g. invoice542.xlsx)

# load excel files into a list of dataframes
df_list <- lapply(myfiles, read_excel)

# name list elements using regex
names(val2) <- sub(r"{[\w\/]+(?:\/)}", "", myfiles, perl = TRUE)

Bear in mind that regex isn't my strong suit, so the above expression could probably be written more clearly/concise.

And that's it for my first ever SO contribution!


问:
How to copy a variable into a lambda from a list?
I am trying to generate a list of lambdas that I will later apply to an object, but when I try to do it via a comprehension or a loop over a list, the reference to the variable is kept, rather than the value itself. Let me illustrate.

Assume your object class is something like this:

class Object:
 def function(self, x):
  print(x)
```
<p>So when you create the object and invoke it you get something like this:</p>
<pre class="lang-py prettyprint-override"><code>o = Object()
o.function(0)
>>> 0
</code>```

Now, if I manually construct my list of lambdas it would look like this:

lambdas = [
 lambda x: x.function(0),
 lambda x: x.function(1),
 lambda x: x.function(2)
]
```
<p>Which I can then apply to my previously created object:</p>
<pre class="lang-py prettyprint-override"><code>for l in lambdas:
 l(o)
>>> 0
>>> 1
>>> 2
</code>```

However, when I generate the lambda list from another list, I only get the reference to the latest element of the list:

lambdas = [lambda x: x.function(i) for i in range(2)]
for l in lambdas:
 l(o)
>>> 2
>>> 2
>>> 2
```

On closer inspection I can see that each lambda has a different memory address, so they are NOT references to the same function.

So I can only assume that the lambda is keeping a reference to i which has a final value of 2 and therefore when invoked, it takes the value.

So my question is if its possible to set the value of the variable inside the lambda before invocation?

Note: The usa case for a list of lambdas is to pass to the agg function of a Pandas groupby on a DataFrame. I am not looking for a solution to the pandas problem, but curious about the general solution.

答:
Generator Option

Just change lambdas to a generator instead of a list, this will cause it redefine i on every call:

```<code>lambdas = (lambda x: x.function(i) for i in range(2))
for l in lambdas:
    print(l(o))
</code>```

Full code:

```<code>class Object:
    def function(self, x):
        print(x)
o = Object()
o.function(0) #manual call
lambdas = (lambda x: x.function(i) for i in range(2))
for l in lambdas:
    l(o)
</code>```

Output:

```<code>0 #output from manual call
0 #output from generator
1 #output from generator
</code>```

List Option

If you need a list for things like lambdas[0](o) you can send i to lambda each iteration by using i=i like so:

```<code>lambdas = [lambda x, i=i: x.function(i) for i in range(2)]
</code>```

Example of second option:

```<code>class Object:
    def function(self, x):
        print(x)
o = Object()
lambdas = [lambda x, i=i: x.function(i) for i in range(2)] #notice the cahnge
for i in range(len(lambdas)):
    lambdas[i](o) #notice the change
</code>```

Output:

```<code>0
1
</code>```

Body:
I am trying to generate a list of lambdas that I will later apply to an object, but when I try to do it via a comprehension or a loop over a list, the reference to the variable is kept, rather than the value itself. Let me illustrate.

Assume your object class is something like this:

class Object:
 def function(self, x):
  print(x)

So when you create the object and invoke it you get something like this:

o = Object()
o.function(0)
>>> 0

Now, if I manually construct my list of lambdas it would look like this:

lambdas = [
 lambda x: x.function(0),
 lambda x: x.function(1),
 lambda x: x.function(2)
]

Which I can then apply to my previously created object:

for l in lambdas:
 l(o)
>>> 0
>>> 1
>>> 2

However, when I generate the lambda list from another list, I only get the reference to the latest element of the list:

lambdas = [lambda x: x.function(i) for i in range(2)]
for l in lambdas:
 l(o)
>>> 2
>>> 2
>>> 2

On closer inspection I can see that each lambda has a different memory address, so they are NOT references to the same function.

So I can only assume that the lambda is keeping a reference to i which has a final value of 2 and therefore when invoked, it takes the value.

So my question is if its possible to set the value of the variable inside the lambda before invocation?

Note: The usa case for a list of lambdas is to pass to the agg function of a Pandas groupby on a DataFrame. I am not looking for a solution to the pandas problem, but curious about the general solution.

Body:
Generator Option

Just change lambdas to a generator instead of a list, this will cause it redefine i on every call:

lambdas = (lambda x: x.function(i) for i in range(2))
for l in lambdas:
    print(l(o))

Full code:

class Object:
    def function(self, x):
        print(x)
o = Object()
o.function(0) #manual call
lambdas = (lambda x: x.function(i) for i in range(2))
for l in lambdas:
    l(o)

Output:

0 #output from manual call
0 #output from generator
1 #output from generator

List Option

If you need a list for things like lambdas[0](o) you can send i to lambda each iteration by using i=i like so:

lambdas = [lambda x, i=i: x.function(i) for i in range(2)]

Example of second option:

class Object:
    def function(self, x):
        print(x)
o = Object()
lambdas = [lambda x, i=i: x.function(i) for i in range(2)] #notice the cahnge
for i in range(len(lambdas)):
    lambdas[i](o) #notice the change

Output:

0
1


问:
Using the new Application Registration results in an error message on login
I have a legacy B2C application that runs just fine. I decided to upgrade to the new 'experience' since the message said they're discontinuing the old legacy blade as of Nov-21. So I followed the instructions on this page:
AAD B2C specifics
When I start up the application, I get this message:

Switching back to the legacy application results in a working login screen.

答:
•   Since your Azure AD B2C application is a ‘PublicClientApplication’, it has the property of ‘UseCorporateNetwork’ which is a Boolean that enables the application to benefit from Integrated Windows Authentication and SSO as these are cross platform capabilities. Thus, set this property to ‘true’ in ‘package.appxmanifest’ by enabling the capabilities, viz., Enterprise Authentication, Private Networks(Client & Server) and Shared User certificate.

Also, as IWA is not enabled by default as applications requesting the above type of authentication require a higher level of verification to be accepted for social identities using MSAL .NET.

Kindly check the ‘RedirectURI’ of your new Azure AD B2C experience as it may get overridden by that in ‘UserDetailsClient\App.cs’. Hence, replace the ‘RedirectURI’ in your Azure AD B2C application by the one that is overridden in ‘UserDetailsClient\App.cs’ along with the msal://auth. Maybe, this should resolve your issue. For more details, kindly refer to the below Github link below: -

https://github.com/Azure-Samples/active-directory-b2c-xamarin-native/issues/28


问:
OAuth 2.0 and Google Signin in .NET 5 (core)?
I can't find anything online that mimics Google sign-in for MVC 5 and below for implementation in MVC 6. Is it supported yet? I was using OWIN, but it appears that it is now obsolete in Core. Could anyone be so kind as to throw some links or info my way? I'm at a complete loss.</p>

答:
In .NET 5 is as follows:

First add nuget package:

```<code>Install-Package Microsoft.AspNetCore.Authentication.Google -Version 5.0.14
</code>```

Then add this code to startup.cs:

```<code>services.AddAuthentication().AddGoogle(options =>
             {
                 options.ClientId = "xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
                 options.ClientSecret = "yyyyyy-yyyyyyyyyyyyyyyyyyyyyyyyyyyy";
             });
</code>```

microsoft reference

Body:
In .NET 5 is as follows:

First add nuget package:

Install-Package Microsoft.AspNetCore.Authentication.Google -Version 5.0.14

Then add this code to startup.cs:

services.AddAuthentication().AddGoogle(options =>
             {
                 options.ClientId = "xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
                 options.ClientSecret = "yyyyyy-yyyyyyyyyyyyyyyyyyyyyyyyyyyy";
             });

microsoft reference


问:
Material UI v5 styles applied to class does'nt apply?
I am trying to style the MUI slider,so I decided to style it using the className prop. But the style applied to the main class does'nt get applied,while rest other styles like 'hover' state get applied. If I remove all the classes and just style it using SX prop,everything works fine. But I want to keep the styles seperate into an external css file.

Below is my code :

App.css

```<code>.container{
  margin-left: 30%;
  margin-top: 20%;

}

/* This does'nt get applied */
.slider {
  color: #ff0000;
  width: 300px;
}

.slider:hover {
  color: #2e8b57;
}

.slider > .MuiSlider-thumb {
  border-radius: 1px;
}
</code>```

App.js

```<code>import "./App.css"
import * as React from 'react';
import Slider from '@mui/material/Slider';

export default function App() {
  return (
    <div className="container">
      <Slider className="slider"  defaultValue={30} />
    </div>
  );
}
</code>```

答:
The problem is with Material UI style injection order. The custom styles do apply, but Mui styles are injected before the custom style so they doesn't have effect in this case.

This guide explain how to change the injection order:

https://mui.com/guides/interoperability/#css-injection-order

Body:
I am trying to style the MUI slider,so I decided to style it using the className prop. But the style applied to the main class does'nt get applied,while rest other styles like 'hover' state get applied. If I remove all the classes and just style it using SX prop,everything works fine. But I want to keep the styles seperate into an external css file.

Below is my code :

App.css

.container{
  margin-left: 30%;
  margin-top: 20%;

}

/* This does'nt get applied */
.slider {
  color: #ff0000;
  width: 300px;
}

.slider:hover {
  color: #2e8b57;
}

.slider > .MuiSlider-thumb {
  border-radius: 1px;
}

App.js

import "./App.css"
import * as React from 'react';
import Slider from '@mui/material/Slider';

export default function App() {
  return (

      <Slider className="slider"  defaultValue={30} />

  );
}