问:
Getting full blame history all at once for a given file
I'm working on a program that analyzes git blame history over time, starting with the first commit of a given file all the way to HEAD, along a given branch.

Currently, the way I'm doing it is:

Use git log --pretty='%H %ad' --date=unix <branch> to get a list of every commit on the branch.

For each commit in that list, individually, use git blame --date=unix --minimal -l -e -w <commit> <filename> and parse the results.

The problem is that this takes a long time. Plus, I'm actually doing this for every file in a repo, over multiple repos. So worst case for a given repo I think it's something like O(number_of_files * number_of_commits). A lot of the time is taken up by spawning git processes. For a tiny repo with a few dozen files and a few hundred commits it takes almost 3 minutes (to run git about 16,000 times), and its already fully parallelized.

My question is, is there a way to get the complete blame history (e.g. if a line was changed multiple times in multiple commits) for every change to a given file (still one file at a time, though) in a single git command, so that I can reduce the amount of time this takes? I'd like to reduce it to O(number_of_files). This is my first optimization target, I just haven't been able to figure out if there's a way to do it yet.

I looked at the output from git blame --incremental but, unless I'm misreading (I didn't do a proper comparison so I might be wrong here), it still only gives the blames for the most recent changes, not every change at once.

Is it possible to do this and, if so, how?


来源: stackexchange

问:
How to send two successive related HTTP requests?
I could not find how to send successive related requests (like in order to verify an email)

Pseudo-code of what I am trying to achieve:

```<code>confirmEmail: async (req, res) => {
        const user = req.body;
        console.log(user);
        console.log(`User ${user.email} trying to verify email`);

        [1/ Generating token or code]
        [2/ Sending an email to verify user with token or code]

        return res.status(200).send("verification email sent");
    }
</code>```

I am thinking about implementing it the following way to take into account if this is the first or second request (or third etc):

```<code>confirmEmail: async (req, res) => {
        const user = req.body.user;
        console.log(user);
        console.log(`User ${user.email} trying to verify email`);

   if (req.body.step == 2) { // we add a json item "step"
      if req.body.verificationCode = [verificationCode in DB for user.email] {
         [set user as confirmed user]
         return res.status(204).send("You are now verified");
      }
      else
         return res.status(401).send("Wrong verification code");

   }
   else { // step 1

        [1/ Generating token or code and add it to a DB table]
        [2/ Sending an email to verify user with token or code]

        return res.status(200).send("verification email sent");
   }
}
</code>```

I don't think that this is optimal so I would like to make it work smoothly harnessing the power of node.js. Some kind of callback logic inside the function to avoid using a database (but callback don't take parameters?), able to handle a 3rd request and with the verification code to expire after 10 minutes and handle concurrent connections and users.

Many thanks in advance!

ContentLicense: CC BY-SA 4.0

Body:
I could not find how to send successive related requests (like in order to verify an email)

Pseudo-code of what I am trying to achieve:

confirmEmail: async (req, res) => {
        const user = req.body;
        console.log(user);
        console.log(`User ${user.email} trying to verify email`);

        [1/ Generating token or code]
        [2/ Sending an email to verify user with token or code]

        return res.status(200).send("verification email sent");
    }

I am thinking about implementing it the following way to take into account if this is the first or second request (or third etc):

confirmEmail: async (req, res) => {
        const user = req.body.user;
        console.log(user);
        console.log(`User ${user.email} trying to verify email`);

   if (req.body.step == 2) { // we add a json item "step"
      if req.body.verificationCode = [verificationCode in DB for user.email] {
         [set user as confirmed user]
         return res.status(204).send("You are now verified");
      }
      else
         return res.status(401).send("Wrong verification code");

   }
   else { // step 1

        [1/ Generating token or code and add it to a DB table]
        [2/ Sending an email to verify user with token or code]

        return res.status(200).send("verification email sent");
   }
}

I don't think that this is optimal so I would like to make it work smoothly harnessing the power of node.js. Some kind of callback logic inside the function to avoid using a database (but callback don't take parameters?), able to handle a 3rd request and with the verification code to expire after 10 minutes and handle concurrent connections and users.

Many thanks in advance!


问:
Python: How to upload folder to Google Drive
i want to upload a local folder to google drive with python

Folder example

```<code>1 folder level
C:\Users\test\Documents\google drvie\test\

the folder you want to upload
Folder name: upload
C:\Users\test\Documents\google drvie\test\upload

* In the upload folder
There is still a hierarchy of folders and files.
I want to upload all folders and files in upload.

C:\Users\test\Documents\google drvie\test\upload\upload2
C:\Users\test\Documents\google drvie\test\upload\test.txt
C:\Users\test\Documents\google drvie\test\upload\upload2\uplpad3
C:\Users\test\Documents\google drvie\test\upload\upload2\uplpad3\test.txt
</code>```

I did it with the script below, but I can't upload by folder.
Only files can be uploaded.

When uploading by folder, the following access permission error is displayed.
If anyone knows, I would appreciate it if you could tell me.

error contents
Traceback

```<code>GoogleDriveFile({'parents': [{'id': '1J8TXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'}], 'title': 'upload'})
Traceback (most recent call last):
  File "c:\Users\test\Documents\google drvie\googledrive_file_up.py", line 43, in <module>
    f.SetContentFile(os.path.join(path,x))
  File "C:\Users\test\AppData\Roaming\Python\Python39\site-packages\pydrive\files.py", line 169, in SetContentFile
    self.content = open(filename, 'rb')
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\test\\Documents\\google drvie\\test\\upload'
</code>```

Reference page
How to Upload File to Google Drive using Python Script?

code

```<code>from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth

import os

#Authenticate Google services
gauth = GoogleAuth()

# load credentials or create empty credentials if none exist
gauth.LoadCredentialsFile("mycreds.txt")

#If you don't have Google service credentials
if gauth.credentials is None:
     #Automatically receive authorization code from user and configure local web server
     gauth. LocalWebserverAuth()
# if the access token does not exist or has expired
elif gauth.access_token_expired:
     #refresh authorization for google services
     gauth. Refresh()
# if none match
else:
     #Authorize Google services
     gauth. Authorize()
# save credentials to file in txt format
gauth.SaveCredentialsFile("mycreds.txt")

#Authentication process for Google Drive
drive = GoogleDrive(gauth)

# specify folder path to upload
path = r'C:\Users\test\Documents\google drvie\test'
# File ID to upload to GOOGLE DRIVE
folder_id='1J8TXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
Loop processing (repeated processing) by #for statement
for x in os.listdir(path):
     # Create GoogleDriveFile object
     #f = drive.CreateFile({'title' : x})
     f = drive.CreateFile({"parents": [{"id": folder_id},]})
     #file title
     f['title'] = x
     # set local file and upload
     print(f)
     f.SetContentFile(os.path.join(path,x))
     print(f)
     #Upload to Google Drive
     f.Upload()
     print(f)

     f = None
</code>```

Sorry for the inconvenience, but thank you in advance.

Body:
i want to upload a local folder to google drive with python

Folder example

1 folder level
C:\Users\test\Documents\google drvie\test\

the folder you want to upload
Folder name: upload
C:\Users\test\Documents\google drvie\test\upload

* In the upload folder
There is still a hierarchy of folders and files.
I want to upload all folders and files in upload.

C:\Users\test\Documents\google drvie\test\upload\upload2
C:\Users\test\Documents\google drvie\test\upload\test.txt
C:\Users\test\Documents\google drvie\test\upload\upload2\uplpad3
C:\Users\test\Documents\google drvie\test\upload\upload2\uplpad3\test.txt

I did it with the script below, but I can't upload by folder.
Only files can be uploaded.

When uploading by folder, the following access permission error is displayed.
If anyone knows, I would appreciate it if you could tell me.

error contents
Traceback

GoogleDriveFile({'parents': [{'id': '1J8TXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'}], 'title': 'upload'})
Traceback (most recent call last):
  File "c:\Users\test\Documents\google drvie\googledrive_file_up.py", line 43, in <module>
    f.SetContentFile(os.path.join(path,x))
  File "C:\Users\test\AppData\Roaming\Python\Python39\site-packages\pydrive\files.py", line 169, in SetContentFile
    self.content = open(filename, 'rb')
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\test\\Documents\\google drvie\\test\\upload'

Reference page
How to Upload File to Google Drive using Python Script?

code

from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth

import os

#Authenticate Google services
gauth = GoogleAuth()

# load credentials or create empty credentials if none exist
gauth.LoadCredentialsFile("mycreds.txt")

#If you don't have Google service credentials
if gauth.credentials is None:
     #Automatically receive authorization code from user and configure local web server
     gauth. LocalWebserverAuth()
# if the access token does not exist or has expired
elif gauth.access_token_expired:
     #refresh authorization for google services
     gauth. Refresh()
# if none match
else:
     #Authorize Google services
     gauth. Authorize()
# save credentials to file in txt format
gauth.SaveCredentialsFile("mycreds.txt")

#Authentication process for Google Drive
drive = GoogleDrive(gauth)

# specify folder path to upload
path = r'C:\Users\test\Documents\google drvie\test'
# File ID to upload to GOOGLE DRIVE
folder_id='1J8TXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
Loop processing (repeated processing) by #for statement
for x in os.listdir(path):
     # Create GoogleDriveFile object
     #f = drive.CreateFile({'title' : x})
     f = drive.CreateFile({"parents": [{"id": folder_id},]})
     #file title
     f['title'] = x
     # set local file and upload
     print(f)
     f.SetContentFile(os.path.join(path,x))
     print(f)
     #Upload to Google Drive
     f.Upload()
     print(f)

     f = None

Sorry for the inconvenience, but thank you in advance.


问:
[node.js , firebase]Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined
I am a webcoding person. I was trying to use a firebase one day and suddenly I got an error like this and [MONGOOSE] DeprecationWarning: Mongoose: the strictQuery option will be switched back to false by default in Mongoose 7. Use mongoose.set('strictQuery', false); if you want to prepare for this change. Or use mongoose.set('strictQuery', true); to suppress this warning.
(Use node --trace-deprecation ... to show where the warning was created)  error

I'm coding using replit

image :
https://cdn.upload.systems/uploads/PpBS60RJ.png

I tried googling and watched YouTube videos, but there was no answer.


问:
Django forms.py phone number charfield only accept number/integer, I did it but the validation error not working, go to def validate(self)
my forms.py

