问:
How to Request and removes updates of locationManager from a thread to a service
I have a service that implements the interface LocationListener with the methods of this interface.

When I run the service, I instantiate a LocationManager.

Then I start a thread that will run non-stop with an infinite loop.

Since this thread, I wish I could make a locationManager.removeupdates on my locationManager instantiated at the beginning of service.

But there is a problem, apparently I would need a Looper, I tried many things, but I can not use it.

Basically, here is my code, obviously, I don't know how use Looper, because my code stop after Log.d("GPS", "GPS Activé");

I've been searched stuff on Looper, but find a comprehensible how-to in my language (I'm French)
are really difficult.

The code may seem weird, because, as I removed a lot of things...

```<code>public class ServicePrincipal extends Service implements LocationListener {

    boolean localisationOn = false;

    LocationManager locationManager;

    public class MyBinder extends Binder{
        ServicePrincipal getService(){
            return ServicePrincipal.this;
        }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return new MyBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        locationManager.removeUpdates(this);
        super.onDestroy();
    }

    @Override
    public void onStart(Intent intent, int startId) {

        MyThread mythread = new MyThread();
                    MyThread.start();
        super.onStart(intent, startId);
    }

    public class MyThread extends Thread {

        int nbInfos;
        @Override
        public void run() {

            for (;;) {

                        if (localisationOn)
                        {
                            localisationOn = false;
                            Looper.prepare();
                            stopGPS();
                            Looper.loop();
                        }

                            if (!localisationOn)
                            {
                                Looper.prepare();
                                startGPS();
                                Looper.loop();
                                /* On active le flag de localisation */
                                localisationOn = true;
                            }
                }
                try {
                    Log.d("Boucle for", "~~~~ Fin de boucle ~~~~");
                    this.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void onLocationChanged(Location location) {
        if ((location != null) && (localisationOn))
        {
            Log.d("Localisation", "Envoi des informations de localisation avec :");
            Log.d("Latitude", String.valueOf(location.getLatitude()));
            Log.d("Longitude", String.valueOf(location.getLongitude()));
        }

    }

    public void onProviderDisabled(String provider) {

    }

    public void onProviderEnabled(String provider) {

    }

    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    public void startGPS()
    {
        /* Intent du service de localisation */
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        /* On active l'actualisation par le GPS et par le réseau téléphonique */
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1,1,this);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1,1,this);

        Log.d("GPS", "GPS Activé");
    }

    public void stopGPS()
    {

        locationManager.removeUpdates(this);
        Log.d("GPS", "GPS Désactivé");
    }

}
</code>```

答:
This problem happens when requestLocationUpdates() is called from a thread.Your program will be crashed.I solved that problem when I was working.
I modified your code.Hope now your looper problem will be solved.Moreover,it will remove your infinite loop problem.Hope this help.

```<code>public class ServicePrincipal extends Service implements LocationListener {

    boolean localisationOn = false;

    LocationManager locationManager;
    private final Handler handler = new Handler();
    public class MyBinder extends Binder{
        ServicePrincipal getService(){
            return ServicePrincipal.this;
        }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return new MyBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        locationManager.removeUpdates(this);
        super.onDestroy();
    }

    @Override
    public void onStart(Intent intent, int startId) {

        /*MyThread mythread = new MyThread();
                    MyThread.start();*/
    handler.post(getData);
        super.onStart(intent, startId);
    }

    private final Runnable getData = new Runnable() {
        public void run() {
            getDataFrame();
        }
    };

    private void getDataFrame() {
        if (localisationOn){
                            localisationOn = false;
                            stopGPS();
                }
        if (!localisationOn){
                        startGPS();
                        /* On active le flag de localisation */
                        localisationOn = true;
                }
        handler.postDelayed(getData,10000);

    }
    public void onLocationChanged(Location location) {
        if ((location != null) && (localisationOn))
        {
            Log.d("Localisation", "Envoi des informations de localisation avec :");
            Log.d("Latitude", String.valueOf(location.getLatitude()));
            Log.d("Longitude", String.valueOf(location.getLongitude()));
        }

    }

    public void onProviderDisabled(String provider) {

    }

    public void onProviderEnabled(String provider) {

    }

    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    public void startGPS()
    {
        /* Intent du service de localisation */
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        /* On active l'actualisation par le GPS et par le réseau téléphonique */
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1,1,this);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1,1,this);

        Log.d("GPS", "GPS Activé");
    }

    public void stopGPS()
    {

        locationManager.removeUpdates(this);
        Log.d("GPS", "GPS Désactivé");
    }

}
</code>```

Body:
I have a service that implements the interface LocationListener with the methods of this interface.

When I run the service, I instantiate a LocationManager.

Then I start a thread that will run non-stop with an infinite loop.

Since this thread, I wish I could make a locationManager.removeupdates on my locationManager instantiated at the beginning of service.

But there is a problem, apparently I would need a Looper, I tried many things, but I can not use it.

Basically, here is my code, obviously, I don't know how use Looper, because my code stop after Log.d("GPS", "GPS Activé");

I've been searched stuff on Looper, but find a comprehensible how-to in my language (I'm French)
are really difficult.

The code may seem weird, because, as I removed a lot of things...

public class ServicePrincipal extends Service implements LocationListener {

    boolean localisationOn = false;

    LocationManager locationManager;

    public class MyBinder extends Binder{
        ServicePrincipal getService(){
            return ServicePrincipal.this;
        }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return new MyBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        locationManager.removeUpdates(this);
        super.onDestroy();
    }

    @Override
    public void onStart(Intent intent, int startId) {

        MyThread mythread = new MyThread();
                    MyThread.start();
        super.onStart(intent, startId);
    }

    public class MyThread extends Thread {

        int nbInfos;
        @Override
        public void run() {

            for (;;) {

                        if (localisationOn)
                        {
                            localisationOn = false;
                            Looper.prepare();
                            stopGPS();
                            Looper.loop();
                        }

                            if (!localisationOn)
                            {
                                Looper.prepare();
                                startGPS();
                                Looper.loop();
                                /* On active le flag de localisation */
                                localisationOn = true;
                            }
                }
                try {
                    Log.d("Boucle for", "~~~~ Fin de boucle ~~~~");
                    this.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void onLocationChanged(Location location) {
        if ((location != null) && (localisationOn))
        {
            Log.d("Localisation", "Envoi des informations de localisation avec :");
            Log.d("Latitude", String.valueOf(location.getLatitude()));
            Log.d("Longitude", String.valueOf(location.getLongitude()));
        }

    }

    public void onProviderDisabled(String provider) {

    }

    public void onProviderEnabled(String provider) {

    }

    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    public void startGPS()
    {
        /* Intent du service de localisation */
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        /* On active l'actualisation par le GPS et par le réseau téléphonique */
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1,1,this);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1,1,this);

        Log.d("GPS", "GPS Activé");
    }

    public void stopGPS()
    {

        locationManager.removeUpdates(this);
        Log.d("GPS", "GPS Désactivé");
    }

}

Body:
This problem happens when requestLocationUpdates() is called from a thread.Your program will be crashed.I solved that problem when I was working.
I modified your code.Hope now your looper problem will be solved.Moreover,it will remove your infinite loop problem.Hope this help.

public class ServicePrincipal extends Service implements LocationListener {

    boolean localisationOn = false;

    LocationManager locationManager;
    private final Handler handler = new Handler();
    public class MyBinder extends Binder{
        ServicePrincipal getService(){
            return ServicePrincipal.this;
        }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return new MyBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        locationManager.removeUpdates(this);
        super.onDestroy();
    }

    @Override
    public void onStart(Intent intent, int startId) {

        /*MyThread mythread = new MyThread();
                    MyThread.start();*/
    handler.post(getData);
        super.onStart(intent, startId);
    }

    private final Runnable getData = new Runnable() {
        public void run() {
            getDataFrame();
        }
    };

    private void getDataFrame() {
        if (localisationOn){
                            localisationOn = false;
                            stopGPS();
                }
        if (!localisationOn){
                        startGPS();
                        /* On active le flag de localisation */
                        localisationOn = true;
                }
        handler.postDelayed(getData,10000);

    }
    public void onLocationChanged(Location location) {
        if ((location != null) && (localisationOn))
        {
            Log.d("Localisation", "Envoi des informations de localisation avec :");
            Log.d("Latitude", String.valueOf(location.getLatitude()));
            Log.d("Longitude", String.valueOf(location.getLongitude()));
        }

    }

    public void onProviderDisabled(String provider) {

    }

    public void onProviderEnabled(String provider) {

    }

    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    public void startGPS()
    {
        /* Intent du service de localisation */
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        /* On active l'actualisation par le GPS et par le réseau téléphonique */
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1,1,this);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1,1,this);

        Log.d("GPS", "GPS Activé");
    }

    public void stopGPS()
    {

        locationManager.removeUpdates(this);
        Log.d("GPS", "GPS Désactivé");
    }

}


来源: stackexchange

问:
Meta data .gz file in r won't load properly
The file here: https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE104323

called: GSE104323_metadata_barcodes_24185cells.txt.gz

Will not load propoerly in R, it is missing the age column which is arguably the most important metadata and half the coilums are NA's.
The following code loads the data.
hochgerner24k_2018_meta <- read.table(paste(testsetpath,"/Hochgerner2018/GSE104323_metadata_barcodes_24185cells.txt.gz", sep=""), header =TRUE, fill =TRUE)

Without fill = TRUE the following error is produced: Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  :
line 1 did not have 30 elements

How can I load this metadata into a dataframe without all this missing information?

答:
That file doesn't have any metadata that I can see. It's a tab-separated file. How do I know that? Well I suppose I could have looked at its documentation which is probably around some where, but what I did instead was to look at it in a text editor --->

You can observe the typical arrangement of text for a tab-separated file: all the columns are left aligned with some of them shifting over when the text bleeds over into the next column.