```<code>from django import forms
from .models import Account

FRUIT_CHOICES= [
    ('Afghanistan', 'Afghanistan'),
    ('Albania', 'Albania'),
    ('Algeria', 'Algeria'),
    ('Andorra', 'Andorra'),
    ('Angola', 'Angola'),
    ('Antigua and Barbuda', 'Antigua and Barbuda'),
    ('Argentina', 'Argentina'),
    ('Armenia', 'Armenia'),
    ('Australia', 'Australia'),
    ('Austria', 'Austria'),
    ('Azerbaijan', 'Azerbaijan'),
    ('Bahamas', 'Bahamas'),
    ('Bahrain', 'Bahrain'),
    ('Bangladesh', 'Bangladesh'),
    ('Barbados', 'Barbados'),
    ('Malaysia', 'Malaysia'),
    ]

class RegistrationForm(forms.ModelForm):

    password=forms.CharField(widget=forms.PasswordInput())
    confirm_password=forms.CharField(widget=forms.PasswordInput())
    phone_number=forms.CharField(widget=forms.TextInput(attrs={
        'placeholder':'Enter Phone Number'
    }))
    country=forms.CharField(widget=forms.Select(choices=FRUIT_CHOICES))
    email=forms.EmailField(help_text="We'll never share your email with anyone else")
    class Meta:
        model=Account
        fields=['first_name','last_name','email','phone_number','password']

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)

        self.fields['first_name'].widget.attrs['placeholder']='Enter First Name'
        self.fields['last_name'].widget.attrs['placeholder']='Enter last Name'
        self.fields['email'].widget.attrs['placeholder']='Enter Email'
        self.fields['password'].widget.attrs['placeholder']='Enter Password'
        self.fields['confirm_password'].widget.attrs['placeholder']='Repeat Password'
        for abc in self.fields:
            self.fields[abc].widget.attrs['class']='form-control'

    def clean(self):
        cleanned_data=super().clean()
        password=cleanned_data.get('password')
        confirm_password=cleanned_data.get('confirm_password')
enter image description here
        if password != confirm_password:
            raise forms.ValidationError("Password and confirm password does not match")

    **def validate(self):
        cleanned_data=super().clean()
        phone_number=cleanned_data.get('phone_number')
        if phone_number.is_number() == False:
            raise forms.VallidationError("Please enter valid phone number, Example=012111111")**
</code>```

okay, regarding this function

```<code>def validate(self): #this is working, the charfield only accept integer
        cleanned_data=super().clean()
        phone_number=cleanned_data.get('phone_number')
        if phone_number.is_number() == False:
            raise forms.VallidationError("Please enter valid phone number, Example=012111111")
</code>```

Supposedly I shall get the error when the phone number contain alphabet "Please enter valid phone number, Example=012111111" , right?

But the output came out

phone_number
“gbfhbgf” value must be an integer.

May I know any solution to edit this error?

enter image description here

Body:
my forms.py

from django import forms
from .models import Account

FRUIT_CHOICES= [
    ('Afghanistan', 'Afghanistan'),
    ('Albania', 'Albania'),
    ('Algeria', 'Algeria'),
    ('Andorra', 'Andorra'),
    ('Angola', 'Angola'),
    ('Antigua and Barbuda', 'Antigua and Barbuda'),
    ('Argentina', 'Argentina'),
    ('Armenia', 'Armenia'),
    ('Australia', 'Australia'),
    ('Austria', 'Austria'),
    ('Azerbaijan', 'Azerbaijan'),
    ('Bahamas', 'Bahamas'),
    ('Bahrain', 'Bahrain'),
    ('Bangladesh', 'Bangladesh'),
    ('Barbados', 'Barbados'),
    ('Malaysia', 'Malaysia'),
    ]

class RegistrationForm(forms.ModelForm):

    password=forms.CharField(widget=forms.PasswordInput())
    confirm_password=forms.CharField(widget=forms.PasswordInput())
    phone_number=forms.CharField(widget=forms.TextInput(attrs={
        'placeholder':'Enter Phone Number'
    }))
    country=forms.CharField(widget=forms.Select(choices=FRUIT_CHOICES))
    email=forms.EmailField(help_text="We'll never share your email with anyone else")
    class Meta:
        model=Account
        fields=['first_name','last_name','email','phone_number','password']

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)

        self.fields['first_name'].widget.attrs['placeholder']='Enter First Name'
        self.fields['last_name'].widget.attrs['placeholder']='Enter last Name'
        self.fields['email'].widget.attrs['placeholder']='Enter Email'
        self.fields['password'].widget.attrs['placeholder']='Enter Password'
        self.fields['confirm_password'].widget.attrs['placeholder']='Repeat Password'
        for abc in self.fields:
            self.fields[abc].widget.attrs['class']='form-control'

    def clean(self):
        cleanned_data=super().clean()
        password=cleanned_data.get('password')
        confirm_password=cleanned_data.get('confirm_password')
enter image description here
        if password != confirm_password:
            raise forms.ValidationError("Password and confirm password does not match")

    **def validate(self):
        cleanned_data=super().clean()
        phone_number=cleanned_data.get('phone_number')
        if phone_number.is_number() == False:
            raise forms.VallidationError("Please enter valid phone number, Example=012111111")**

okay, regarding this function

def validate(self): #this is working, the charfield only accept integer
        cleanned_data=super().clean()
        phone_number=cleanned_data.get('phone_number')
        if phone_number.is_number() == False:
            raise forms.VallidationError("Please enter valid phone number, Example=012111111")

Supposedly I shall get the error when the phone number contain alphabet "Please enter valid phone number, Example=012111111" , right?

But the output came out

phone_number
“gbfhbgf” value must be an integer.

May I know any solution to edit this error?

enter image description here


问:
Unity C# IEnumerator isn't changing Sprite Renderer properties
So I'm making a project where I need an Object to mimic the properties of a set of other Objects with a certain time in between.

For that I used the following IEnumerator:

```<code>public IEnumerator GoBack(GameObject[] go)
{
    for (int i = go.Length-1; i >= 0; i--)
    {
        if (go[i] != null)
        {
            GameObject g = go[i];
            transform.position = g.transform.position;
            sprRenderer.flipX = g.GetComponent<SpriteRenderer>().flipX;
            sprRenderer.sprite = g.GetComponent<SpriteRenderer>().sprite;

            Destroy(go[i]);
            yield return new WaitForSecondsRealtime(rollBack);
        }
    }

    GetComponent<Animator>().Play("EndTurnBack");
}
</code>```

This basically alters my Object to be equal to the position, sprite and flipX of the object it is mimicking.
The problem is that only the position appears to work and I have no clue as to why

I tried printing in the console what was the sprite and flipX of my Object for each iteration and it is exactly what I want but the results don't appear on the screen.

Body:
So I'm making a project where I need an Object to mimic the properties of a set of other Objects with a certain time in between.

For that I used the following IEnumerator:

public IEnumerator GoBack(GameObject[] go)
{
    for (int i = go.Length-1; i >= 0; i--)
    {
        if (go[i] != null)
        {
            GameObject g = go[i];
            transform.position = g.transform.position;
            sprRenderer.flipX = g.GetComponent<SpriteRenderer>().flipX;
            sprRenderer.sprite = g.GetComponent<SpriteRenderer>().sprite;

            Destroy(go[i]);
            yield return new WaitForSecondsRealtime(rollBack);
        }
    }

    GetComponent<Animator>().Play("EndTurnBack");
}

This basically alters my Object to be equal to the position, sprite and flipX of the object it is mimicking.
The problem is that only the position appears to work and I have no clue as to why

I tried printing in the console what was the sprite and flipX of my Object for each iteration and it is exactly what I want but the results don't appear on the screen.


问:
Why is my program skipping right over my cin, and going directly to default in a switch?
I have been trying to fix this issue for quite a while, and I have no clue where I am going wrong. I am not receiving any syntax errors, but I am not sure if I am making a basic mistake.

```<code>#include <iostream>
#include <cmath>
#include <string>
#include <unistd.h>
using namespace std;
/* Starting code below! */

int main() {

    char name;

    int damage;
    int health;
    int agility;

    cout<<"\u2694 Welcome to open world RPG \u2694 \n \n";

    cout<<"Welcome traveller! What is your name? \n \n";
    cin>>name;
    sleep(1);

    cout<<"==========Character Custimization========== \n \n";
    cout<<"1) Golem, 2) Adventurer, 3) Knight, 4) Hare-Morph \n \n";

    int profile;
    cin>>profile;

        switch (profile) {
            case '1':
                cout<<"You have chosen Golem!" << endl;
                break;
            case '2':
                cout<<"You have chosen Adventurer!" << endl;
                break;
            case '3':
                cout<<"You have chosen Knight" << endl;
                break;
            case '4':
                cout<<"You have chosen Hare-Morph!" << endl;
                break;
            case '5':
                cout<<"DEBUG PLAYER" << endl;
                break;
            default:
                cout<<"FAILED INPUT";
                break;
        }

    exit(0);

}

</code>```

I am expecting a user input question, with my program following with an answer from the switch.

Body:
I have been trying to fix this issue for quite a while, and I have no clue where I am going wrong. I am not receiving any syntax errors, but I am not sure if I am making a basic mistake.

#include <iostream>
#include <cmath>
#include <string>
#include <unistd.h>
using namespace std;
/* Starting code below! */

int main() {

    char name;

    int damage;
    int health;
    int agility;

    cout<<"\u2694 Welcome to open world RPG \u2694 \n \n";

    cout<<"Welcome traveller! What is your name? \n \n";
    cin>>name;
    sleep(1);

    cout<<"==========Character Custimization========== \n \n";
    cout<<"1) Golem, 2) Adventurer, 3) Knight, 4) Hare-Morph \n \n";

    int profile;
    cin>>profile;

        switch (profile) {
            case '1':
                cout<<"You have chosen Golem!" << endl;
                break;
            case '2':
                cout<<"You have chosen Adventurer!" << endl;
                break;
            case '3':
                cout<<"You have chosen Knight" << endl;
                break;
            case '4':
                cout<<"You have chosen Hare-Morph!" << endl;
                break;
            case '5':
                cout<<"DEBUG PLAYER" << endl;
                break;
            default:
                cout<<"FAILED INPUT";
                break;
        }

    exit(0);

}

I am expecting a user input question, with my program following with an answer from the switch.


问:
Show more table rows with angular
I am working with Syncfusion grids and I created two components, each displaying a table with 2 rows initially. I created a show more button that should add two extra rows every time it is clicked. The button in component-one works as expected, but the button in component-two is not displaying the extra two rows when clicked. I am not seeing any errors in the console and really cannot figure out why it's not working....If I remove component-one then the button in component-two starts working as expected. Both components have the same functionality so I don't understand why the show more button in component-two is not working.

component-one.component.html

```<code><ejs-grid [dataSource]="data.slice(0, items)">
  <e-columns>
    <e-column
      field="OrderID"
      headerText="Order ID"
      textAlign="Right"
      width="90"
    ></e-column>
    <e-column
      field="CustomerID"
      headerText="Customer ID"
      width="120"
    ></e-column>
    <e-column
      field="Freight"
      headerText="Freight"
      textAlign="Right"
      format="C2"
      width="90"
    ></e-column>
    <e-column
      field="OrderDate"
      headerText="Order Date"
      textAlign="Right"
      format="yMd"
      width="120"
    ></e-column>
  </e-columns>
</ejs-grid>
<button (click)="showMore()">show more</button>
</code>```

component-one.component.ts

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-component-one',
  templateUrl: './component-one.component.html',
  styleUrls: ['./component-one.component.scss'],
})
export class ComponentOneComponent implements OnInit {
  constructor() {}

  ngOnInit(): void {}

  data: object[] = [
    {
      OrderID: 10258,
      CustomerID: 'ERNSH',
      EmployeeID: 1,
      OrderDate: new Date(8375418e5),
      ShipName: 'Ernst Handel',
      ShipCity: 'Graz',
      ShipAddress: 'Kirchgasse 6',
      ShipRegion: 'CJ',
      ShipPostalCode: '8010',
      ShipCountry: 'Austria',
      Freight: 140.51,
      Verified: !0,
    },
    {
      OrderID: 10259,
      CustomerID: 'CENTC',
      EmployeeID: 4,
      OrderDate: new Date(8376282e5),
      ShipName: 'Centro comercial Moctezuma',
      ShipCity: 'México D.F.',
      ShipAddress: 'Sierras de Granada 9993',
      ShipRegion: 'CJ',
      ShipPostalCode: '05022',
      ShipCountry: 'Mexico',
      Freight: 3.25,
      Verified: !1,
    },
    {
      OrderID: 10260,
      CustomerID: 'OTTIK',
      EmployeeID: 4,
      OrderDate: new Date(8377146e5),
      ShipName: 'Ottilies Käseladen',
      ShipCity: 'Köln',
      ShipAddress: 'Mehrheimerstr. 369',
      ShipRegion: 'CJ',
      ShipPostalCode: '50739',
      ShipCountry: 'Germany',
      Freight: 55.09,
      Verified: !0,
    },
    {
      OrderID: 10261,
      CustomerID: 'QUEDE',
      EmployeeID: 4,
      OrderDate: new Date(8377146e5),
      ShipName: 'Que Delícia',
      ShipCity: 'Rio de Janeiro',
      ShipAddress: 'Rua da Panificadora, 12',
      ShipRegion: 'RJ',
      ShipPostalCode: '02389-673',
      ShipCountry: 'Brazil',
      Freight: 3.05,
      Verified: !1,
    },
    {
      OrderID: 10262,
      CustomerID: 'RATTC',
      EmployeeID: 8,
      OrderDate: new Date(8379738e5),
      ShipName: 'Rattlesnake Canyon Grocery',
      ShipCity: 'Albuquerque',
      ShipAddress: '2817 Milton Dr.',
      ShipRegion: 'NM',
      ShipPostalCode: '87110',
      ShipCountry: 'USA',
      Freight: 48.29,
      Verified: !0,
    },
  ];

  items: number = 2;
  showMore() {
    this.items += 2;
  }
}
</code>```

component-two.component.html

```<code><ejs-grid [dataSource]="data.slice(0, items)">
  <e-columns>
    <e-column
      field="OrderID"
      headerText="Order ID"
      textAlign="Right"
      width="90"
    ></e-column>
    <e-column
      field="CustomerID"
      headerText="Customer ID"
      width="120"
    ></e-column>
    <e-column
      field="Freight"
      headerText="Freight"
      textAlign="Right"
      format="C2"
      width="90"
    ></e-column>
    <e-column
      field="OrderDate"
      headerText="Order Date"
      textAlign="Right"
      format="yMd"
      width="120"
    ></e-column>
  </e-columns>
</ejs-grid>
<button (click)="showMore()">show more</button>
</code>```

component-two.component.ts

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-component-two',
  templateUrl: './component-two.component.html',
  styleUrls: ['./component-two.component.scss'],
})
export class ComponentTwoComponent implements OnInit {
  constructor() {}

  ngOnInit(): void {}
  data: object[] = [
    {
      OrderID: 10258,
      CustomerID: 'ERNSH',
      EmployeeID: 1,
      OrderDate: new Date(8375418e5),
      ShipName: 'Ernst Handel',
      ShipCity: 'Graz',
      ShipAddress: 'Kirchgasse 6',
      ShipRegion: 'CJ',
      ShipPostalCode: '8010',
      ShipCountry: 'Austria',
      Freight: 140.51,
      Verified: !0,
    },
    {
      OrderID: 10259,
      CustomerID: 'CENTC',
      EmployeeID: 4,
      OrderDate: new Date(8376282e5),
      ShipName: 'Centro comercial Moctezuma',
      ShipCity: 'México D.F.',
      ShipAddress: 'Sierras de Granada 9993',
      ShipRegion: 'CJ',
      ShipPostalCode: '05022',
      ShipCountry: 'Mexico',
      Freight: 3.25,
      Verified: !1,
    },
    {
      OrderID: 10260,
      CustomerID: 'OTTIK',
      EmployeeID: 4,
      OrderDate: new Date(8377146e5),
      ShipName: 'Ottilies Käseladen',
      ShipCity: 'Köln',
      ShipAddress: 'Mehrheimerstr. 369',
      ShipRegion: 'CJ',
      ShipPostalCode: '50739',
      ShipCountry: 'Germany',
      Freight: 55.09,
      Verified: !0,
    },
    {
      OrderID: 10261,
      CustomerID: 'QUEDE',
      EmployeeID: 4,
      OrderDate: new Date(8377146e5),
      ShipName: 'Que Delícia',
      ShipCity: 'Rio de Janeiro',
      ShipAddress: 'Rua da Panificadora, 12',
      ShipRegion: 'RJ',
      ShipPostalCode: '02389-673',
      ShipCountry: 'Brazil',
      Freight: 3.05,
      Verified: !1,
    },
    {
      OrderID: 10262,
      CustomerID: 'RATTC',
      EmployeeID: 8,
      OrderDate: new Date(8379738e5),
      ShipName: 'Rattlesnake Canyon Grocery',
      ShipCity: 'Albuquerque',
      ShipAddress: '2817 Milton Dr.',
      ShipRegion: 'NM',
      ShipPostalCode: '87110',
      ShipCountry: 'USA',
      Freight: 48.29,
      Verified: !0,
    },
  ];

  items: number = 2;
  showMore() {
    this.items += 2;
  }
}
</code>```

Title: Show more table rows with angular

Body:
I am working with Syncfusion grids and I created two components, each displaying a table with 2 rows initially. I created a show more button that should add two extra rows every time it is clicked. The button in component-one works as expected, but the button in component-two is not displaying the extra two rows when clicked. I am not seeing any errors in the console and really cannot figure out why it's not working....If I remove component-one then the button in component-two starts working as expected. Both components have the same functionality so I don't understand why the show more button in component-two is not working.

component-one.component.html

<ejs-grid [dataSource]="data.slice(0, items)">
  <e-columns>
    <e-column
      field="OrderID"
      headerText="Order ID"
      textAlign="Right"
      width="90"
    ></e-column>
    <e-column
      field="CustomerID"
      headerText="Customer ID"
      width="120"
    ></e-column>
    <e-column
      field="Freight"
      headerText="Freight"
      textAlign="Right"
      format="C2"
      width="90"
    ></e-column>
    <e-column
      field="OrderDate"
      headerText="Order Date"
      textAlign="Right"
      format="yMd"
      width="120"
    ></e-column>
  </e-columns>
</ejs-grid>
<button (click)="showMore()">show more</button>

component-one.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-component-one',
  templateUrl: './component-one.component.html',
  styleUrls: ['./component-one.component.scss'],
})
export class ComponentOneComponent implements OnInit {
  constructor() {}

  ngOnInit(): void {}

  data: object[] = [
    {
      OrderID: 10258,
      CustomerID: 'ERNSH',
      EmployeeID: 1,
      OrderDate: new Date(8375418e5),
      ShipName: 'Ernst Handel',
      ShipCity: 'Graz',
      ShipAddress: 'Kirchgasse 6',
      ShipRegion: 'CJ',
      ShipPostalCode: '8010',
      ShipCountry: 'Austria',
      Freight: 140.51,
      Verified: !0,
    },
    {
      OrderID: 10259,
      CustomerID: 'CENTC',
      EmployeeID: 4,
      OrderDate: new Date(8376282e5),
      ShipName: 'Centro comercial Moctezuma',
      ShipCity: 'México D.F.',
      ShipAddress: 'Sierras de Granada 9993',
      ShipRegion: 'CJ',
      ShipPostalCode: '05022',
      ShipCountry: 'Mexico',
      Freight: 3.25,
      Verified: !1,
    },
    {
      OrderID: 10260,
      CustomerID: 'OTTIK',
      EmployeeID: 4,
      OrderDate: new Date(8377146e5),
      ShipName: 'Ottilies Käseladen',
      ShipCity: 'Köln',
      ShipAddress: 'Mehrheimerstr. 369',
      ShipRegion: 'CJ',
      ShipPostalCode: '50739',
      ShipCountry: 'Germany',
      Freight: 55.09,
      Verified: !0,
    },
    {
      OrderID: 10261,
      CustomerID: 'QUEDE',
      EmployeeID: 4,
      OrderDate: new Date(8377146e5),
      ShipName: 'Que Delícia',
      ShipCity: 'Rio de Janeiro',
      ShipAddress: 'Rua da Panificadora, 12',
      ShipRegion: 'RJ',
      ShipPostalCode: '02389-673',
      ShipCountry: 'Brazil',
      Freight: 3.05,
      Verified: !1,
    },
    {
      OrderID: 10262,
      CustomerID: 'RATTC',
      EmployeeID: 8,
      OrderDate: new Date(8379738e5),
      ShipName: 'Rattlesnake Canyon Grocery',
      ShipCity: 'Albuquerque',
      ShipAddress: '2817 Milton Dr.',
      ShipRegion: 'NM',
      ShipPostalCode: '87110',
      ShipCountry: 'USA',
      Freight: 48.29,
      Verified: !0,
    },
  ];

  items: number = 2;
  showMore() {
    this.items += 2;
  }
}

component-two.component.html

<ejs-grid [dataSource]="data.slice(0, items)">
  <e-columns>
    <e-column
      field="OrderID"
      headerText="Order ID"
      textAlign="Right"
      width="90"
    ></e-column>
    <e-column
      field="CustomerID"
      headerText="Customer ID"
      width="120"
    ></e-column>
    <e-column
      field="Freight"
      headerText="Freight"
      textAlign="Right"
      format="C2"
      width="90"
    ></e-column>
    <e-column
      field="OrderDate"
      headerText="Order Date"
      textAlign="Right"
      format="yMd"
      width="120"
    ></e-column>
  </e-columns>