```<code>hochgerner24k_2018_meta <- read.table("~/Downloads/GSE104323_metadata_barcodes_24185cells.txt.gz", header =TRUE, sep="\t")
> str(hochgerner24k_2018_meta)
'data.frame':   24216 obs. of  11 variables:
 $ Sample.name..24185.single.cells.      : chr  "10X79_1_AAACTAGCTAGCCC-" "10X79_1_AAACTAGGATGTAT-" "10X79_1_AAACTCACGGCGTT-" "10X79_1_AAACTGTCGGCTCA-" ...
 $ source.name                           : chr  "dentate gyrus" "dentate gyrus" "dentate gyrus" "dentate gyrus" ...
 $ organism                              : chr  "Mus musculus" "Mus musculus" "Mus musculus" "Mus musculus" ...
 $ characteristics..strain               : chr  "hGFAP-GFP" "hGFAP-GFP" "hGFAP-GFP" "hGFAP-GFP" ...
 $ characteristics..age                  : chr  "P120" "P120" "P120" "P120" ...
 $ characteristics..sex.of.pooled.animals: chr  "2males+1female" "2males+1female" "2males+1female" "2males+1female" ...
 $ characteristics..cell.cluster         : chr  "Neuroblast" "OPC" "GC-adult" "MOL" ...
 $ molecule                              : chr  "total RNA" "total RNA" "total RNA" "total RNA" ...
 $ SRR.run.accession                     : chr  "SRR6089817" "SRR6089947" "SRR6089529" "SRR6089595" ...
 $ raw.file..original.file.name.         : chr  "10X79_1_AAACTAGCTAGCCC.fq.gz" "10X79_1_AAACTAGGATGTAT.fq.gz" "10X79_1_AAACTCACGGCGTT.fq.gz" "10X79_1_AAACTGTCGGCTCA.fq.gz" ...
 $ UMI_CellularBarcode                   : chr  "CGGCGATCCC_AAACTAGCTAGCCC" "AGTGGTAATG_AAACTAGGATGTAT" "GGGTGCGCTC_AAACTCACGGCGTT" "CCTTTCAACG_AAACTGTCGGCTCA" ...
</code>```

Note: .gz files will not always be this format (or any format). They are just compressed and the delimiter has no particular special importance to the compression algorithm. The next .gz file you see could have any structure or no structure.

ContentLicense: CC BY-SA 4.0

Body:
That file doesn't have any metadata that I can see. It's a tab-separated file. How do I know that? Well I suppose I could have looked at its documentation which is probably around some where, but what I did instead was to look at it in a text editor --->

You can observe the typical arrangement of text for a tab-separated file: all the columns are left aligned with some of them shifting over when the text bleeds over into the next column.

hochgerner24k_2018_meta <- read.table("~/Downloads/GSE104323_metadata_barcodes_24185cells.txt.gz", header =TRUE, sep="\t")
> str(hochgerner24k_2018_meta)
'data.frame':   24216 obs. of  11 variables:
 $ Sample.name..24185.single.cells.      : chr  "10X79_1_AAACTAGCTAGCCC-" "10X79_1_AAACTAGGATGTAT-" "10X79_1_AAACTCACGGCGTT-" "10X79_1_AAACTGTCGGCTCA-" ...
 $ source.name                           : chr  "dentate gyrus" "dentate gyrus" "dentate gyrus" "dentate gyrus" ...
 $ organism                              : chr  "Mus musculus" "Mus musculus" "Mus musculus" "Mus musculus" ...
 $ characteristics..strain               : chr  "hGFAP-GFP" "hGFAP-GFP" "hGFAP-GFP" "hGFAP-GFP" ...
 $ characteristics..age                  : chr  "P120" "P120" "P120" "P120" ...
 $ characteristics..sex.of.pooled.animals: chr  "2males+1female" "2males+1female" "2males+1female" "2males+1female" ...
 $ characteristics..cell.cluster         : chr  "Neuroblast" "OPC" "GC-adult" "MOL" ...
 $ molecule                              : chr  "total RNA" "total RNA" "total RNA" "total RNA" ...
 $ SRR.run.accession                     : chr  "SRR6089817" "SRR6089947" "SRR6089529" "SRR6089595" ...
 $ raw.file..original.file.name.         : chr  "10X79_1_AAACTAGCTAGCCC.fq.gz" "10X79_1_AAACTAGGATGTAT.fq.gz" "10X79_1_AAACTCACGGCGTT.fq.gz" "10X79_1_AAACTGTCGGCTCA.fq.gz" ...
 $ UMI_CellularBarcode                   : chr  "CGGCGATCCC_AAACTAGCTAGCCC" "AGTGGTAATG_AAACTAGGATGTAT" "GGGTGCGCTC_AAACTCACGGCGTT" "CCTTTCAACG_AAACTGTCGGCTCA" ...

Note: .gz files will not always be this format (or any format). They are just compressed and the delimiter has no particular special importance to the compression algorithm. The next .gz file you see could have any structure or no structure.


问:
TypeScript hasOwnProperty equivalent
In JavaScript, if I want to loop through a dictionary and set properties of another dictionary, I'd use something like this:

```<code>for (let key in dict) {
  if (obj.hasOwnProperty(key)) {
    obj[key] = dict[key];
  }
}
</code>```

If obj is a TypeScript object (instance of a class), is there a way to perform the same operation?

答:
I found fp-ts has function worked best for my use case:

```<code>const role = 'mother' as string
const rolesConst = {
  mother: 'mother',
  father: 'father'
} as const
if (has(role, rolesConst)) {
  // role's type is 'mother' | 'father'
}
</code>```

https://gcanti.github.io/fp-ts/modules/ReadonlyRecord.ts.html#has

Title: TypeScript hasOwnProperty equivalent

Body:
In JavaScript, if I want to loop through a dictionary and set properties of another dictionary, I'd use something like this:

for (let key in dict) {
  if (obj.hasOwnProperty(key)) {
    obj[key] = dict[key];
  }
}

If obj is a TypeScript object (instance of a class), is there a way to perform the same operation?

Body:
I found fp-ts has function worked best for my use case:

const role = 'mother' as string
const rolesConst = {
  mother: 'mother',
  father: 'father'
} as const
if (has(role, rolesConst)) {
  // role's type is 'mother' | 'father'
}

https://gcanti.github.io/fp-ts/modules/ReadonlyRecord.ts.html#has


问:
Calling AWS Location API from Sagemaker: Access Denied Exception Error
I have been trying to run the following code in AWS Sagemaker

```<code>location = boto3.client('location', region_name='us-east-1')
Response = location.search_place_index_for_text(IndexName = 'explore.place', Text = 'Boston, MA')
print(Response)
</code>```

but I get the following error

AccessDeniedException: An error occurred (AccessDeniedException) when
calling the SearchPlaceIndexForText operation: User:
arn:aws:sts::713361781863:assumed-role/AmazonSageMaker-ExecutionRole-20220208T112132/SageMaker
is not authorized to perform: geo:SearchPlaceIndexForText on resource:
arn:aws:geo:us-east-1:713361781863:place-index/explore.place

If I run the same code from my local python I get the correct response. I imagine is a permission issue connecting Sagemaker to the AWS Location Service - how do I grant access to sagemaker/update my IAM?

thanks!

答:
You can add inline policy to AmazonSageMaker-ExecutionRole-20220208T112132 role:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "geo:SearchPlaceIndexForText",
            "Resource": "arn:aws:geo:us-east-1:713361781863:place-index/explore.place"
        }
    ]
}
</code>```

Body:
I have been trying to run the following code in AWS Sagemaker

location = boto3.client('location', region_name='us-east-1')
Response = location.search_place_index_for_text(IndexName = 'explore.place', Text = 'Boston, MA')
print(Response)

but I get the following error

AccessDeniedException: An error occurred (AccessDeniedException) when
calling the SearchPlaceIndexForText operation: User:
arn:aws:sts::713361781863:assumed-role/AmazonSageMaker-ExecutionRole-20220208T112132/SageMaker
is not authorized to perform: geo:SearchPlaceIndexForText on resource:
arn:aws:geo:us-east-1:713361781863:place-index/explore.place

If I run the same code from my local python I get the correct response. I imagine is a permission issue connecting Sagemaker to the AWS Location Service - how do I grant access to sagemaker/update my IAM?

thanks!

Body:
You can add inline policy to AmazonSageMaker-ExecutionRole-20220208T112132 role:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "geo:SearchPlaceIndexForText",
            "Resource": "arn:aws:geo:us-east-1:713361781863:place-index/explore.place"
        }
    ]
}


问:
RestSharp 107.2.1 throws 'Request failed with status code UnsupportedMediaType'
I'm trying to send a post request with RestSharp 107.2.1 and I receive the 'UnupportedMediaType' error.
Sending the same body as raw json and the same parameter with Postman is successful.

I tried to use the 'AddBody' and 'AddJsonBody' with and without serializing first with jsonconvert, all throws the same error. Any idea how to make this work?

```<code>            var udfbody = new
            {
                name = "testname",
                displayName = "testdisplayname",
                required = "False",
                type = "TEXT"
            };

            var addudf = new RestRequest();
            addudf.Resource = "addUserDefinedField";
            addudf.Method = Method.Post;
            addudf.AddHeader("Authorization", bamauthtoken);
            addudf.AddParameter("type", "IP4Network");

            //1
            //addudf.AddBody(udfbody, ContentType.Json);

            //2
            //addudf.AddJsonBody(udfbody);

            var serializedbody = JsonConvert.SerializeObject(udfbody);

            //3
            //addudf.AddJsonBody(serializedbody);

            //4
            //addudf.AddBody(serializedbody, ContentType.Json);

            //5
            addudf.AddParameter("application/json", serializedbody, ParameterType.RequestBody);

            var addudfresp = await restclient.PostAsync(addudf).ConfigureAwait(false);
</code>```

here is an image about the same body in postman

答:
OK, figured out.

```<code>addudf.AddParameter("type", "IP4Network");
</code>```

needs to be

```<code>addudf.AddQueryParameter("type", "IP4Network");
</code>```

Body:
I'm trying to send a post request with RestSharp 107.2.1 and I receive the 'UnupportedMediaType' error.
Sending the same body as raw json and the same parameter with Postman is successful.

I tried to use the 'AddBody' and 'AddJsonBody' with and without serializing first with jsonconvert, all throws the same error. Any idea how to make this work?

            var udfbody = new
            {
                name = "testname",
                displayName = "testdisplayname",
                required = "False",
                type = "TEXT"
            };

            var addudf = new RestRequest();
            addudf.Resource = "addUserDefinedField";
            addudf.Method = Method.Post;
            addudf.AddHeader("Authorization", bamauthtoken);
            addudf.AddParameter("type", "IP4Network");

            //1
            //addudf.AddBody(udfbody, ContentType.Json);

            //2
            //addudf.AddJsonBody(udfbody);

            var serializedbody = JsonConvert.SerializeObject(udfbody);

            //3
            //addudf.AddJsonBody(serializedbody);

            //4
            //addudf.AddBody(serializedbody, ContentType.Json);

            //5
            addudf.AddParameter("application/json", serializedbody, ParameterType.RequestBody);

            var addudfresp = await restclient.PostAsync(addudf).ConfigureAwait(false);

here is an image about the same body in postman

Body:
OK, figured out.

addudf.AddParameter("type", "IP4Network");

needs to be

addudf.AddQueryParameter("type", "IP4Network");


问:
Is there any way to make the Scrollview scroll up an extra 100px React Native
I have a component that contains a scrollview. It also have a bottom sheet component. Is there a way to increase the distance of the scrollview when my bottom sheet is active. When my bottom sheet is active I need my scrollview to scroll 100 extra px when my bottom sheet is active because the bottom sheet covers some of the content</p>
```<code><View>
  <Scrollview>
    ...items to scroll
  </Scrollview>
  <ButtomSheet />