</ejs-grid>
<button (click)="showMore()">show more</button>

component-two.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-component-two',
  templateUrl: './component-two.component.html',
  styleUrls: ['./component-two.component.scss'],
})
export class ComponentTwoComponent implements OnInit {
  constructor() {}

  ngOnInit(): void {}
  data: object[] = [
    {
      OrderID: 10258,
      CustomerID: 'ERNSH',
      EmployeeID: 1,
      OrderDate: new Date(8375418e5),
      ShipName: 'Ernst Handel',
      ShipCity: 'Graz',
      ShipAddress: 'Kirchgasse 6',
      ShipRegion: 'CJ',
      ShipPostalCode: '8010',
      ShipCountry: 'Austria',
      Freight: 140.51,
      Verified: !0,
    },
    {
      OrderID: 10259,
      CustomerID: 'CENTC',
      EmployeeID: 4,
      OrderDate: new Date(8376282e5),
      ShipName: 'Centro comercial Moctezuma',
      ShipCity: 'México D.F.',
      ShipAddress: 'Sierras de Granada 9993',
      ShipRegion: 'CJ',
      ShipPostalCode: '05022',
      ShipCountry: 'Mexico',
      Freight: 3.25,
      Verified: !1,
    },
    {
      OrderID: 10260,
      CustomerID: 'OTTIK',
      EmployeeID: 4,
      OrderDate: new Date(8377146e5),
      ShipName: 'Ottilies Käseladen',
      ShipCity: 'Köln',
      ShipAddress: 'Mehrheimerstr. 369',
      ShipRegion: 'CJ',
      ShipPostalCode: '50739',
      ShipCountry: 'Germany',
      Freight: 55.09,
      Verified: !0,
    },
    {
      OrderID: 10261,
      CustomerID: 'QUEDE',
      EmployeeID: 4,
      OrderDate: new Date(8377146e5),
      ShipName: 'Que Delícia',
      ShipCity: 'Rio de Janeiro',
      ShipAddress: 'Rua da Panificadora, 12',
      ShipRegion: 'RJ',
      ShipPostalCode: '02389-673',
      ShipCountry: 'Brazil',
      Freight: 3.05,
      Verified: !1,
    },
    {
      OrderID: 10262,
      CustomerID: 'RATTC',
      EmployeeID: 8,
      OrderDate: new Date(8379738e5),
      ShipName: 'Rattlesnake Canyon Grocery',
      ShipCity: 'Albuquerque',
      ShipAddress: '2817 Milton Dr.',
      ShipRegion: 'NM',
      ShipPostalCode: '87110',
      ShipCountry: 'USA',
      Freight: 48.29,
      Verified: !0,
    },
  ];

  items: number = 2;
  showMore() {
    this.items += 2;
  }
}


问:
WPF Ribbon Multiple Comboboxes in same Group
I have multiple RibbonComboBoxes in one RibbonGroup and I keep having anything but the very first RibbonComboBox not return null on me.  It doesn't seem to be finding any other ComboBoxes in the group for some reason.

I have a Ribbon Group, then a separate RibbonComboBox for each combo box I need.  These also live inside of a grid.  Any ideas?

ContentLicense: CC BY-SA 3.0


问:
Outliers in Data mining
I am learning the algorithm about outliers, could you help me answer these questions? I feel confused.
Thank you!

Title: Outliers in Data mining


问:
Join operation in an ImageCollection
I carried out join operation to help in smoothing out my images in a Landsat ImageCollection by getting at least 3 Images in a specified time window, obtain the median and then adding those images to the ImageCollection. I expected to obtain an ImageCollection that I could still carry out some filter functions to create a time series with the median images, but it didn't work.

```<code>// 1. selecting the time window
var days = 32;
var milli = ee.Number(days).multiply(1000*24*60*60)
console.log(milli)

var join = ee.Join.saveAll({
  matchesKey:"images"
})

// 2. Apply the filter
var dif_filter = ee.Filter.maxDifference({
  difference:milli,
  leftField:"system:time_start",
  rightField:"system:time_start"
})

// 3. Apply the join
var joined_collection = join.apply({
  primary: original_collection,
  secondary:original_collection,
  condition:dif_filter
})

// Adding the median images to our collection
function medianCalculator(image){
  var imageGetter = ee.ImageCollection.fromImages(image.get("images"))
  var medianImage = imageGetter.reduce(ee.Reducer.median())
  return ee.Image(image).addBands(medianImage).select("NDVI_median", "EVI_median", "NDVI", "EVI")
}

// collection with smoothed Images
var collection_2 = joined_collection.map(medianCalculator)
print(collection_2)
</code>```

I wanted to carry out some filters on "collection_2" but there was an error, "Line 110: collection_2.filter(...).median is not a function". What am I missing.
I suspect that after performing the Join, the ImageCollection got turned into a FeatureCollection so I tried looking for ways of converting a FeatureCollection to an ImageCollection...to no avail.

Title: Join operation in an ImageCollection

Body:
I carried out join operation to help in smoothing out my images in a Landsat ImageCollection by getting at least 3 Images in a specified time window, obtain the median and then adding those images to the ImageCollection. I expected to obtain an ImageCollection that I could still carry out some filter functions to create a time series with the median images, but it didn't work.

// 1. selecting the time window
var days = 32;
var milli = ee.Number(days).multiply(1000*24*60*60)
console.log(milli)

var join = ee.Join.saveAll({
  matchesKey:"images"
})

// 2. Apply the filter
var dif_filter = ee.Filter.maxDifference({
  difference:milli,
  leftField:"system:time_start",
  rightField:"system:time_start"
})

// 3. Apply the join
var joined_collection = join.apply({
  primary: original_collection,
  secondary:original_collection,
  condition:dif_filter
})

// Adding the median images to our collection
function medianCalculator(image){
  var imageGetter = ee.ImageCollection.fromImages(image.get("images"))
  var medianImage = imageGetter.reduce(ee.Reducer.median())
  return ee.Image(image).addBands(medianImage).select("NDVI_median", "EVI_median", "NDVI", "EVI")
}

// collection with smoothed Images
var collection_2 = joined_collection.map(medianCalculator)
print(collection_2)

I wanted to carry out some filters on "collection_2" but there was an error, "Line 110: collection_2.filter(...).median is not a function". What am I missing.
I suspect that after performing the Join, the ImageCollection got turned into a FeatureCollection so I tried looking for ways of converting a FeatureCollection to an ImageCollection...to no avail.


问:
vs code marks all files as updated after build (after eslint is introduced into project)
We recently introduced eslint to help with code standard. But after running build command, all files are marked as updated in vs code even though there is no actual change in them.

Build cmd include following cmd:

"build": "yarn prettier --write ./ && yarn eslint --fix ./ && reactview-build --enableDataFetcher --outputDirectory ../../Output/Content/Scripts/ReactViews/",

This behavior only appears after the introduction of eslint. Not sure if this is eslint issue or vs code issue. Anything we can do to avoid this? I would appreciate some help here. Thank!


问:
How to use an image url to upload a copy of that image to AWS S3?
In my React frontend I have an external image url eg https://pixabay.com/image.jpg.

How can I upload the actual image (not the image url) to AWS S3?

Something like this I got from here:

```<code>import S3 from 'aws-sdk/clients/s3';
import stream from 'stream'
import axios from 'axios';

export default async (url, filename, callback) => {
  const s3 = new S3({
    region: process.env.BUCKET_REGION,
    accessKeyId: process.env.AWS_IAM_ACCESS_KEY,
    secretAccessKey: process.env.AWS_IAM_SECRET_KEY,
    signatureVersion: 'v4',
  });

  const uploadStream = () => {
    const pass = new stream.PassThrough();
    promise = s3.upload({
      Key: filename,
      Body: pass,
      ACL: 'public-read',
      ContentType: 'application/octet-stream',
    }).promise();
    return pass;
  }

  const imageRequest = axios({
    method: 'get',
    url: url,
    responseType: 'stream'
  }).then( (response) => {
    console.log('STREAM.then', response)
    if(response.status===200){
      contentType = response.headers['content-type'];
      response.data.pipe(uploadStream());
    }
  });

  return promise
}
</code>```

Body:
In my React frontend I have an external image url eg https://pixabay.com/image.jpg.

How can I upload the actual image (not the image url) to AWS S3?

Something like this I got from here:

import S3 from 'aws-sdk/clients/s3';
import stream from 'stream'
import axios from 'axios';

export default async (url, filename, callback) => {
  const s3 = new S3({
    region: process.env.BUCKET_REGION,
    accessKeyId: process.env.AWS_IAM_ACCESS_KEY,
    secretAccessKey: process.env.AWS_IAM_SECRET_KEY,
    signatureVersion: 'v4',
  });

  const uploadStream = () => {
    const pass = new stream.PassThrough();
    promise = s3.upload({
      Key: filename,
      Body: pass,
      ACL: 'public-read',
      ContentType: 'application/octet-stream',
    }).promise();
    return pass;
  }

  const imageRequest = axios({
    method: 'get',
    url: url,
    responseType: 'stream'
  }).then( (response) => {
    console.log('STREAM.then', response)
    if(response.status===200){
      contentType = response.headers['content-type'];
      response.data.pipe(uploadStream());
    }
  });

  return promise
}


问:
How to input a stream that will ignore numbers and treat all symbols as delimiters
I have a binary tree that takes in a stream of words and adds them each to a new node of the binary tree, skipping duplicates.

I tried implementing an input method like so:

```<code>void WordTree::input(std::istream& in) {
   std::string str;

   while (in >> str) {
      // convert to lowercase
      std::transform(str.begin(), str.end(), str.begin(), ::tolower);
      str.erase(std::remove_if(str.begin(), str.end(), ::isdigit), str.end());
      str.erase(std::remove_if(str.begin(), str.end(), ::ispunct), str.end());
      // add to tree
      if (str != " ")
         add(str);
   }
}
</code>```

But for a given test input like std::string str_input = " 100 2/3 alakazam qwerty up-time level up up up up bastion how are you 23 ALAKAZAM"

I'm getting the  results as:

```<code> occurrences: 3
alakazam occurrences: 2
are occurrences: 1
bastion occurrences: 1
how occurrences: 1
level occurrences: 1
qwerty occurrences: 1
up occurrences: 4
uptime occurrences: 1
you occurrences: 1

Unique word count: 10
</code>```

It appears to be counting spaces as inputs? Even though I have a conditional to ignore any spaces. I also have the problem that I need an input of "up-time" to be two words like such that "up" and "time" are their own words.

I tried implementing the method with characters instead for more control, but it so far just mushes the whole string together.

```<code>void WordTree::input(std::istream& in) {

   char c;
   std::string str;

   while (in >> c) {
      if (std::isalpha(c)) {
         str = str + c;
      }
      else if (str != "") {
         std::transform(str.begin(), str.end(), str.begin(), ::tolower);
         add(str);
         str = "";
      }
   }
}
</code>```

The output from my display method (which just traverses the tree returns the word in the node) looks like:

```<code>alakazamqwertyup occurrences: 1
timelevelupupupupbastionhowareyou occurrences: 1
</code>```

Body:
I have a binary tree that takes in a stream of words and adds them each to a new node of the binary tree, skipping duplicates.

I tried implementing an input method like so:

void WordTree::input(std::istream& in) {
   std::string str;

   while (in >> str) {
      // convert to lowercase
      std::transform(str.begin(), str.end(), str.begin(), ::tolower);
      str.erase(std::remove_if(str.begin(), str.end(), ::isdigit), str.end());
      str.erase(std::remove_if(str.begin(), str.end(), ::ispunct), str.end());
      // add to tree
      if (str != " ")
         add(str);
   }
}

But for a given test input like std::string str_input = " 100 2/3 alakazam qwerty up-time level up up up up bastion how are you 23 ALAKAZAM"

I'm getting the  results as:

 occurrences: 3
alakazam occurrences: 2
are occurrences: 1
bastion occurrences: 1
how occurrences: 1
level occurrences: 1
qwerty occurrences: 1
up occurrences: 4
uptime occurrences: 1
you occurrences: 1

Unique word count: 10

It appears to be counting spaces as inputs? Even though I have a conditional to ignore any spaces. I also have the problem that I need an input of "up-time" to be two words like such that "up" and "time" are their own words.

I tried implementing the method with characters instead for more control, but it so far just mushes the whole string together.

void WordTree::input(std::istream& in) {

   char c;
   std::string str;

   while (in >> c) {
      if (std::isalpha(c)) {
         str = str + c;
      }
      else if (str != "") {
         std::transform(str.begin(), str.end(), str.begin(), ::tolower);
         add(str);
         str = "";
      }
   }
}

The output from my display method (which just traverses the tree returns the word in the node) looks like:

alakazamqwertyup occurrences: 1
timelevelupupupupbastionhowareyou occurrences: 1


问:
python script cannot run with not root user
i have script with python3.
i run it with root user. it can run normal as below:

```<code>[root@seagull project]# ./test_call.py roam_block
{'Event-Timestamp': 1670570784, 'CC-Request-Number': 2, 'CC-Request-Type': 3, 'Auth-Application-Id': 4, 'Origin-Realm': 'tocs.net', 'Origin-Host': 'HNOCS11', 'Result-Code': 2001, 'Session-Id': 'ProtocolSimulator:84896190808:1a17c618-0ffb-4da2-8dbf-23ec217f2995'}
[root@seagull project]# pwd
/home/seagul/project
</code>```

but when i run with other user ( not root user). it run failed.

```<code>[seagul@seagull project]$ ./test_call.py roam_block
Traceback (most recent call last):
  File "./test_call.py", line 352, in <module>
    make_call()
  File "./test_call.py", line 153, in make_call
    raw = cnx.cap_exchange_req()
  File "/home/seagul/project/data_gy_call.py", line 46, in cap_exchange_req
    self.set_diameter_diction_using_wireshark_dictionary()
  File "/home/seagul/project/data_gy_call.py", line 387, in set_diameter_diction_using_wireshark_dictionary
    self._diam_dct = Dictionary(parse_xml(_xml))
  File "/home/seagul/project/diameter.py", line 193, in parse_xml
    root = ET.fromstring(''.join(xmllist))
  File "/usr/lib64/python3.6/xml/etree/ElementTree.py", line 1315, in XML
    return parser.close()
xml.etree.ElementTree.ParseError: no element found: line 1, column 0
[seagul@seagull project]$ pwd
/home/seagul/project
</code>```

Body:
i have script with python3.
i run it with root user. it can run normal as below:

[root@seagull project]# ./test_call.py roam_block
{'Event-Timestamp': 1670570784, 'CC-Request-Number': 2, 'CC-Request-Type': 3, 'Auth-Application-Id': 4, 'Origin-Realm': 'tocs.net', 'Origin-Host': 'HNOCS11', 'Result-Code': 2001, 'Session-Id': 'ProtocolSimulator:84896190808:1a17c618-0ffb-4da2-8dbf-23ec217f2995'}
[root@seagull project]# pwd
/home/seagul/project

but when i run with other user ( not root user). it run failed.

[seagul@seagull project]$ ./test_call.py roam_block
Traceback (most recent call last):
  File "./test_call.py", line 352, in <module>
    make_call()
  File "./test_call.py", line 153, in make_call
    raw = cnx.cap_exchange_req()
  File "/home/seagul/project/data_gy_call.py", line 46, in cap_exchange_req
    self.set_diameter_diction_using_wireshark_dictionary()
  File "/home/seagul/project/data_gy_call.py", line 387, in set_diameter_diction_using_wireshark_dictionary
    self._diam_dct = Dictionary(parse_xml(_xml))
  File "/home/seagul/project/diameter.py", line 193, in parse_xml
    root = ET.fromstring(''.join(xmllist))
  File "/usr/lib64/python3.6/xml/etree/ElementTree.py", line 1315, in XML
    return parser.close()
xml.etree.ElementTree.ParseError: no element found: line 1, column 0
[seagul@seagull project]$ pwd
/home/seagul/project


问:
Local Storage with jQuery button Zoom
I want Local Storage , I selected but now I want to add local Storage to it so it remembers when I leave the page

I made now this code but it doesn't seem to work properly, could someone please help me ?

Local with button Zoom In , Zoom Out

```<code>HTML Button Zoom
</code>```
```<code><div class="me-4">
                <button id="zoom-out" class="btn btn-zoom" data-value="zoom-out"><i class="fas fa-search-minus"></i></button>
                <button id="zoom-in" class="btn btn-zoom" data-value="zoom-in"><i class="fas fa-search-plus"></i></button>
            </div>
</code>```
```<code>HTML Content
</code>```
```<code><section id="content" class="card card-body mt-2">
            <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Delectus maiores mollitia consequuntur? Cum
                commodi debitis et. Voluptates et provident, cum voluptate voluptatum alias, delectus asperiores atque
                magni, fugit eveniet laborum!</p>
            <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Porro blanditiis velit modi maxime quam, labore recusandae repellat tenetur unde in harum asperiores qui corporis vero ullam provident quisquam at voluptas laudantium expedita placeat ad? Corporis quod amet harum maiores omnis!</p>
            <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Consequatur sequi velit laboriosam maxime
                nostrum necessitatibus aliquam iste reprehenderit numquam! Aliquid minus magni corporis magnam
                consequuntur minima sint beatae, sit voluptatum?</p>
            <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Reiciendis modi placeat incidunt at voluptatibus, quibusdam, perspiciatis eligendi obcaecati perferendis maiores animi, eum vel aspernatur doloremque fugit et quasi soluta beatae dolorum rem ducimus saepe! Ipsam adipisci modi quo, dignissimos facere accusamus omnis enim eaque sint perspiciatis quos vel tempore doloribus.</p>
        </section>
</code>```
```<code>JS
</code>```
```<code>$(document).ready(function(){
   var getContent = $("#content");

    /* =============================== Local Storage =================================*/
    const savedZoom = localStorage.getItem('Zoom');

    if(savedZoom){
        $(getContent).css("fontSize", savedZoom);
    }

    /* =============================== BUTTON ZOOM =================================*/
    $(".btn-zoom").click(function(){
        var btnZoom = $(this).attr('data-value');
        console.log(btnZoom);

        $(".btn-zoom").each(function(){
            /* =============================== ZOOM OUT =================================*/
            if(btnZoom == "zoom-out"){
                var presentSize = getContent.css('fontSize');
                var latestSize = parseInt(presentSize.replace("px", "")) - 1;
                $(getContent).css("fontSize", latestSize + "px");
                // console.log(latestSize + "px");
            }
            /* =============================== ZOOM IN =================================*/
            if(btnZoom == "zoom-in"){
                var presentSize = getContent.css('fontSize');
                var latestSize = parseInt (presentSize.replace ("px", "")) + 1;
                $(getContent).css ("fontSize", latestSize + "px");
                // console.log(latestSize + "px");
            }
            saveZoom (btnZoom)
        })
    })

}
function saveZoom(btnZoom){
    localStorage.setItem("Zoom" , btnZoom)
}
</code>```

Title: Local Storage with jQuery button Zoom

Body:
I want Local Storage , I selected but now I want to add local Storage to it so it remembers when I leave the page

I made now this code but it doesn't seem to work properly, could someone please help me ?

Local with button Zoom In , Zoom Out

HTML Button Zoom

                <button id="zoom-out" class="btn btn-zoom" data-value="zoom-out"></button>
                <button id="zoom-in" class="btn btn-zoom" data-value="zoom-in"></button>

HTML Content

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Delectus maiores mollitia consequuntur? Cum
                commodi debitis et. Voluptates et provident, cum voluptate voluptatum alias, delectus asperiores atque
                magni, fugit eveniet laborum!

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Porro blanditiis velit modi maxime quam, labore recusandae repellat tenetur unde in harum asperiores qui corporis vero ullam provident quisquam at voluptas laudantium expedita placeat ad? Corporis quod amet harum maiores omnis!

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Consequatur sequi velit laboriosam maxime
                nostrum necessitatibus aliquam iste reprehenderit numquam! Aliquid minus magni corporis magnam
                consequuntur minima sint beatae, sit voluptatum?

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Reiciendis modi placeat incidunt at voluptatibus, quibusdam, perspiciatis eligendi obcaecati perferendis maiores animi, eum vel aspernatur doloremque fugit et quasi soluta beatae dolorum rem ducimus saepe! Ipsam adipisci modi quo, dignissimos facere accusamus omnis enim eaque sint perspiciatis quos vel tempore doloribus.

JS