</View>;

</code>```

答:
If you have some state that manages if/when BottomSheet is active, you can add a style to scroll view conditionally. Like:

```<code><View>
  <Scrollview style={bottomSheetActive ? {height: 200px} : {height: 100px}>
    {children}
  </ScrollView>
  {bottomSheetActive && (<BottomSheet />)}
</View>
</code>```

Body:
I have a component that contains a scrollview. It also have a bottom sheet component. Is there a way to increase the distance of the scrollview when my bottom sheet is active. When my bottom sheet is active I need my scrollview to scroll 100 extra px when my bottom sheet is active because the bottom sheet covers some of the content

<View>
  <Scrollview>
    ...items to scroll
  </Scrollview>
  <ButtomSheet />
</View>;

Body:
If you have some state that manages if/when BottomSheet is active, you can add a style to scroll view conditionally. Like:

<View>
  <Scrollview style={bottomSheetActive ? {height: 200px} : {height: 100px}>
    {children}
  </ScrollView>
  {bottomSheetActive && (<BottomSheet />)}
</View>


问:
How do I deploy plain PHP site (no framework used)
Wrote a tiny project containing about 5 files with vanilla PHP and Js. This means I have no composer.json & no .htaccess files, no database. Just a POST request to a script(php).

Tried deploying on Heroku but couldn't. Got the error below

```<code>-----> Building on the Heroku-20 stack
-----> Using buildpack: heroku/php
-----> App not compatible with buildpack: https://buildpack-
registry.s3.amazonaws.com/buildpacks/heroku/php.tgz

!     ERROR: Application not supported by this buildpack!
!
!     The 'heroku/php' buildpack is set on this application, but was
!     unable to detect a PHP codebase.
!
!     A PHP app on Heroku requires a 'composer.json' at the root of
!     the directory structure, or an 'index.php' for legacy behavior.
!
!     If you are trying to deploy a PHP application, ensure that one
!     of these files is present at the top level directory.
!
!     If you are trying to deploy an application written in another
!     language, you need to change the list of buildpacks set on your
!     Heroku app using the 'heroku buildpacks' command.
!
!     For more information, refer to the following documentation:
!     https://devcenter.heroku.com/articles/buildpacks
!     https://devcenter.heroku.com/articles/php-support#activation
      More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure
!     Push failed
</code>```

答:
As the error message says, you must have a composer.json¹ in the root of your project.

If you don't have any dependencies, it can be empty:

```<code>{}
</code>```

Add that file, commit it, and redeploy.

¹Or an index.php for "legacy behaviour", but who wants that?

Body:
Wrote a tiny project containing about 5 files with vanilla PHP and Js. This means I have no composer.json & no .htaccess files, no database. Just a POST request to a script(php).

Tried deploying on Heroku but couldn't. Got the error below

-----> Building on the Heroku-20 stack
-----> Using buildpack: heroku/php
-----> App not compatible with buildpack: https://buildpack-
registry.s3.amazonaws.com/buildpacks/heroku/php.tgz

!     ERROR: Application not supported by this buildpack!
!
!     The 'heroku/php' buildpack is set on this application, but was
!     unable to detect a PHP codebase.
!
!     A PHP app on Heroku requires a 'composer.json' at the root of
!     the directory structure, or an 'index.php' for legacy behavior.
!
!     If you are trying to deploy a PHP application, ensure that one
!     of these files is present at the top level directory.
!
!     If you are trying to deploy an application written in another
!     language, you need to change the list of buildpacks set on your
!     Heroku app using the 'heroku buildpacks' command.
!
!     For more information, refer to the following documentation:
!     https://devcenter.heroku.com/articles/buildpacks
!     https://devcenter.heroku.com/articles/php-support#activation
      More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure
!     Push failed

Body:
As the error message says, you must have a composer.json¹ in the root of your project.

If you don't have any dependencies, it can be empty:

{}

Add that file, commit it, and redeploy.

¹Or an index.php for "legacy behaviour", but who wants that?


问:
Why can't we store Unicode directly?
I read some article about Unicode and UTF-8.

The Unicode standard describes how characters are represented by code points. A code point is an integer value, usually denoted in base 16. In the standard, a code point is written using the notation U+12CA to mean the character with value 0x12ca (4,810 decimal). The Unicode standard contains a lot of tables listing characters and their corresponding code points:

Strictly, these definitions imply that it’s meaningless to say ‘this is character U+12CA‘. U+12CA is a code point, which represents some particular character; in this case, it represents the character ‘ETHIOPIC SYLLABLE WI’. In informal contexts, this distinction between code points and characters will sometimes be forgotten.

To summarize the previous section: a Unicode string is a sequence of code points, which are numbers from 0 through 0x10FFFF (1,114,111 decimal). This sequence needs to be represented as a set of bytes (meaning, values from 0 through 255) in memory. The rules for translating a Unicode string into a sequence of bytes are called an encoding.

I wonder why we have to encode U+12CA to UTF-8 or UTF-16 instead of saving the binary of 12CA in the disk directly. I think the reason is:

Unicode is not Self-synchronizing code, so if

```<code>10 represent A
110 represent B
10110 represent C
</code>```

When I see 10110 in the disk we can't tell it's A and B or just C.

Unicode uses much more space instead of UTF-8 or UTF-16.

Am I right?

答: Consider one situation, even if you can directly save unicode binary into disk and close the file, what happens when you open the file again? It's just a bunch of binary, you don't know how many bytes a char occupied right, which means, if ''(U+129398) and 'A' are the content of your file, then if you take it 1 byte for a char, then '' can't be decoded correctly, which takes 2 bytes, then instead 1 emoji you see, you get two, which is U+63862 and U+65536 unicode char.</p>

ContentLicense: CC BY-SA 3.0

Title: Why can't we store Unicode directly?

Body:
I read some article about Unicode and UTF-8.

The Unicode standard describes how characters are represented by code points. A code point is an integer value, usually denoted in base 16. In the standard, a code point is written using the notation U+12CA to mean the character with value 0x12ca (4,810 decimal). The Unicode standard contains a lot of tables listing characters and their corresponding code points:

Strictly, these definitions imply that it’s meaningless to say ‘this is character U+12CA‘. U+12CA is a code point, which represents some particular character; in this case, it represents the character ‘ETHIOPIC SYLLABLE WI’. In informal contexts, this distinction between code points and characters will sometimes be forgotten.

To summarize the previous section: a Unicode string is a sequence of code points, which are numbers from 0 through 0x10FFFF (1,114,111 decimal). This sequence needs to be represented as a set of bytes (meaning, values from 0 through 255) in memory. The rules for translating a Unicode string into a sequence of bytes are called an encoding.

I wonder why we have to encode U+12CA to UTF-8 or UTF-16 instead of saving the binary of 12CA in the disk directly. I think the reason is:

Unicode is not Self-synchronizing code, so if

10 represent A
110 represent B
10110 represent C

When I see 10110 in the disk we can't tell it's A and B or just C.

Unicode uses much more space instead of UTF-8 or UTF-16.

Am I right?


问:
How Redis Cluster connection using redis plus plus ensures connection consistency in case the corresponding node shuts down
How Redis Cluster connection using redis plus plus ensures connection consistency in case the corresponding node shuts down ?

The documentation in https://github.com/sewenew/redis-plus-plus#redis-cluster states that "You only need to set one master node's host & port in ConnectionOptions, and RedisCluster will get other nodes' info automatically (with the CLUSTER SLOTS command)"

If the IP and port used to create the connection somehow goes down after establishing the connection, and the corresponding slave is automatically upgraded to master by Redis, does redis-plus-plus takes care of this? Or we may expect an error ?

答:
Yes, redis-plus-plus will take care of this.

Once RedisCluster is successfully constructed, it will get all nodes' IP and port with the CLUSTER SLOTS command. Also if the cluster topology changes, e.g. master down, new master elected, redis-plus-plus automatically updates the info.

However, there's a time window between old master is down, and new master is elected. In this case, if your command is sent to the broken master, you'll get exception. Everything will remove to normal, once the new master is elected.


问:
How can I manually return or throw a validation error/exception in Laravel?
Have a method that's importing CSV-data into a Database. I do some basic validation using

```<code>class CsvImportController extends Controller
{
    public function import(Request $request)
    {
        $this->validate($request, [
            'csv_file' => 'required|mimes:csv,txt',
        ]);
</code>```

But after that things can go wrong for more complex reasons, further down the rabbit hole, that throws exceptions of some sort. I can't write proper validation stuff to use with the validate method here, but, I really like how Laravel works when the validation fails and how easy it is to embed the error(s) into the blade view etc, so...

Is there a (preferably clean) way to manually tell Laravel that "I know I didn't use your validate method right now, but I'd really like you to expose this error here as if I did"? Is there something I can return, an exception I can wrap things with, or something?

```<code>try
{
    // Call the rabbit hole of an import method
}
catch(\Exception $e)
{
    // Can I return/throw something that to Laravel looks
    // like a validation error and acts accordingly here?
}
</code>```

答:
In Laravel 8 and above, the following works in both a controller and a model:

```<code>return back()->withErrors(["email" => "Are you sure the email is correct?"])->withInput();
</code>```

This will return the user to the view they were on previously, displaying the specified error for the specified field (if it exists), and re-populate all the fields with the information the user just entered, allowing them to simply adjust the incorrect field rather than fill out the whole form again.

Another functionally similar alternative would be to do something like this:

```<code>throw ValidationException::withMessages(['email' => 'Are you sure the email is correct?']);
</code>```

Body:
Have a method that's importing CSV-data into a Database. I do some basic validation using

class CsvImportController extends Controller
{
    public function import(Request $request)
    {
        $this->validate($request, [
            'csv_file' => 'required|mimes:csv,txt',
        ]);

But after that things can go wrong for more complex reasons, further down the rabbit hole, that throws exceptions of some sort. I can't write proper validation stuff to use with the validate method here, but, I really like how Laravel works when the validation fails and how easy it is to embed the error(s) into the blade view etc, so...

Is there a (preferably clean) way to manually tell Laravel that "I know I didn't use your validate method right now, but I'd really like you to expose this error here as if I did"? Is there something I can return, an exception I can wrap things with, or something?

try
{
    // Call the rabbit hole of an import method
}
catch(\Exception $e)
{
    // Can I return/throw something that to Laravel looks
    // like a validation error and acts accordingly here?
}

Body:
In Laravel 8 and above, the following works in both a controller and a model:

return back()->withErrors(["email" => "Are you sure the email is correct?"])->withInput();

This will return the user to the view they were on previously, displaying the specified error for the specified field (if it exists), and re-populate all the fields with the information the user just entered, allowing them to simply adjust the incorrect field rather than fill out the whole form again.

Another functionally similar alternative would be to do something like this:

throw ValidationException::withMessages(['email' => 'Are you sure the email is correct?']);


问:
How do physics engines model angular velocity and angular acceleration (in 3D)
I have been looking around for answers to this question and I can't find a straight answer.
It seems the word online is that angular velocity is stored as a vector, where the direction is the axis of rotation and the length is the rate of rotation.
That makes some sense but it completely neglects how you actually work with it.
So there are 2 critical operations that need to be done.

Apply angular acceleration (how do you add a angular acceleration (presumably in the same data type) to your angular velocity?)

Calculate the velocity of a point on the rigidbody taking into account both angular and linear velocity.

I have looked at how physics engines like bullet handle it but the math is very confusing and some of the operator overloads seem to hide what is actually going on.

Answers are preferred in C++ or C but as long as the math is clear anything works.

答:
Data Structures

First some data structures.

Linear Algebra

I assume there are Vector3 classes for 3 valued vectors and Quaternion classes for 4 valued rotations as well as Matrix3 for 3×3 inertia and rotations and other operations. Each obeys its corresponding rules of linear algebra (addition +, subtraction -, scaling *, and products *). Each object has its own rules on how to handle these operators. It might be a scale operation, or a matrix-vector product, or a quaternion product depending on the context.

Body Properties

Each body has a scalar mass m, and a body mass moment of inertia tensor I_body which are used in the equations of motion. You also should keep the inverse inertia I_body_inv = inverse( I_body ).

Body State

The current state of the body, contains its position r (Vector3), orientation q (Quaternion) and motion. But commonly instead of storing the two velocity vectors (translational v (Vector3), rotational ω (Vector 3)), the two momentum vectors are stored (linear p (Vector 3), angular L (Vector 3)). Each summed at the center of mass.

The state vector has 13 components since each vector has 3 and the quaternion q has 4

Y = [ r, q, p, L ]

You can choose to make Y an array/vector, or a struct with appropriate operators to perform linear algebra with.

Motion Extraction

Given Y you can always extract the translational velocity v and angular velocity ω of the body with the following algorithm

```<code>[v, ω] = GetMotion(Y)
// Get Motion from Y=[r, q, p, L]

r = Y[0:2];
q = Y[3:6];
p = Y[7:9];
L = Y[10:12];

// Get 3×3 rotation matrix R from orientation q
R = rotation(q);

// Get 3×3 inverse mass moment of inertia on the world frame
I_inv = R * I_body_inv * transpose(R);

// Get translational velocity vector
v = p / m;

// Get rotational velocity vector
ω = I_inv * L;

return [v, ω];
</code>```

The reverse is also needed to set the initial conditions of the body

```<code>Y = GetState(r, q, v, ω)
// Get state vector from position & motion

// Get 3×3 rotation matrix R from orientation q
R = rotation(q);

// Get 3×3 mass moment of inertia on the world frame
I = R * I_body * transpose(R);

// Get translational momentum vector
p = m * v;

// Get angular momentum vector
L = I * ω;

return [r, q, p, L];
</code>```

Integration

At each time step the applied load vectors (force F, torque τ) change the body state vector.

Body State Rate

The time rate of the body state, I call Y', is calculated as follows

```<code>Y' = GetRate(t, Y)
// Assemble the time rate of the body state Y at time t

r = Y[0:2];
q = Y[3:6];
p = Y[7:9];
L = Y[10:12];

// Get the motion of the body
[v, ω] = GetMotion(Y);

// Get the loading
[F, τ] = GetLoading(t, r, q, v, ω);

r' = v
q' = 0.5*quaterion(ω)*q
p' = F
L' = τ

return [r', q', p', L'];
</code>```

where quaternion(ω) = [ωx,ωy,ωz,0] and quaterion product * is per quaternion rules.

Runge-Kutta 4

It is common to integrate over time using the RK4 method

```<code>ΔY = GetStep(t, Y, h)
// Integrate state vector Y, over time step h at time t

K0 = GetRate(t, Y);
K1 = GetRate(t+h/2, Y + h/2*K0);
K2 = GetRate(t+h/2, Y + h/2*K1);
K3 = GetRate(t+h, Y + h*K2);

return h/6*(K0 + 2*K1 + 2*K2 + K3);
</code>```

Simulation

A simulation is the integration of the state vector over many finite time steps.

Body Loading

A loading function that describes the forces/torques on each body at each time frame is needed to evaluate the state rate

```<code>[F,τ] = GetLoading(t, r, q, v, ω)
// Describe the force vector F, and torque vector τ
// from time t, position r, orientation q,
// velocity v, and rot. velocity ω
</code>```

Simulation Loop

And the simulation loop integrates until the target time is reached

```<code>Y = GetState(r, q, v, ω);
time = 0;
while(time<target_time)
{
    Y += GetStep(time, Y, h);
    time += h;
}
</code>```

And there you have the basics of a single rigid body simulation.

Post Processing

When you have the body state Y you get the motion of the center of mass with [v, ω] = GetMotion(Y). But to answer the second question you need to the velocity of an arbitrary point v_A. The point is located with vector r_A

```<code>v_A = GetVelocityAtPoint(Y, r_A)
// Get velocity of world point A
r = Y[0:2]
[v, ω] = GetMotion(Y)

return v + cross(ω, r_A - r);
</code>```

If you want the velocity of a point v_B riding on the body, and defined by a local vector r_B_body then

```<code>v_B = GetVelocityAtBodyPoint(Y, r_B_body)
// Get velocity of body point B
r = Y[0:2]
q = Y[3:6]
R = rotation(q)
r_A = r + R*r_B_body
return GetVelocityAtPoint(Y, r_A)
</code>```

Note that over many steps, the orientation Quaternion q might drift from a unit quaternion and it would need to be re-normlized.

```<code>q = normalize(q)
// m = sqrt(qx^2+qy^2+qz^2+qw^2)
// q = q/m
</code>```

In my experience, the drifting away from a unit quaternion does not get progressively worse, as it tends to drift away and then drift back to a unit quaternion, and the resulting error in orientation angle is actually pretty small.

Body:
Data Structures

First some data structures.

Linear Algebra

I assume there are Vector3 classes for 3 valued vectors and Quaternion classes for 4 valued rotations as well as Matrix3 for 3×3 inertia and rotations and other operations. Each obeys its corresponding rules of linear algebra (addition +, subtraction -, scaling *, and products *). Each object has its own rules on how to handle these operators. It might be a scale operation, or a matrix-vector product, or a quaternion product depending on the context.

Body Properties

Each body has a scalar mass m, and a body mass moment of inertia tensor I_body which are used in the equations of motion. You also should keep the inverse inertia I_body_inv = inverse( I_body ).

Body State

The current state of the body, contains its position r (Vector3), orientation q (Quaternion) and motion. But commonly instead of storing the two velocity vectors (translational v (Vector3), rotational ω (Vector 3)), the two momentum vectors are stored (linear p (Vector 3), angular L (Vector 3)). Each summed at the center of mass.

The state vector has 13 components since each vector has 3 and the quaternion q has 4

Y = [ r, q, p, L ]

You can choose to make Y an array/vector, or a struct with appropriate operators to perform linear algebra with.

Motion Extraction

Given Y you can always extract the translational velocity v and angular velocity ω of the body with the following algorithm

[v, ω] = GetMotion(Y)
// Get Motion from Y=[r, q, p, L]

r = Y[0:2];
q = Y[3:6];
p = Y[7:9];
L = Y[10:12];

// Get 3×3 rotation matrix R from orientation q
R = rotation(q);

// Get 3×3 inverse mass moment of inertia on the world frame
I_inv = R * I_body_inv * transpose(R);

// Get translational velocity vector
v = p / m;

// Get rotational velocity vector
ω = I_inv * L;

return [v, ω];

The reverse is also needed to set the initial conditions of the body

Y = GetState(r, q, v, ω)
// Get state vector from position & motion

// Get 3×3 rotation matrix R from orientation q
R = rotation(q);

// Get 3×3 mass moment of inertia on the world frame
I = R * I_body * transpose(R);

// Get translational momentum vector
p = m * v;

// Get angular momentum vector
L = I * ω;

return [r, q, p, L];

Integration

At each time step the applied load vectors (force F, torque τ) change the body state vector.

Body State Rate

The time rate of the body state, I call Y', is calculated as follows

Y' = GetRate(t, Y)
// Assemble the time rate of the body state Y at time t

r = Y[0:2];
q = Y[3:6];
p = Y[7:9];
L = Y[10:12];

// Get the motion of the body
[v, ω] = GetMotion(Y);

// Get the loading
[F, τ] = GetLoading(t, r, q, v, ω);

r' = v
q' = 0.5*quaterion(ω)*q
p' = F
L' = τ

return [r', q', p', L'];

where quaternion(ω) = [ωx,ωy,ωz,0] and quaterion product * is per quaternion rules.

Runge-Kutta 4

It is common to integrate over time using the RK4 method

ΔY = GetStep(t, Y, h)
// Integrate state vector Y, over time step h at time t

K0 = GetRate(t, Y);
K1 = GetRate(t+h/2, Y + h/2*K0);
K2 = GetRate(t+h/2, Y + h/2*K1);
K3 = GetRate(t+h, Y + h*K2);

return h/6*(K0 + 2*K1 + 2*K2 + K3);

Simulation

A simulation is the integration of the state vector over many finite time steps.

Body Loading

A loading function that describes the forces/torques on each body at each time frame is needed to evaluate the state rate

[F,τ] = GetLoading(t, r, q, v, ω)
// Describe the force vector F, and torque vector τ
// from time t, position r, orientation q,
// velocity v, and rot. velocity ω

Simulation Loop

And the simulation loop integrates until the target time is reached

Y = GetState(r, q, v, ω);
time = 0;
while(time<target_time)
{
    Y += GetStep(time, Y, h);
    time += h;
}

And there you have the basics of a single rigid body simulation.

Post Processing

When you have the body state Y you get the motion of the center of mass with [v, ω] = GetMotion(Y). But to answer the second question you need to the velocity of an arbitrary point v_A. The point is located with vector r_A

v_A = GetVelocityAtPoint(Y, r_A)
// Get velocity of world point A
r = Y[0:2]
[v, ω] = GetMotion(Y)

return v + cross(ω, r_A - r);

If you want the velocity of a point v_B riding on the body, and defined by a local vector r_B_body then

v_B = GetVelocityAtBodyPoint(Y, r_B_body)
// Get velocity of body point B
r = Y[0:2]
q = Y[3:6]
R = rotation(q)
r_A = r + R*r_B_body
return GetVelocityAtPoint(Y, r_A)

Note that over many steps, the orientation Quaternion q might drift from a unit quaternion and it would need to be re-normlized.

q = normalize(q)
// m = sqrt(qx^2+qy^2+qz^2+qw^2)
// q = q/m

In my experience, the drifting away from a unit quaternion does not get progressively worse, as it tends to drift away and then drift back to a unit quaternion, and the resulting error in orientation angle is actually pretty small.


问:
Render HTML string in Node?
Alright, so I have downloaded Express, set the port with process.env.PORT || 8080, and set the app variable var app = express(). Now, what I'm trying to accomplish is instead of rendering HTML through a file, could I do it through a string?

```<code>var html = "<!DOCTYPE html>\n<html>\n    <head>\n    </head>\n <body>\n      <h1>Hello World!</h1>\n   </body>\n</html>";
app.get('/',function(req,res){
   res.render(html);
});
</code>```

Is there a possible way to do this?

答:
Use res.setHeader set HTTP Response Header

  res.setHeader("Content-Type", "text/html")
  res.send(`

Mock API

  `)
```

Title: Render HTML string in Node?

Body:
Alright, so I have downloaded Express, set the port with process.env.PORT || 8080, and set the app variable var app = express(). Now, what I'm trying to accomplish is instead of rendering HTML through a file, could I do it through a string?

var html = "<!DOCTYPE html>\n\n    \n    \n \n
Hello World!
\n   \n";
app.get('/',function(req,res){
   res.render(html);
});

Is there a possible way to do this?

Body:
Use res.setHeader set HTTP Response Header

  res.setHeader("Content-Type", "text/html")
  res.send(`
  <h1>Mock API</h1>
  `)


问:
Difference between @Binding and Binding<Type> in Swift
I understand that @Binding is a property wrapper and I believe that Binding<Type> is a form of type casting but what is the difference in practical terms?

For example declaring a var like:

@Binding
var hidden: Bool
```
<p>versus</p>
<pre class="lang-swift prettyprint-override"><code>var hidden: Binding<Bool>
</code>```

答:
You're correct that @Binding is a property wrapper. More specifically, it's a DynamicProperty, which means that it has the ability to notify its parent View to trigger a render when its value changes.

@Binding does this while maintaining a fairly transparent interface to the underlying Bool. For example, in a View where you had @Binding var hidden: Bool defined as a property, you could write hidden = false or Text(hidden ? "hidden" : "visible"), just as if hidden were a regular Bool. If you want to get access to the underlying Binding<Bool>, you can use $:

```<code>$hidden //<-- Binding<Bool>
</code>```

In your second example, Binding<Bool> is not "type casting", but rather "type annotation" -- by writing var hidden: Binding<Bool>, you're telling the compiler that hidden is Binding<Bool>. Because it's Binding<Bool> and not just a Bool (and not a @Binding), you can't treat it like you would if it were just a Bool. For example, hidden = false will not work with Binding<Bool>. Instead, to access the underlying Bool value, you can use its .wrappedValue property: hidden.wrappedValue = false.

The two are are very similar, but different in a couple of important ways (like those detailed above). In practical terms:

If you're using a binding as a property on a View, you'll likely end up using @Binding.

If you're the binding it outside of a view (and thus don't have use of the DynamicProperty aspect), you'll likely use Binding<Bool> (technically, nothing is stopping you from using @Binding outside of a View, but it's a semantically odd decision).

Body:
I understand that @Binding is a property wrapper and I believe that Binding<Type> is a form of type casting but what is the difference in practical terms?

For example declaring a var like:

@Binding
var hidden: Bool

versus

var hidden: Binding<Bool>

Body:
You're correct that @Binding is a property wrapper. More specifically, it's a DynamicProperty, which means that it has the ability to notify its parent View to trigger a render when its value changes.

@Binding does this while maintaining a fairly transparent interface to the underlying Bool. For example, in a View where you had @Binding var hidden: Bool defined as a property, you could write hidden = false or Text(hidden ? "hidden" : "visible"), just as if hidden were a regular Bool. If you want to get access to the underlying Binding<Bool>, you can use $:

$hidden //<-- Binding<Bool>

In your second example, Binding<Bool> is not "type casting", but rather "type annotation" -- by writing var hidden: Binding<Bool>, you're telling the compiler that hidden is Binding<Bool>. Because it's Binding<Bool> and not just a Bool (and not a @Binding), you can't treat it like you would if it were just a Bool. For example, hidden = false will not work with Binding<Bool>. Instead, to access the underlying Bool value, you can use its .wrappedValue property: hidden.wrappedValue = false.

The two are are very similar, but different in a couple of important ways (like those detailed above). In practical terms:

If you're using a binding as a property on a View, you'll likely end up using @Binding.

If you're the binding it outside of a view (and thus don't have use of the DynamicProperty aspect), you'll likely use Binding<Bool> (technically, nothing is stopping you from using @Binding outside of a View, but it's a semantically odd decision).