$(document).ready(function(){
   var getContent = $("#content");

    /* =============================== Local Storage =================================*/
    const savedZoom = localStorage.getItem('Zoom');

    if(savedZoom){
        $(getContent).css("fontSize", savedZoom);
    }

    /* =============================== BUTTON ZOOM =================================*/
    $(".btn-zoom").click(function(){
        var btnZoom = $(this).attr('data-value');
        console.log(btnZoom);

        $(".btn-zoom").each(function(){
            /* =============================== ZOOM OUT =================================*/
            if(btnZoom == "zoom-out"){
                var presentSize = getContent.css('fontSize');
                var latestSize = parseInt(presentSize.replace("px", "")) - 1;
                $(getContent).css("fontSize", latestSize + "px");
                // console.log(latestSize + "px");
            }
            /* =============================== ZOOM IN =================================*/
            if(btnZoom == "zoom-in"){
                var presentSize = getContent.css('fontSize');
                var latestSize = parseInt (presentSize.replace ("px", "")) + 1;
                $(getContent).css ("fontSize", latestSize + "px");
                // console.log(latestSize + "px");
            }
            saveZoom (btnZoom)
        })
    })

}
function saveZoom(btnZoom){
    localStorage.setItem("Zoom" , btnZoom)
}


问:
Redirecting stdout and stderr in both C and C++ on Windows
We're moving from Visual Studio 2013 to VS 2019, and it's no longer possible to assign to "_file" in the code below. I've been looking at other questions about this, and it's just not clear to me what to do. I see references to using freopen, which we use on Linux, but I'm not sure how that fits into this mechanism where we're piping to a child process, which then uses our custom print function that sends the output to the various places it's supposed to go. It's also not clear in those answers that it works on Windows. Links to posts where it talks about this tend to be broken, so some of the promising introductory answers were dead ends.

Ideally, the solution will work on both VS 2013 and VS 2019, but if not, I can conditionally compile it to handle that.

```<code>DWORD WINAPI io_thread (LPVOID *param);

void captureStdStreams (const char *outfile)
    {
    static HANDLE readHandle;
    static HANDLE writeHandle;

    FILE *xxx = stderr;

    if (CreatePipe (&readHandle, &writeHandle, 0, 0))
        {
        SetStdHandle (STD_ERROR_HANDLE, writeHandle);
        SetStdHandle (STD_OUTPUT_HANDLE, writeHandle);
        int fd = _open_osfhandle ((intptr_t) writeHandle, O_WRONLY | O_TEXT);
        dup2 (fd, 2);
        stderr->_file = fd;
        dup2 (fd, 1);
        stdout->_file = fd;
        }

    HANDLE th = CreateThread (0, 0, (LPTHREAD_START_ROUTINE) io_thread, &readHandle, 0, 0);
    CloseHandle (th);
    }

DWORD WINAPI io_thread (LPVOID *param)
    {
    HANDLE readHandle = *(HANDLE *) param;

    // Line buffer and pointer

    static char iobuf[256];
    static unsigned int bp = 0;

    for (;;)
        {
        DWORD nread;

        if (ReadFile (readHandle, &iobuf[bp], 1, &nread, 0))
            {
            if (bp == sizeof (iobuf) - 1 || iobuf[bp] == '\n')
                {
                productspecific::print ("%.*s", bp + 1, iobuf);
                bp = 0;
                }
            else
                {
                bp += 1;
                }
            }
        }

    return 0;
    }
</code>```

Body:
We're moving from Visual Studio 2013 to VS 2019, and it's no longer possible to assign to "_file" in the code below. I've been looking at other questions about this, and it's just not clear to me what to do. I see references to using freopen, which we use on Linux, but I'm not sure how that fits into this mechanism where we're piping to a child process, which then uses our custom print function that sends the output to the various places it's supposed to go. It's also not clear in those answers that it works on Windows. Links to posts where it talks about this tend to be broken, so some of the promising introductory answers were dead ends.

Ideally, the solution will work on both VS 2013 and VS 2019, but if not, I can conditionally compile it to handle that.

DWORD WINAPI io_thread (LPVOID *param);

void captureStdStreams (const char *outfile)
    {
    static HANDLE readHandle;
    static HANDLE writeHandle;

    FILE *xxx = stderr;

    if (CreatePipe (&readHandle, &writeHandle, 0, 0))
        {
        SetStdHandle (STD_ERROR_HANDLE, writeHandle);
        SetStdHandle (STD_OUTPUT_HANDLE, writeHandle);
        int fd = _open_osfhandle ((intptr_t) writeHandle, O_WRONLY | O_TEXT);
        dup2 (fd, 2);
        stderr->_file = fd;
        dup2 (fd, 1);
        stdout->_file = fd;
        }

    HANDLE th = CreateThread (0, 0, (LPTHREAD_START_ROUTINE) io_thread, &readHandle, 0, 0);
    CloseHandle (th);
    }

DWORD WINAPI io_thread (LPVOID *param)
    {
    HANDLE readHandle = *(HANDLE *) param;

    // Line buffer and pointer

    static char iobuf[256];
    static unsigned int bp = 0;

    for (;;)
        {
        DWORD nread;

        if (ReadFile (readHandle, &iobuf[bp], 1, &nread, 0))
            {
            if (bp == sizeof (iobuf) - 1 || iobuf[bp] == '\n')
                {
                productspecific::print ("%.*s", bp + 1, iobuf);
                bp = 0;
                }
            else
                {
                bp += 1;
                }
            }
        }

    return 0;
    }


问:
Why is GeoFence not triggering when entering a radius? (ANDROID - API 31)
I'm having this problem where the only time the geofence triggers is only when I create a radius right where I'm standing at the time and when I start moving and entering other radios it won't trigger.

I'm pretty sure the problem is the pendingIntent FLAG, but I don't know how to solve it.

I have tried all the FLAGS, but some of them don't even work. This same code worked on API 29, but I can't get it to work on API 31. Any help is appreciated.

MAIN CODE

```<code>package com.geofenceApp.geofencing

import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.google.android.gms.location.*
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.CircleOptions
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import kotlin.random.Random

const val GEOFENCE_RADIUS = 70
const val GEOFENCE_ID = "REMINDER_GEOFENCE_ID"
const val GEOFENCE_EXPIRATION = 10 * 24 * 60 * 60 * 1000 // 10 dias
const val GEOFENCE_DWELL_DELAY =  10 * 1000 // 10 segundos // 2 minutos
const val GEOFENCE_LOCATION_REQUEST_CODE = 12345
const val CAMERA_ZOOM_LEVEL = 13f
const val LOCATION_REQUEST_CODE = 123

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    private lateinit var map: GoogleMap
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var geofencingClient: GeofencingClient

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)
        val mapFragment = supportFragmentManager
                .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        geofencingClient = LocationServices.getGeofencingClient(this)
    }

    override fun onMapReady(googleMap: GoogleMap) {
        map = googleMap
        map.uiSettings.isZoomControlsEnabled = true

        if (!isLocationPermissionGranted()) {
            val permissions = mutableListOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
            permissions.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
            ActivityCompat.requestPermissions(
                this,
                permissions.toTypedArray(),
                LOCATION_REQUEST_CODE
            )
        } else {

            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return
            }

            this.map.isMyLocationEnabled = true

            // Hace zoom a la ultima ubicacion conocida
            fusedLocationClient.lastLocation.addOnSuccessListener {
                if (it != null) {
                    with(map) {
                        val latLng = LatLng(it.latitude, it.longitude)
                        moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, CAMERA_ZOOM_LEVEL))
                    }
                } else {
                    with(map) {        //Hace zoom a la ubicacion actual
                        moveCamera(
                            CameraUpdateFactory.newLatLngZoom(
                                LatLng(-34.69787, -58.50459),
                                CAMERA_ZOOM_LEVEL
                            )
                        )
                    }
                }
            }
        }

        setLongClick(map)
        setPoiClick(map)
    }

    private fun setPoiClick(map: GoogleMap) {
        map.setOnPoiClickListener { poi ->
            map.addMarker(
                MarkerOptions()
                    .position(poi.latLng)
                    .title(poi.name)
            )?.showInfoWindow()

        }
    }

    private fun setLongClick(map: GoogleMap) {
        map.setOnMapLongClickListener { latlng ->

            map.addMarker(
                MarkerOptions().position(latlng)
                    .title("Radio")
            )?.showInfoWindow()
            map.addCircle(
                CircleOptions()
                    .center(latlng)
                    .strokeColor(Color.argb(50, 70, 70, 70))
                    .fillColor(Color.argb(70, 150, 150, 150))
                    .radius(GEOFENCE_RADIUS.toDouble())
            )
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, CAMERA_ZOOM_LEVEL))

            val database = Firebase.database
            val reference = database.getReference("reminders")
            val key = reference.push().key
            if (key != null) {
                val reminder = Reminder(key, latlng.latitude, latlng.longitude,"Entrando al radio en ${latlng.latitude} - ${latlng.longitude}")
                reference.child(key).setValue(reminder)
            }
            createGeoFence(latlng, key!!, geofencingClient)
        }
    }

    private fun createGeoFence(location: LatLng, key: String, geofencingClient: GeofencingClient) {
        val geofence = Geofence.Builder()
            .setRequestId(GEOFENCE_ID)
            .setCircularRegion(location.latitude, location.longitude, GEOFENCE_RADIUS.toFloat())
            .setExpirationDuration(GEOFENCE_EXPIRATION.toLong())
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_DWELL)
            .setLoiteringDelay(GEOFENCE_DWELL_DELAY)
            .build()

        val geofenceRequest = GeofencingRequest.Builder()
            .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
            .addGeofence(geofence)
            .build()

        val intent = Intent(this, GeofenceReceiver::class.java)
            .putExtra("key", key)
            .putExtra("message", "Entrada detectada al radio - ${location.latitude}, ${location.longitude}")

        val pendingIntent = PendingIntent.getBroadcast(applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE)

        if (ContextCompat.checkSelfPermission(
                applicationContext, Manifest.permission.ACCESS_BACKGROUND_LOCATION
        ) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION),
                GEOFENCE_LOCATION_REQUEST_CODE
            )
        } else {
            geofencingClient.addGeofences(geofenceRequest, pendingIntent)
        }
    }

    private fun isLocationPermissionGranted() : Boolean {
        return ContextCompat.checkSelfPermission(
            this, Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
            applicationContext, Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == GEOFENCE_LOCATION_REQUEST_CODE) {
            if (permissions.isNotEmpty() && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(
                    this,
                    "Esta aplicación necesita acceso a la ubicación en segundo plano",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
        if (requestCode == LOCATION_REQUEST_CODE) {
            if (
                grantResults.isNotEmpty() && (
                        grantResults[0] == PackageManager.PERMISSION_GRANTED ||
                                grantResults[1] == PackageManager.PERMISSION_GRANTED)
            ) {
                if (ActivityCompat.checkSelfPermission(
                        this,
                        Manifest.permission.ACCESS_FINE_LOCATION
                    ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                        this,
                        Manifest.permission.ACCESS_COARSE_LOCATION
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    return
                }
                map.isMyLocationEnabled = true
                onMapReady(map)
            } else {
                Toast.makeText(
                    this,
                    "La aplicación necesita permiso para funcionar",
                    Toast.LENGTH_LONG
                ).show()
            }

            if (grantResults.isNotEmpty() && grantResults[2] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(
                    this,
                    "Esta aplicación necesita acceso a la ubicación en segundo plano",
                    Toast.LENGTH_LONG
                ).show()
            }
        }
    }

    companion object {
        fun removeGeofence(context: Context, triggeringGeofenceList: MutableList<Geofence>) {
            val geofenceIdList = mutableListOf<String>()
            for (entry in triggeringGeofenceList) {
                geofenceIdList.add(entry.requestId)
            }
            LocationServices.getGeofencingClient(context).removeGeofences(geofenceIdList)
        }

        fun showNotification(context: Context?, message: String) {
            val CHANNEL_ID = "REMINDER_NOTIFICATION_CHANNEL"
            var notificationId = 1589
            notificationId += Random(notificationId).nextInt(1, 30)

            val notificationBuilder = NotificationCompat.Builder(context!!.applicationContext, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_alarm)
                .setContentTitle(context.getString(R.string.app_name))
                .setContentText(message)
                .setStyle(
                    NotificationCompat.BigTextStyle().bigText(message)
                )
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)

            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            val channel = NotificationChannel(
                CHANNEL_ID,
                context.getString(R.string.app_name),
                NotificationManager.IMPORTANCE_DEFAULT
            ).apply {
                description = context.getString(R.string.app_name)
            }
            notificationManager.createNotificationChannel(channel)
            notificationManager.notify(notificationId, notificationBuilder.build())
        }
    }

}
</code>```

As I mentioned above this same code worked on API 29 but I need it to work on API 31 and is not working, I've been trying to solve this problem for the last 2 weeks.

Body:
I'm having this problem where the only time the geofence triggers is only when I create a radius right where I'm standing at the time and when I start moving and entering other radios it won't trigger.

I'm pretty sure the problem is the pendingIntent FLAG, but I don't know how to solve it.

I have tried all the FLAGS, but some of them don't even work. This same code worked on API 29, but I can't get it to work on API 31. Any help is appreciated.

MAIN CODE

package com.geofenceApp.geofencing

import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.google.android.gms.location.*
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.CircleOptions
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import kotlin.random.Random

const val GEOFENCE_RADIUS = 70
const val GEOFENCE_ID = "REMINDER_GEOFENCE_ID"
const val GEOFENCE_EXPIRATION = 10 * 24 * 60 * 60 * 1000 // 10 dias
const val GEOFENCE_DWELL_DELAY =  10 * 1000 // 10 segundos // 2 minutos
const val GEOFENCE_LOCATION_REQUEST_CODE = 12345
const val CAMERA_ZOOM_LEVEL = 13f
const val LOCATION_REQUEST_CODE = 123

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    private lateinit var map: GoogleMap
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var geofencingClient: GeofencingClient

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)
        val mapFragment = supportFragmentManager
                .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        geofencingClient = LocationServices.getGeofencingClient(this)
    }

    override fun onMapReady(googleMap: GoogleMap) {
        map = googleMap
        map.uiSettings.isZoomControlsEnabled = true

        if (!isLocationPermissionGranted()) {
            val permissions = mutableListOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
            permissions.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
            ActivityCompat.requestPermissions(
                this,
                permissions.toTypedArray(),
                LOCATION_REQUEST_CODE
            )
        } else {

            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return
            }

            this.map.isMyLocationEnabled = true

            // Hace zoom a la ultima ubicacion conocida
            fusedLocationClient.lastLocation.addOnSuccessListener {
                if (it != null) {
                    with(map) {
                        val latLng = LatLng(it.latitude, it.longitude)
                        moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, CAMERA_ZOOM_LEVEL))
                    }
                } else {
                    with(map) {        //Hace zoom a la ubicacion actual
                        moveCamera(
                            CameraUpdateFactory.newLatLngZoom(
                                LatLng(-34.69787, -58.50459),
                                CAMERA_ZOOM_LEVEL
                            )
                        )
                    }
                }
            }
        }

        setLongClick(map)
        setPoiClick(map)
    }

    private fun setPoiClick(map: GoogleMap) {
        map.setOnPoiClickListener { poi ->
            map.addMarker(
                MarkerOptions()
                    .position(poi.latLng)
                    .title(poi.name)
            )?.showInfoWindow()

        }
    }

    private fun setLongClick(map: GoogleMap) {
        map.setOnMapLongClickListener { latlng ->

            map.addMarker(
                MarkerOptions().position(latlng)
                    .title("Radio")
            )?.showInfoWindow()
            map.addCircle(
                CircleOptions()
                    .center(latlng)
                    .strokeColor(Color.argb(50, 70, 70, 70))
                    .fillColor(Color.argb(70, 150, 150, 150))
                    .radius(GEOFENCE_RADIUS.toDouble())
            )
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, CAMERA_ZOOM_LEVEL))

            val database = Firebase.database
            val reference = database.getReference("reminders")
            val key = reference.push().key
            if (key != null) {
                val reminder = Reminder(key, latlng.latitude, latlng.longitude,"Entrando al radio en ${latlng.latitude} - ${latlng.longitude}")
                reference.child(key).setValue(reminder)
            }
            createGeoFence(latlng, key!!, geofencingClient)
        }
    }

    private fun createGeoFence(location: LatLng, key: String, geofencingClient: GeofencingClient) {
        val geofence = Geofence.Builder()
            .setRequestId(GEOFENCE_ID)
            .setCircularRegion(location.latitude, location.longitude, GEOFENCE_RADIUS.toFloat())
            .setExpirationDuration(GEOFENCE_EXPIRATION.toLong())
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_DWELL)
            .setLoiteringDelay(GEOFENCE_DWELL_DELAY)
            .build()

        val geofenceRequest = GeofencingRequest.Builder()
            .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
            .addGeofence(geofence)
            .build()

        val intent = Intent(this, GeofenceReceiver::class.java)
            .putExtra("key", key)
            .putExtra("message", "Entrada detectada al radio - ${location.latitude}, ${location.longitude}")

        val pendingIntent = PendingIntent.getBroadcast(applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE)

        if (ContextCompat.checkSelfPermission(
                applicationContext, Manifest.permission.ACCESS_BACKGROUND_LOCATION
        ) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION),
                GEOFENCE_LOCATION_REQUEST_CODE
            )
        } else {
            geofencingClient.addGeofences(geofenceRequest, pendingIntent)
        }
    }

    private fun isLocationPermissionGranted() : Boolean {
        return ContextCompat.checkSelfPermission(
            this, Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
            applicationContext, Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == GEOFENCE_LOCATION_REQUEST_CODE) {
            if (permissions.isNotEmpty() && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(
                    this,
                    "Esta aplicación necesita acceso a la ubicación en segundo plano",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
        if (requestCode == LOCATION_REQUEST_CODE) {
            if (
                grantResults.isNotEmpty() && (
                        grantResults[0] == PackageManager.PERMISSION_GRANTED ||
                                grantResults[1] == PackageManager.PERMISSION_GRANTED)
            ) {
                if (ActivityCompat.checkSelfPermission(
                        this,
                        Manifest.permission.ACCESS_FINE_LOCATION
                    ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                        this,
                        Manifest.permission.ACCESS_COARSE_LOCATION
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    return
                }
                map.isMyLocationEnabled = true
                onMapReady(map)
            } else {
                Toast.makeText(
                    this,
                    "La aplicación necesita permiso para funcionar",
                    Toast.LENGTH_LONG
                ).show()
            }

            if (grantResults.isNotEmpty() && grantResults[2] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(
                    this,
                    "Esta aplicación necesita acceso a la ubicación en segundo plano",
                    Toast.LENGTH_LONG
                ).show()
            }
        }
    }

    companion object {
        fun removeGeofence(context: Context, triggeringGeofenceList: MutableList<Geofence>) {
            val geofenceIdList = mutableListOf<String>()
            for (entry in triggeringGeofenceList) {
                geofenceIdList.add(entry.requestId)
            }
            LocationServices.getGeofencingClient(context).removeGeofences(geofenceIdList)
        }

        fun showNotification(context: Context?, message: String) {
            val CHANNEL_ID = "REMINDER_NOTIFICATION_CHANNEL"
            var notificationId = 1589
            notificationId += Random(notificationId).nextInt(1, 30)

            val notificationBuilder = NotificationCompat.Builder(context!!.applicationContext, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_alarm)
                .setContentTitle(context.getString(R.string.app_name))
                .setContentText(message)
                .setStyle(
                    NotificationCompat.BigTextStyle().bigText(message)
                )
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)

            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            val channel = NotificationChannel(
                CHANNEL_ID,
                context.getString(R.string.app_name),
                NotificationManager.IMPORTANCE_DEFAULT
            ).apply {
                description = context.getString(R.string.app_name)
            }
            notificationManager.createNotificationChannel(channel)
            notificationManager.notify(notificationId, notificationBuilder.build())
        }
    }

}

As I mentioned above this same code worked on API 29 but I need it to work on API 31 and is not working, I've been trying to solve this problem for the last 2 weeks.


问:
Fetching an url to an image from API results in a 302 error
I am making a website in which I load images and other data from an API that is owned by someone else. The data is received in json format.

The response looks a bit like this:

```<code>{
  ...
  "users": [
    {
      "name": "John Doe",
      "profile_image": "https://api.<url>/img/<id>",
      "date_created": "<date>",
      ...
    },
    ...
  ]
  ...
}
</code>```

The issue I'm facing is that when I fetch these posts using JavaScript and want to use the profile_image as the src for an  tag, I sometimes (not always) get an response of 302 as supposed to the 200 I want, and the image won't load as a result of that.

My JavaScript looks kinda like this (very simplified):

```<code>function fetchUsers() {
  return fetch(url)
    .then(response => response.json())
    .catch(error => console.log(error));
}

async function loadUsers() {
  let users = await fetchUsers()
  users.forEach(user => {
    userDiv.innerHTML += createUser(user);
  });
}

function createUser(user) {
  return `
    <div>
      <h3>${user.name}</h3>
      <img src="${user.profile_image}">
    </div>
  `;
}
</code>```

When I follow the url I got from the API myself in the browser I get send to the image without any problems.

I suspect that it has to do with the fact that the image url seems to be linking to another API containing the images. I also noticed that in the DevTools console I see an error about Cross-Origin Read Blocking (CORB) blocking a cross-orign response.

Does anyone have experience with this problem and might be able to help?

Would be greatly appreciated!

Body:
I am making a website in which I load images and other data from an API that is owned by someone else. The data is received in json format.

The response looks a bit like this:

{
  ...
  "users": [
    {
      "name": "John Doe",
      "profile_image": "https://api.<url>/img/<id>",
      "date_created": "<date>",
      ...
    },
    ...
  ]
  ...
}

The issue I'm facing is that when I fetch these posts using JavaScript and want to use the profile_image as the src for an  tag, I sometimes (not always) get an response of 302 as supposed to the 200 I want, and the image won't load as a result of that.

My JavaScript looks kinda like this (very simplified):

function fetchUsers() {
  return fetch(url)
    .then(response => response.json())
    .catch(error => console.log(error));
}

async function loadUsers() {
  let users = await fetchUsers()
  users.forEach(user => {
    userDiv.innerHTML += createUser(user);
  });
}

function createUser(user) {
  return `

${user.name}

  `;
}

When I follow the url I got from the API myself in the browser I get send to the image without any problems.

I suspect that it has to do with the fact that the image url seems to be linking to another API containing the images. I also noticed that in the DevTools console I see an error about Cross-Origin Read Blocking (CORB) blocking a cross-orign response.

Does anyone have experience with this problem and might be able to help?

Would be greatly appreciated!


问:
LocalStorage key disappears when I set a new one
This was working before just fine. But now when it sets another new one it always get removed, and viceversa. I'm only setting in two different functions, each of those have:

```<code>localStorage.setItem("d-token", res.token);
localStorage.setItem("t-token", res.token);
</code>```

When I execute the function to set the d-token, t-token is removed, and when I set t-token, d-token is the one that gets removed which didn't happen before. I don't remember making any changes

I tried refreshing the page, but it still not working like it used to.

Body:
This was working before just fine. But now when it sets another new one it always get removed, and viceversa. I'm only setting in two different functions, each of those have:

localStorage.setItem("d-token", res.token);
localStorage.setItem("t-token", res.token);

When I execute the function to set the d-token, t-token is removed, and when I set t-token, d-token is the one that gets removed which didn't happen before. I don't remember making any changes

I tried refreshing the page, but it still not working like it used to.


问:
Android: launch PopupMenu from click/touch only on the hint shown on an EditText line?
I would like to be able to only launch a PopupMenu when an EditText line is empty and the EditText's hint is being shown and then is clicked on.  The hint is shown at the left-most portion of the line.  Currently, the PopupMenu is launched when any where on the EditText line is clicked on.

How do I restrict the PopupMenu launching to only when the hint is clicked on (the "Do" text shown in the left-most portion of the EditText below), rather than any where on the entire EditText line?

code in onCreate() of Activity:

```<code>cEditText.setOnClickListener(this::showTypePopup);
</code>```

code outside of onCreate():

```<code>private void showTypePopup(View v) {

    int stringToDo = cEditText.getText().toString().replace(" ", "").length();

    if (stringToDo == 0) {
        PopupMenu popup = new PopupMenu(this, v);
        popup.getMenuInflater().inflate(R.menu.p_menu, popup.getMenu());
        popup.setOnMenuItemClickListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.menu_one) {
                cEditText.setHint("Do");
                return true;
            }
            ...
            return false;
        });
        popup.show();
    }
}
</code>```

Body:
I would like to be able to only launch a PopupMenu when an EditText line is empty and the EditText's hint is being shown and then is clicked on.  The hint is shown at the left-most portion of the line.  Currently, the PopupMenu is launched when any where on the EditText line is clicked on.

How do I restrict the PopupMenu launching to only when the hint is clicked on (the "Do" text shown in the left-most portion of the EditText below), rather than any where on the entire EditText line?

code in onCreate() of Activity:

cEditText.setOnClickListener(this::showTypePopup);

code outside of onCreate():

private void showTypePopup(View v) {

    int stringToDo = cEditText.getText().toString().replace(" ", "").length();

    if (stringToDo == 0) {
        PopupMenu popup = new PopupMenu(this, v);
        popup.getMenuInflater().inflate(R.menu.p_menu, popup.getMenu());
        popup.setOnMenuItemClickListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.menu_one) {
                cEditText.setHint("Do");
                return true;
            }
            ...
            return false;
        });
        popup.show();
    }
}