问:
What return this function in typescript?
When I hover on the keyword 'function' the description says:

"(local function)(this: any, next: (err?: mongoose.CallbackError | undefined) => void): Promise<void>"

So does It return a Promise<void> or a simple <void>? I can't even understand what does this function returns? And to be honest I don't understand really well the concept of Promise<void>...

userSchema.pre('save', async function (next) {

    let user = this as UserDocument;
    if(!user.isModified('password')){
        return next();
    }

    const salt = await bcrypt.genSalt(config.get<number>('saltWorkFactor'));
    const hash = await bcrypt.hash(user.password, salt);

    user.password = hash;
    return next();

})
```

答:
Long answer short: It return a Promise<void>

Callbacks

To understand why, here are some details.
First one must understand Callbacks in node.js. Callbacks are one of the basic structure/feature of how node.js works.

You could say that node.js is basically an Event-Driven Programming "framework" (most people will frown to the framework word...). That means that you tell node that in the event of a certain thing happening, it should do a certain action/function (callback).

For node to understand us, we normally give the callback function as a parameter to another function that will do the work of "listening to the event" and executing the callback that we give it. So it is not "us" that execute the callback, it is the event listener.

In your case,

```<code>userSchema.pre('save', async function (next) {
</code>```

pre is the function (a method in Mongoose's userSchema), save is the event that one must react to, async function (next) { is the callback or what must be done after the event.

You will note that your callback is returning next(), but next() returns void, which mean that your callback is returning void.
So why is it returning Promise<void>?

The fact is that in your case, your callback is an async function. And every async functions will return a promise. It is an async function because it is awaiting another promise (two promises even) inside of it. They are hidden because of the await

```<code>const salt = await bcrypt.genSalt(config.get<number>('saltWorkFactor'));
const hash = await bcrypt.hash(user.password, salt);
</code>```

Note: The bcrypt methods are very expensive in terms of CPU and time (also a security feature among other things).

It also means that normally in your code

```<code>const hash = await bcrypt.hash(user.password, salt);
user.password = hash;
</code>```

you couldn't have available "right away" the hash value for the user.password and, worse, you couldn't even know when it would come. Will your program stop and wait until bcrypt finish its business?
If you have many async functions, your program will be a great favourite for the slowest champion in the Olympics.

What is going on with those promises and how can we not be labelled as a geriatric program?

Promises

Here is a quick/long comment to try to explain the concept of promises.

In "normal" code, each lines of code is executed and "finished" before the next one. Ex: (with cooking)

Combine the Butter and Sugar,

Add Eggs One at a Time, etc.

Or in your code:

```<code> let user = this as UserDocument;
if(!user.isModified('password')){
    return next();
}
</code>```

A promise is a certain code that is executed but not finished before the next line of code. Ex:

while the cake is in the oven (promise),

you prepare the frosting,

but you can't put it until the cake in baked (the "then" action of promises).

Note: Your code is using await so there is no "explicit" then method.

You will have many example of "promises" things in everyday life. you may have heard of asynchronous code = not one after the other, not in sync, ...

Turning on an alarm to wake you in the morning, then you make the promise that you will not ignore it;

putting a reminder on the calendar then you make the promise that you will go to that job interview; etc.

All the while, you continue with your life after making those promises.

In code, a function that returns a promise will have a then method where you tell the computer what to do when when the "alarms goes off".
It is usually written like this

```<code>mypromise().then(doThisThingFunction)

const continueWithMyLife = true
</code>```

In this way the then method is very similar to the callback of node.js. It is just expressed in a different way in the code and is not specific to node (callbacks are also not specific to node...).
One very important difference between them is that callbacks are something that the listener "do" and promises is something that resolves (hopefully) to a returning value.

Async/Await

Nowadays it is common to use async/await. Fortunately/unfortunately it basically hides the asynchronous behaviour. Better flow of reading the code, but also much worse understanding of promises for new programmers.

After a await, there is no then method (Or you could say that the following line of code is the then action). There is no "continuing with your life". There is only "waiting until the alarms goes off", So the next line after the await is essentially the "get out of the bed action".

That is why, in your code, the hash value is available in the next line. Basically in the "old way" to write promises

```<code>user.password = hash;
</code>```

would be inside the then function.

And that is also why it is returning Promise<void>

But still, all these analogies won't really help. The best is to try it in everyday code. There is nothing like experience to understand anything.

Body:
Long answer short: It return a Promise<void>

Callbacks

To understand why, here are some details.
First one must understand Callbacks in node.js. Callbacks are one of the basic structure/feature of how node.js works.

You could say that node.js is basically an Event-Driven Programming "framework" (most people will frown to the framework word...). That means that you tell node that in the event of a certain thing happening, it should do a certain action/function (callback).

For node to understand us, we normally give the callback function as a parameter to another function that will do the work of "listening to the event" and executing the callback that we give it. So it is not "us" that execute the callback, it is the event listener.

In your case,

userSchema.pre('save', async function (next) {

pre is the function (a method in Mongoose's userSchema), save is the event that one must react to, async function (next) { is the callback or what must be done after the event.

You will note that your callback is returning next(), but next() returns void, which mean that your callback is returning void.
So why is it returning Promise<void>?

The fact is that in your case, your callback is an async function. And every async functions will return a promise. It is an async function because it is awaiting another promise (two promises even) inside of it. They are hidden because of the await

const salt = await bcrypt.genSalt(config.get<number>('saltWorkFactor'));
const hash = await bcrypt.hash(user.password, salt);

Note: The bcrypt methods are very expensive in terms of CPU and time (also a security feature among other things).

It also means that normally in your code

const hash = await bcrypt.hash(user.password, salt);
user.password = hash;

you couldn't have available "right away" the hash value for the user.password and, worse, you couldn't even know when it would come. Will your program stop and wait until bcrypt finish its business?
If you have many async functions, your program will be a great favourite for the slowest champion in the Olympics.

What is going on with those promises and how can we not be labelled as a geriatric program?

Promises

Here is a quick/long comment to try to explain the concept of promises.

In "normal" code, each lines of code is executed and "finished" before the next one. Ex: (with cooking)

Combine the Butter and Sugar,

Add Eggs One at a Time, etc.

Or in your code:

 let user = this as UserDocument;
if(!user.isModified('password')){
    return next();
}

A promise is a certain code that is executed but not finished before the next line of code. Ex:

while the cake is in the oven (promise),

you prepare the frosting,

but you can't put it until the cake in baked (the "then" action of promises).

Note: Your code is using await so there is no "explicit" then method.

You will have many example of "promises" things in everyday life. you may have heard of asynchronous code = not one after the other, not in sync, ...

Turning on an alarm to wake you in the morning, then you make the promise that you will not ignore it;

putting a reminder on the calendar then you make the promise that you will go to that job interview; etc.

All the while, you continue with your life after making those promises.

In code, a function that returns a promise will have a then method where you tell the computer what to do when when the "alarms goes off".
It is usually written like this

mypromise().then(doThisThingFunction)

const continueWithMyLife = true

In this way the then method is very similar to the callback of node.js. It is just expressed in a different way in the code and is not specific to node (callbacks are also not specific to node...).
One very important difference between them is that callbacks are something that the listener "do" and promises is something that resolves (hopefully) to a returning value.

Async/Await

Nowadays it is common to use async/await. Fortunately/unfortunately it basically hides the asynchronous behaviour. Better flow of reading the code, but also much worse understanding of promises for new programmers.

After a await, there is no then method (Or you could say that the following line of code is the then action). There is no "continuing with your life". There is only "waiting until the alarms goes off", So the next line after the await is essentially the "get out of the bed action".

That is why, in your code, the hash value is available in the next line. Basically in the "old way" to write promises

user.password = hash;

would be inside the then function.

And that is also why it is returning Promise<void>

But still, all these analogies won't really help. The best is to try it in everyday code. There is nothing like experience to understand anything.


问:
Pandas Group By, Aggregate, Then Return A Different Column
I have a pandas DataFrame containing baseball fielding statistics. Each row shows how many games a player has appeared at a given position over the course of his career.

Player
Position
Games

Brock Holt
2B
20

Brock Holt
3B
70

Ben Zobrist
OF
100

Ben Zobrist
2B
15

I want to be able to return one row per player containing the position they played the most over the years. In the example above the resulting DataFrame would be:

Player
Position

Brock Holt
3B

Ben Zobrist
OF

I've been attempting to group by Player and aggregate by Games like so

```<code>df.groupby('Player').agg({'Games':['max']})
</code>```

which simply provides the name of the player and the maximum number of games played at a position and

```<code>df.groupby('Player')['Position'].agg({'Games':['max']})
</code>```

which returns the error "nested renamer is not supported."

答:
You can also just use groupby and max directly as below:

```<code>df.groupby(['Player']).max()
</code>```

Yields:

```<code>           Position Games
Player
Ben Zobrist OF      100
Brock Holt  3B      70
</code>```

Body:
I have a pandas DataFrame containing baseball fielding statistics. Each row shows how many games a player has appeared at a given position over the course of his career.

Player
Position
Games

Brock Holt
2B
20

Brock Holt
3B
70

Ben Zobrist
OF
100

Ben Zobrist
2B
15

I want to be able to return one row per player containing the position they played the most over the years. In the example above the resulting DataFrame would be:

Player
Position

Brock Holt
3B

Ben Zobrist
OF

I've been attempting to group by Player and aggregate by Games like so

df.groupby('Player').agg({'Games':['max']})

which simply provides the name of the player and the maximum number of games played at a position and

df.groupby('Player')['Position'].agg({'Games':['max']})

which returns the error "nested renamer is not supported."

Body:
You can also just use groupby and max directly as below:

df.groupby(['Player']).max()

Yields:

           Position Games
Player
Ben Zobrist OF      100
Brock Holt  3B      70


问:
Django rest framework How to fix many-to-many n+1 error?
I have models:

```<code>class Group(models.Model):
    number = models.CharField(choices=CLASS_NUMBERS,
                              max_length=2,
                              verbose_name="Номер класса")
    name = models.CharField(max_length=20,
                            verbose_name="Название класса")
    group_teacher = models.ForeignKey('users.Teacher',
                                      on_delete=models.CASCADE,
                                      verbose_name="Классный руководитель",
                                      related_name='group_teacher')
    students = models.ManyToManyField('users.Student',
                                      verbose_name="Ученики", blank=True,
                                      related_name='group_students')
    code = models.CharField(max_length=8, unique=True)

class Teacher(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,
                                verbose_name="Преподаватель", related_name='teacher_user')
class Student(models.Model):
    user = models.OneToOneField(User,
                                on_delete=models.CASCADE,
                                verbose_name="Ученик", related_name='student_user')
</code>```

and serializers:

```<code>class TeacherSerializer(ModelSerializer):
    class Meta:
        model = Teacher
        fields = [
            'user'
        ]

class StudentsSerializer(ModelSerializer):
    class Meta:
        model = Student
        fields = [
            'user'
        ]

class GroupSerializer(ModelSerializer):
    class Meta:
        model = Group
        fields = [
            'id',
            'number',
            'name',
            'code',
            'group_teacher',
            'students',
        ]
</code>```

When I make an appeal to the api I get warnings:

Potential n+1 query detected on Teacher.user Potential n+1 query
detected on Teacher.user Potential n+1 query detected on
Student.user Potential n+1 query detected on Student.user
Potential n+1 query detected on Student.user Potential n+1 query
detected on Student.user

Queries

my view set:

```<code>class GroupModelViewSet(viewsets.ModelViewSet):
    serializer_class = GroupSerializer

    def get_queryset(self):
        return Group.objects.all().prefetch_related('students')
</code>```

How to fix these errors n+1, select_related does not let me select the model of students and teachers

答:
The N+1 query problem happens when the data access framework executed N additional SQL statements to fetch the same data that could have been retrieved when executing the primary SQL query.

You are trying to reach the same database table from all serializers

in your case, this will work

```<code>class TeacherSerializer(ModelSerializer):
    class Meta:
        model = Teacher
        fields = "__all__"

class StudentsSerializer(ModelSerializer):
    class Meta:
        model = Student
        fields = "__all__"

class GroupSerializer(ModelSerializer):
    class Meta:
        model = Group
        fields = [
            'id',
            'number',
            'name',
            'code',
            'group_teacher',
            'students',
        ]
</code>```

```<code>class GroupModelViewSet(viewsets.ModelViewSet):
    serializer_class = GroupSerializer

    def get_queryset(self):
        return Group.objects.all().prefetch_related('group_teacher', 'group_students')

</code>```

Using the related_name allows you to specify a simpler or more legible name to get the reverse relation. In this case, if you specify user = models.ForeignKey(User, related_name='tech_user'), the call would then be User.tech_user.all()

```<code>prefetch_related('tech_user')
</code>```

Body:
I have models:

class Group(models.Model):
    number = models.CharField(choices=CLASS_NUMBERS,
                              max_length=2,
                              verbose_name="Номер класса")
    name = models.CharField(max_length=20,
                            verbose_name="Название класса")
    group_teacher = models.ForeignKey('users.Teacher',
                                      on_delete=models.CASCADE,
                                      verbose_name="Классный руководитель",
                                      related_name='group_teacher')
    students = models.ManyToManyField('users.Student',
                                      verbose_name="Ученики", blank=True,
                                      related_name='group_students')
    code = models.CharField(max_length=8, unique=True)

class Teacher(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,
                                verbose_name="Преподаватель", related_name='teacher_user')
class Student(models.Model):
    user = models.OneToOneField(User,
                                on_delete=models.CASCADE,
                                verbose_name="Ученик", related_name='student_user')

and serializers:

class TeacherSerializer(ModelSerializer):
    class Meta:
        model = Teacher
        fields = [
            'user'
        ]

class StudentsSerializer(ModelSerializer):
    class Meta:
        model = Student
        fields = [
            'user'
        ]

class GroupSerializer(ModelSerializer):
    class Meta:
        model = Group
        fields = [
            'id',
            'number',
            'name',
            'code',
            'group_teacher',
            'students',
        ]

When I make an appeal to the api I get warnings:

Potential n+1 query detected on Teacher.user Potential n+1 query
detected on Teacher.user Potential n+1 query detected on
Student.user Potential n+1 query detected on Student.user
Potential n+1 query detected on Student.user Potential n+1 query
detected on Student.user

Queries

my view set:

class GroupModelViewSet(viewsets.ModelViewSet):
    serializer_class = GroupSerializer

    def get_queryset(self):
        return Group.objects.all().prefetch_related('students')

How to fix these errors n+1, select_related does not let me select the model of students and teachers

Body:
The N+1 query problem happens when the data access framework executed N additional SQL statements to fetch the same data that could have been retrieved when executing the primary SQL query.

You are trying to reach the same database table from all serializers

in your case, this will work

class TeacherSerializer(ModelSerializer):
    class Meta:
        model = Teacher
        fields = "__all__"

class StudentsSerializer(ModelSerializer):
    class Meta:
        model = Student
        fields = "__all__"

class GroupSerializer(ModelSerializer):
    class Meta:
        model = Group
        fields = [
            'id',
            'number',
            'name',
            'code',
            'group_teacher',
            'students',
        ]

class GroupModelViewSet(viewsets.ModelViewSet):
    serializer_class = GroupSerializer

    def get_queryset(self):
        return Group.objects.all().prefetch_related('group_teacher', 'group_students')

Using the related_name allows you to specify a simpler or more legible name to get the reverse relation. In this case, if you specify user = models.ForeignKey(User, related_name='tech_user'), the call would then be User.tech_user.all()

prefetch_related('tech_user')


问:
What does != 0 mean in this command line -> NR%2 != 0'
I have tested both of the commands.

```<code>ls -l | awk 'NR%2 != 0'
ls -l | awk 'NR%2'
</code>```

I saw the difference in the output, but, I do not know how can I explain it when I am teaching it to someone else.

Could you explain to me what != 0 means exactly?

答:
In awk, the variable NR is preset with "the total number of input records seen so far". Thus, when processing the first line it is set to 1, for the second line to 2, etc.

The % operator calculates the remainder of a numerical division. Thus, with NR%2 denoting the remainder when dividing the records number by 2, for the first line this computes to 1, for the second to 0, for the third to 1 again, and so on.

To determine whether a record is an odd row or an even row, just check whether NR%2 evaluates to 1 or to 0, i.e. NR%2 == 1 or NR%2 == 0. As 1 and 0 are the only possible values, one could also check for the negation of the opposite: NR%2 != 0 and NR%2 != 1, respectively.

In awk, a typical instruction consists of a pattern or condition (evaluating to a boolean value) and an action statement. In your case, the action statements are missing, which means the current record should be printed if the condition evaluates to true. For convenience, if the condition evaluates to a number instead (as in your second case), the number is automatically cast to a boolean value, with 0 becomng false, and any other value becoming true.

Therefore, awk 'NR%2 != 0' which evaluates to true on every other line starting with the first, will print odd rows and skip even rows. awk 'NR%2 == 1' will do the same. And as 1 is cast to true, just awk 'NR%2' will also do the same.

Body:
I have tested both of the commands.

ls -l | awk 'NR%2 != 0'
ls -l | awk 'NR%2'

I saw the difference in the output, but, I do not know how can I explain it when I am teaching it to someone else.

Could you explain to me what != 0 means exactly?


问:
Creating a C++ Class Diagram
In Visual Studio .NET projects you can add a "Class Diagram" to the project which renders a visual representation of all namespaces, classes, methods, and properties.  Is there any way to do this for Win32 (not .NET) C++ projects?  Either through Visual Studio itself or with a 3rd party tool?</p>

答:
If you have a Visual Studio 2008 solution composed of multiple C++ projects, you can only generate one class diagram per project.

For example, if you have one application project linking to 10 library projects, you'll have to generate 11 separate class diagrams.

There are two ways to work around this, neither of which is pleasant:

Cram all the source into a single project.

Create a class diagram for one project (the application, perhaps) and then drag files from all the other projects into the class diagram.

A more thorough exploration of the capabilities of the Visual Studio class designer is given in Visual C++ Class Designer.

Given the poor support for C++ class diagrams in Visual Studio, you're probably better off going with a commercial tool if you want anything more than a simple list of what classes you have.  WinTranslator from Excel Software might be worth looking at, and someone I work with uses Source Insight.

OwnerDisplayName: Adam Haile

ContentLicense: CC BY-SA 2.5

Title: Creating a C++ Class Diagram


问:
Error in opening text file from src folder in Java
I am making a Java program and want to open a text(notepad) file ,that i have saved in src folder in my Java Program, I have tried to do it by the following code , but it is giving error. "The method exec(String) in the type Runtime is not applicable for the arguments
(InputStream) , Any suggestions ? Thanks

```<code>Runtime runtime = Runtime.getRuntime();
InputStream lic = this.getClass().getClassLoader().getResourceAsStream("MyFile.txt");
Process process = runtime.exec(lic);
</code>```

答:
I think this is what you're trying to do:

```<code>ProcessBuilder pb = new ProcessBuilder("notepad", "/path/to/text-file");
Process process = pb.start();
</code>```

See ProcessBuilder Javadocs.

Body:
I am making a Java program and want to open a text(notepad) file ,that i have saved in src folder in my Java Program, I have tried to do it by the following code , but it is giving error. "The method exec(String) in the type Runtime is not applicable for the arguments
(InputStream) , Any suggestions ? Thanks

Runtime runtime = Runtime.getRuntime();
InputStream lic = this.getClass().getClassLoader().getResourceAsStream("MyFile.txt");
Process process = runtime.exec(lic);

Body:
I think this is what you're trying to do:

ProcessBuilder pb = new ProcessBuilder("notepad", "/path/to/text-file");
Process process = pb.start();

See ProcessBuilder Javadocs.


问:
Laravel installation sail problem ((23) Failed writing body)
I try to install laravel with the original laravel document but nothing happened, I got many errors, for example I tried this command on CMD;

```<code>curl -s https://laravel.build/example-app | bash
</code>```

but I got this error

(23) Failed writing body

When I tried with PowerShell I got this error;

```<code>cmdlet Invoke-WebRequest at command pipeline position 1
Supply values for the following parameters:
Uri:
curl : Cannot find drive. A drive with the name 'https' does not exist.
At line:1 char:1
 curl -s https://laravel.build/example-app | bash
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 CategoryInfo          : ObjectNotFound: (https:String) [Invoke-WebRequest], DriveNotFoundException
 FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
</code>```

Specs;

Docker Engine v20.10.0

Edition   Windows 10 Home Version 20H2 Installed on   14/08/2020 OS
build 19042.685 Experience    Windows Feature Experience Pack
120.2212.551.0

答:
The solution above provided by @chris-j works like a charm, but if you still get the error "Docker in not running" even if the it's green consider doing the following

Do sudo su and then curl -s https://laravel.build/example-app | bash

Body:
I try to install laravel with the original laravel document but nothing happened, I got many errors, for example I tried this command on CMD;

curl -s https://laravel.build/example-app | bash

but I got this error

(23) Failed writing body

When I tried with PowerShell I got this error;

cmdlet Invoke-WebRequest at command pipeline position 1
Supply values for the following parameters:
Uri:
curl : Cannot find drive. A drive with the name 'https' does not exist.
At line:1 char:1
 curl -s https://laravel.build/example-app | bash
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 CategoryInfo          : ObjectNotFound: (https:String) [Invoke-WebRequest], DriveNotFoundException
 FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Specs;

Docker Engine v20.10.0

Edition   Windows 10 Home Version 20H2 Installed on   14/08/2020 OS
build 19042.685 Experience    Windows Feature Experience Pack
120.2212.551.0


问:
In SQL, how to increment a value that is a number, but set a value to 1 if it's null?
The title explains it. I want to update a column value to add +1 to itself if it is a number, but if it is currently null, change it to a 1. This is what I've tried so far:
"UPDATE table SET colname=ISNULL(colname, 0)+1 WHERE othercolname IN('$val', '$val2')";
I'm fairly new to SQL and have looked at a bunch of things, but can't get it to work.

答:
For this you want to use CASE/WHEN/ELSE

```<code>UPDATE table SET colname = (CASE colname WHEN  NULL THEN 1 ELSE colname + 1 END) WHERE othercolname IN('$val', '$val2')
</code>```

To add more detail, your query sets colname to the return value of ISNULL(colname, 0)+1.  The ISNULL function takes only one parameter and returns 1 if that parameter is NULL and 0 if it is not NULL.  Then you are adding 1.  You will get an 'incorrect parameter count' error and if you fix that you would still only get 2's for NULL values and 1's for everything else.  So contrary to popular opinion that query does not look fine.

Body:
For this you want to use CASE/WHEN/ELSE

UPDATE table SET colname = (CASE colname WHEN  NULL THEN 1 ELSE colname + 1 END) WHERE othercolname IN('$val', '$val2')

To add more detail, your query sets colname to the return value of ISNULL(colname, 0)+1.  The ISNULL function takes only one parameter and returns 1 if that parameter is NULL and 0 if it is not NULL.  Then you are adding 1.  You will get an 'incorrect parameter count' error and if you fix that you would still only get 2's for NULL values and 1's for everything else.  So contrary to popular opinion that query does not look fine.


问:
Retrieve all products with same metadata value in Stripe
In Stripe (using Next.js and Node.js), I'm trying to retrieve all products with the same key-value pair in their metadata:

example: retrieve all products with
metadata: {category: 'foo'}

In attempts to render category-specific pages, I don't want to list and parse through my whole catalog but I also know that products can only be retrieved through id (docs), inferring that I would have to:

```<code>list all products
for all products:
  if metadata matches,
    add id to array
for id array:
  retrieve each
</code>```

This is brute forcing though, and not a good idea.

What would be the best way to retrieve conditionally based on metadata?

Any help is appreciated.

答:
Stripe’s API currently doesn’t support querying Products using metadata. You’d have to retrieve all Products and filter through them. Stripe does have a Search API [2] which is currently in Beta so you might want to write in to see if you qualify.

If you happen to keep a track of Products server-side in a database, you could add an additional column for category. You can query your database by category to find those specific Products and then include just those Product IDs using the ids [2] parameter when you retrieve them through Stripe.

[1] https://stripe.com/docs/search-api

[2] https://stripe.com/docs/api/products/list#list_products-ids

Body:
In Stripe (using Next.js and Node.js), I'm trying to retrieve all products with the same key-value pair in their metadata:

example: retrieve all products with
metadata: {category: 'foo'}

In attempts to render category-specific pages, I don't want to list and parse through my whole catalog but I also know that products can only be retrieved through id (docs), inferring that I would have to:

list all products
for all products:
  if metadata matches,
    add id to array
for id array:
  retrieve each

This is brute forcing though, and not a good idea.

What would be the best way to retrieve conditionally based on metadata?

Any help is appreciated.


问:
defining the value for template in helm
I have created a new helm project and directory structure looks like this as follows:

```<code>my-app-helm
   /my-app-helm
      /charts
         /payment
            /templates
              _helpers.tpl
              secrets.yaml
              deployment.yaml
              ingress.yaml
              service.yaml
        Chart.yaml
        values.yaml
    Chart.yaml
</code>```

I refer to template in many placed like in ingress.yaml:

```<code>  - host: {{ .Values.payment.apphost }}
    http:
      paths:
      - path: /sft/v1/payment/
        backend:
          serviceName: {{ template "payment.fullname" . }}
          servicePort: 80
</code>```

I have a requirement that my service name, ingress name etc is prefixed with "ccg-helm", therefore I would like to ask how can I ensure value is "ccg-helm" where ever I reference "template":

for example:

serviceName: {{ template "payment.fullname" . }}

resolves to ccg-helm-payment

答:
If your chart was created from the helm create command, its template creates the "payment.fullname" template.  The logic there is straightforward:

If the fullnameOverride value is set, use that as-is, {{ .Values.fullnameOverride }}.

Let $name be the nameOverride value, if it's set, otherwise the name from Chart.yaml.

If $name is contained in the release name, use {{ .Release.Name }}.

Otherwise use {{ .Release.Name }}-{{ $name }}.

You'll find this in your chart's _helpers.tpl file.

So you have two deploy-time options to meet this requirement.  Either set fullnameOverride to ccg-helm, or use that name as the release name in the helm install command.

helm install . --generate-name --set fullnameOverride=ccg-helm
helm install . ccg-helm
```

For many simpler charts that is the entire name; if you --set fullnameOverride=ccg-helm then in your example the Service will be named exactly ccg-helm.  If you want it to have some other name then you need to edit both the service.yaml and the ingress.yaml to have a matching name, usually with some sort of suffix after the template invocation.

Title: defining the value for template in helm

Body:
I have created a new helm project and directory structure looks like this as follows:

my-app-helm
   /my-app-helm
      /charts
         /payment
            /templates
              _helpers.tpl
              secrets.yaml
              deployment.yaml
              ingress.yaml
              service.yaml
        Chart.yaml
        values.yaml
    Chart.yaml

I refer to template in many placed like in ingress.yaml:

  - host: {{ .Values.payment.apphost }}
    http:
      paths:
      - path: /sft/v1/payment/
        backend:
          serviceName: {{ template "payment.fullname" . }}
          servicePort: 80

I have a requirement that my service name, ingress name etc is prefixed with "ccg-helm", therefore I would like to ask how can I ensure value is "ccg-helm" where ever I reference "template":

for example:

serviceName: {{ template "payment.fullname" . }}

resolves to ccg-helm-payment

Body:
If your chart was created from the helm create command, its template creates the "payment.fullname" template.  The logic there is straightforward:

If the fullnameOverride value is set, use that as-is, {{ .Values.fullnameOverride }}.

Let $name be the nameOverride value, if it's set, otherwise the name from Chart.yaml.

If $name is contained in the release name, use {{ .Release.Name }}.

Otherwise use {{ .Release.Name }}-{{ $name }}.

You'll find this in your chart's _helpers.tpl file.

So you have two deploy-time options to meet this requirement.  Either set fullnameOverride to ccg-helm, or use that name as the release name in the helm install command.

helm install . --generate-name --set fullnameOverride=ccg-helm
helm install . ccg-helm

For many simpler charts that is the entire name; if you --set fullnameOverride=ccg-helm then in your example the Service will be named exactly ccg-helm.  If you want it to have some other name then you need to edit both the service.yaml and the ingress.yaml to have a matching name, usually with some sort of suffix after the template invocation.


问:
SEQUENCE in Ical
I am creating two ics files programmatically with the same UID. One file has sequence number "2130669611". When I send a new ICS file with a new(greater sequence number 2230669611, I am getting the error that this is an old entry while the new sequence number is greater than the old one.
Is there a max value of the sequence number for outlook?

File 1

```<code>BEGIN:VCALENDAR
VERSION:2.0
PRODID:TTSTTS
METHOD:REQUEST
BEGIN:VEVENT
ORGANIZER:MAILTO:XXX@xx.com
ATTENDEE;CN=Manu Bhai;RSVP=TRUE:MAILTO:manu.bhai@xx.com
DTSTART;TZID=UTC+0:20220322T080000Z
DTEND;TZID=UTC+0:20220322T110000Z
LOCATION:>Room.045
TRANSP:OPAQUE
SEQUENCE:2130669611
UID:E00060977P00001158
SUMMARY:Issue with SEQUENCE.
X-ALT-DESC;FMTTYPE=text/html:<!DOCTYPE HTML>
 < html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body class="defaultFont"> Issue with SEQUENCE </body> </html>
PRIORITY:5
CLASS:PUBLIC
BEGIN:VALARM
TRIGGER:-PT15M
ACTION:DISPLAY
DESCRIPTION:Issue with SEQUENCE
END:VALARM
END:VEVENT
END:VCALENDAR
</code>```

File 2

```<code>BEGIN:VCALENDAR
VERSION:2.0
PRODID:TTSTTS
METHOD:REQUEST
BEGIN:VEVENT
ORGANIZER:MAILTO:XXX@xx.com
ATTENDEE;CN=Manu Bhai;RSVP=TRUE:MAILTO:manu.bhai@xx.com
DTSTART;TZID=UTC+0:20220322T080000Z
DTEND;TZID=UTC+0:20220322T110000Z
LOCATION:>Room.045
TRANSP:OPAQUE
SEQUENCE:2230669611
UID:E00060977P00001158
SUMMARY:Issue with SEQUENCE.
X-ALT-DESC;FMTTYPE=text/html:<!DOCTYPE HTML>
 < html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body class="defaultFont"> Issue with SEQUENCE </body> </html>
PRIORITY:5
CLASS:PUBLIC
BEGIN:VALARM
TRIGGER:-PT15M
ACTION:DISPLAY
DESCRIPTION:Issue with SEQUENCE
END:VALARM
END:VEVENT
END:VCALENDAR
</code>```

答:
SEQUENCE is used to indicate a significant update.  Both of your versions look the same.  So in that sense the second one is an 'old' entry and not an update.

As far as max numbers go, the RFC5545 specification does not address that, it does state that it starts with 0 and incremented from there.  I expect the problem here is that there isn't actually a significant update, like a change in the date or time.

Your syntax also has numerous problems, it is not valid according to the specification.  (white space, linelengths, missing DTSTAMP, invalid DTSTART - mixing up form 2 and form 3 of date-time. https://www.rfc-editor.org/rfc/rfc5545#section-3.3.5etc).

Try running your ics through all the ics validators you can find, as they tend to pick up different things at different times.  Here are 2:
https://icalendar.org/validator.html
http://ical-validator.herokuapp.com/validate/ (currently bombing out early because of the whitespace in first line)

Title: SEQUENCE in Ical

Body:
I am creating two ics files programmatically with the same UID. One file has sequence number "2130669611". When I send a new ICS file with a new(greater sequence number 2230669611, I am getting the error that this is an old entry while the new sequence number is greater than the old one.
Is there a max value of the sequence number for outlook?

File 1

BEGIN:VCALENDAR
VERSION:2.0
PRODID:TTSTTS
METHOD:REQUEST
BEGIN:VEVENT
ORGANIZER:MAILTO:XXX@xx.com
ATTENDEE;CN=Manu Bhai;RSVP=TRUE:MAILTO:manu.bhai@xx.com
DTSTART;TZID=UTC+0:20220322T080000Z
DTEND;TZID=UTC+0:20220322T110000Z
LOCATION:>Room.045
TRANSP:OPAQUE
SEQUENCE:2130669611
UID:E00060977P00001158
SUMMARY:Issue with SEQUENCE.
X-ALT-DESC;FMTTYPE=text/html:<!DOCTYPE HTML>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">   Issue with SEQUENCE
PRIORITY:5
CLASS:PUBLIC
BEGIN:VALARM
TRIGGER:-PT15M
ACTION:DISPLAY
DESCRIPTION:Issue with SEQUENCE
END:VALARM
END:VEVENT
END:VCALENDAR

File 2

BEGIN:VCALENDAR
VERSION:2.0
PRODID:TTSTTS
METHOD:REQUEST
BEGIN:VEVENT
ORGANIZER:MAILTO:XXX@xx.com
ATTENDEE;CN=Manu Bhai;RSVP=TRUE:MAILTO:manu.bhai@xx.com
DTSTART;TZID=UTC+0:20220322T080000Z
DTEND;TZID=UTC+0:20220322T110000Z
LOCATION:>Room.045
TRANSP:OPAQUE
SEQUENCE:2230669611
UID:E00060977P00001158
SUMMARY:Issue with SEQUENCE.
X-ALT-DESC;FMTTYPE=text/html:<!DOCTYPE HTML>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">   Issue with SEQUENCE
PRIORITY:5
CLASS:PUBLIC
BEGIN:VALARM
TRIGGER:-PT15M
ACTION:DISPLAY
DESCRIPTION:Issue with SEQUENCE
END:VALARM
END:VEVENT
END:VCALENDAR


问:
First time plotting anything in R- unexpected results
all! New here. Much more comfortable with SQL but working on an R project. I created a point graph that didn't come out as expected. Here is the code that I entered And the result

I guess I was expecting a straight line through? I'm very new to this so bare with me.

I know this is a broad question but any tips/ resources to help me with data visualization using R? Thanks!

答: Try geom_smooth() rather than geom_line(). geom_line() will try to draw a line connecting all your individual datapoints, while geom_smooth() will fit a trend line to your data, which sounds like what you want. It uses loess by default, but if you literally want a straight line, you can have it fit a linear model instead with the argument geom_smooth(method = lm).


问:
Read Excel File Using Openpyxl
I want to save each Row of an excel file in a list using openpyxl.

```<code>wb = load_workbook('Shop.xlsx')
ws = wb.active

l = []

a_column = ws['A']
b_column = ws['B']

for x in range(len(a_column)):
    l.append([a_column[x].value, b_column[x].value])

print(l)
</code>```

Output: [[A1, B1], [A2, B2]]

It works but does anyone know a better way?

The list, for example, only works through the length of A.

答:
You could use itertools.zip_longest:

a_values = [cell.value for cell in a_column]
b_values = [cell.value for cell in b_column]

list(itertools.zip_longest(a_values, b_values))
#=> [('A1', 'B1'), ('A2', 'B2'), ('A3', 'B3'), (None, 'B4'), (None, 'B5')]
```

Title: Read Excel File Using Openpyxl

Body:
I want to save each Row of an excel file in a list using openpyxl.

wb = load_workbook('Shop.xlsx')
ws = wb.active

l = []

a_column = ws['A']
b_column = ws['B']

for x in range(len(a_column)):
    l.append([a_column[x].value, b_column[x].value])

print(l)

Output: [[A1, B1], [A2, B2]]

It works but does anyone know a better way?

The list, for example, only works through the length of A.


问:
Python multiprocessing - check status of each processes
I wonder if it is possible to check how long of each processes take.

for example, there are four workers and the job should take no more than 10 seconds, but one of worker take more than 10 seconds.Is there way to raise a alert after 10 seconds and before process finish the job.

My initial thought is using manager, but it seems I have wait till process finished.

Many thanks.

答:
Use Pipe and messages</p>
```<code>from multiprocessing import Process, Pipe
import numpy as np

caller, worker = Pipe()

val1 = ['der', 'die', 'das']

def worker_function(info):
    print (info.recv())
    for i in range(10):
        print (val1[np.random.choice(3, 1)[0]])

    info.send(['job finished'])
    info.close()

def request(data):

    caller.send(data)
    task = Process(target=worker_function, args=(worker,))

    if not task.is_alive():
        print ("task is requested")
        task.start()

    if caller.recv() == ['job finished']:
        task.join()
        print ("finished")

if __name__ == '__main__':
    data = {'input': 'here'}
    request(data)
</code>```

Body:
Use Pipe and messages

from multiprocessing import Process, Pipe
import numpy as np

caller, worker = Pipe()

val1 = ['der', 'die', 'das']

def worker_function(info):
    print (info.recv())
    for i in range(10):
        print (val1[np.random.choice(3, 1)[0]])

    info.send(['job finished'])
    info.close()

def request(data):

    caller.send(data)
    task = Process(target=worker_function, args=(worker,))

    if not task.is_alive():
        print ("task is requested")
        task.start()

    if caller.recv() == ['job finished']:
        task.join()
        print ("finished")

if __name__ == '__main__':
    data = {'input': 'here'}
    request(data)