问:
Is there a function similar to split_part, json_extract_scalar?
I am using spark_sql version 3.2.1. Is there a function that can replace

split_part,

json_extract_scalar

are not?


问:
enterPictureInPictureMode fails on switching to other app
I want to create an activity that automatically enters PiP when user switches to another app:

```<code>override fun onUserLeaveHint() {
    val currentState = lifecycle.currentState
    val enteredPiP = enterPictureInPictureMode(
        PictureInPictureParams.Builder()
            .setAspectRatio(Rational(3, 4))
            .build())
    Log.d(TAG, "onUserLeaveHint enteredPiP=$enteredPiP, state=$currentState")
    super.onUserLeaveHint()
}
</code>```

This works when I go to home screen:

```<code>onUserLeaveHint enteredPiP=true, state=RESUMED
onPictureInPictureModeChanged: true, state=STARTED
</code>```

But it failes when I switch directly to another app:

```<code>onUserLeaveHint enteredPiP=false, state=RESUMED
</code>```

Body:
I want to create an activity that automatically enters PiP when user switches to another app:

override fun onUserLeaveHint() {
    val currentState = lifecycle.currentState
    val enteredPiP = enterPictureInPictureMode(
        PictureInPictureParams.Builder()
            .setAspectRatio(Rational(3, 4))
            .build())
    Log.d(TAG, "onUserLeaveHint enteredPiP=$enteredPiP, state=$currentState")
    super.onUserLeaveHint()
}

This works when I go to home screen:

onUserLeaveHint enteredPiP=true, state=RESUMED
onPictureInPictureModeChanged: true, state=STARTED

But it failes when I switch directly to another app:

onUserLeaveHint enteredPiP=false, state=RESUMED


问:
Swift String (With Diacritics) Isn't Passing Into CLI Process Correctly
This bug/issue has been bugging me for many months. I've sunk hours trying to solve it. Any help/direction is super welcome!

When trying to run the following function it always throws an error when using certain diacritics (ä, etc.)

My end goal: Allow any language's special characters to be passed into the CLI interface.

func runShortcut(inputShortcut: String) {
    let shortcutsCLI = Process()
    shortcutsCLI.standardInput = nil //TODO: DTS Fix. This allows us to run the Shortcut!!!

    shortcutsCLI.executableURL = URL(fileURLWithPath: "/usr/bin/shortcuts")
    shortcutsCLI.arguments = ["run", inputShortcut.decomposedStringWithCanonicalMapping] //decomposedStringWithCanonicalMapping / composed
    print("Full args: ", shortcutsCLI.arguments) //Prints: Optional(["run", "ä"])

    do {
        try shortcutsCLI.run()
        print("Should've ran the shortcut...")
    } catch {
        print("\(error)")
    }
}

runShortcut(inputShortcut: "ä")
```

I've tried forming the input "string" as Unicode let str = "\u{00c4}", formed from binary, etc. Doesn't seem to matter how I get to the character/string "ä", it refuses to work.

I've also tried str.precomposedStringWithCanonicalMapping & str.precomposedStringWithCanonicalMapping, both unsuccessful.

Everything works fine, running from the CLI, Python & Go. I strongly believe it has something to do with how the string is being passed into the Process().

With that being said, I'm unsure if it's an issue with the String that's being passed in, or if it's an underlying issue with the Process().

I have saved the inputShortcut variable to a local .txt file, then using this command cat "/PathToTxt/a.txt" | xargs shortcuts run, & that works fine, no matter what characters I throw at it. This makes me believe it's less of an issue with the underlying String.

Body:
This bug/issue has been bugging me for many months. I've sunk hours trying to solve it. Any help/direction is super welcome!

When trying to run the following function it always throws an error when using certain diacritics (ä, etc.)

My end goal: Allow any language's special characters to be passed into the CLI interface.

func runShortcut(inputShortcut: String) {
    let shortcutsCLI = Process()
    shortcutsCLI.standardInput = nil //TODO: DTS Fix. This allows us to run the Shortcut!!!

    shortcutsCLI.executableURL = URL(fileURLWithPath: "/usr/bin/shortcuts")
    shortcutsCLI.arguments = ["run", inputShortcut.decomposedStringWithCanonicalMapping] //decomposedStringWithCanonicalMapping / composed
    print("Full args: ", shortcutsCLI.arguments) //Prints: Optional(["run", "ä"])

    do {
        try shortcutsCLI.run()
        print("Should've ran the shortcut...")
    } catch {
        print("\(error)")
    }
}

runShortcut(inputShortcut: "ä")

I've tried forming the input "string" as Unicode let str = "\u{00c4}", formed from binary, etc. Doesn't seem to matter how I get to the character/string "ä", it refuses to work.

I've also tried str.precomposedStringWithCanonicalMapping & str.precomposedStringWithCanonicalMapping, both unsuccessful.

Everything works fine, running from the CLI, Python & Go. I strongly believe it has something to do with how the string is being passed into the Process().

With that being said, I'm unsure if it's an issue with the String that's being passed in, or if it's an underlying issue with the Process().

I have saved the inputShortcut variable to a local .txt file, then using this command cat "/PathToTxt/a.txt" | xargs shortcuts run, & that works fine, no matter what characters I throw at it. This makes me believe it's less of an issue with the underlying String.


问:
where and how to catch an exception for a rest api
for a REST api , we usually have a controller layer and a service layer. I also have a .ts file for date utility.

consider the api:

```<code>('/myroute-controller')
async function controller1(req: Request){
  //call service
   return myrouter_service(req.body)

}

async function myrouter_service(params: any){
  // use utility function
  return my_date_utility(params.now)
}

function my_date_utility(now: Date) {
  new Date(now);  //potential exception
}
</code>```

from a practical perspective, there are 3 places I could catch the exception, the controller, the service or within the utility itself.

I want to throw a custom error like this:

```<code>try{
}catch(err){
  throw new myCustomError({metadata: {date:now}},err.message)
}
</code>```

I am looking for a general idea and guide line as to in which layer the exception is best caught(using try{}catch{}). What is the effect of such placing, and what advantages does it have among other placings?

The only thing I could think of is the stack trace, but, regardless of where the try{}catch{} is placed, we can still determine the point of error, and where the utility was called. I'd like a bit more insight on this.

Body:
for a REST api , we usually have a controller layer and a service layer. I also have a .ts file for date utility.

consider the api:

('/myroute-controller')
async function controller1(req: Request){
  //call service
   return myrouter_service(req.body)

}

async function myrouter_service(params: any){
  // use utility function
  return my_date_utility(params.now)
}

function my_date_utility(now: Date) {
  new Date(now);  //potential exception
}

from a practical perspective, there are 3 places I could catch the exception, the controller, the service or within the utility itself.

I want to throw a custom error like this:

try{
}catch(err){
  throw new myCustomError({metadata: {date:now}},err.message)
}

I am looking for a general idea and guide line as to in which layer the exception is best caught(using try{}catch{}). What is the effect of such placing, and what advantages does it have among other placings?

The only thing I could think of is the stack trace, but, regardless of where the try{}catch{} is placed, we can still determine the point of error, and where the utility was called. I'd like a bit more insight on this.