问:
Pandas dataframe and assigning values
There is a behavior of pandas dataframes that I can't explain. I wish somone could walk me through this.

```<code>import pandas as pd
df = pd.DataFrame(np.array([[1, 5, 10]]), columns=["Jan", "Fév", "Mar"])
df2 = pd.DataFrame(np.array([[4, 4, 4]]), columns=["Jan", "Fév", "Mar"])

df
    Jan Fév Mar
0   1   5   10

df2
    Jan Fév Mar
0   4   4   4
</code>```

So the booleans df < df2 and df >= df2 are respectively:

```<code>df < df2
    Jan     Fév     Mar
0   True    False   False

df >= df2
    Jan     Fév     Mar
0   False   True    True
</code>```

However if I do this sequence of code:

```<code>df3 = df2
df3[df < df2] = 0
df3[df >= df2] = 7
</code>```

I will get as a result:

```<code>df3
    Jan Fév Mar
0   7   7   7

df2
    Jan Fév Mar
0   7   7   7
</code>```

My question is: Why do my code also modifies the values of df2?

Is it because of the df3 = df2?

答:
In pandas there is difference between views and copies, by using = you are creating view, changes applied to it are also applied to original, as opposed to copy. Consider following simple example

```<code>import pandas as pd
df1 = pd.DataFrame({'x':[1,2,3]})
df2 = df1
df3 = df1.copy()
df3['x'] = 0
print(df1)
</code>```

output

```<code>   x
0  1
1  2
2  3
</code>```

then

```<code>df2['x'] = 0
print(df1)
</code>```

gives output

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

If you want to know more read Views and Copies in pandas in Practical Data Science.

Note that built-in python collections also do behave this way, e.g. dicts:

```<code>d1 = dict(x=1,y=2)
d2 = d1
d3 = d1.copy()
d3['x'] = 0
print(d1)  # {'x': 1, 'y': 2}
d2['x'] = 0
print(d1)  # {'x': 0, 'y': 2}
</code>```

Title: Pandas dataframe and assigning values

Body:
There is a behavior of pandas dataframes that I can't explain. I wish somone could walk me through this.

import pandas as pd
df = pd.DataFrame(np.array([[1, 5, 10]]), columns=["Jan", "Fév", "Mar"])
df2 = pd.DataFrame(np.array([[4, 4, 4]]), columns=["Jan", "Fév", "Mar"])

df
    Jan Fév Mar
0   1   5   10

df2
    Jan Fév Mar
0   4   4   4

So the booleans df < df2 and df >= df2 are respectively:

df < df2
    Jan     Fév     Mar
0   True    False   False

df >= df2
    Jan     Fév     Mar
0   False   True    True

However if I do this sequence of code:

df3 = df2
df3[df < df2] = 0
df3[df >= df2] = 7

I will get as a result:

df3
    Jan Fév Mar
0   7   7   7

df2
    Jan Fév Mar
0   7   7   7

My question is: Why do my code also modifies the values of df2?

Is it because of the df3 = df2?

Body:
In pandas there is difference between views and copies, by using = you are creating view, changes applied to it are also applied to original, as opposed to copy. Consider following simple example

import pandas as pd
df1 = pd.DataFrame({'x':[1,2,3]})
df2 = df1
df3 = df1.copy()
df3['x'] = 0
print(df1)

output

   x
0  1
1  2
2  3

then

df2['x'] = 0
print(df1)

gives output

0    0
1    0
2    0

If you want to know more read Views and Copies in pandas in Practical Data Science.

Note that built-in python collections also do behave this way, e.g. dicts:

d1 = dict(x=1,y=2)
d2 = d1
d3 = d1.copy()
d3['x'] = 0
print(d1)  # {'x': 1, 'y': 2}
d2['x'] = 0
print(d1)  # {'x': 0, 'y': 2}


来源: stackexchange

问:
Should state only be in a root component?
This may be considered as an opinionated question, but I was wondering if it is best to keep state at the root of the component.

For example, suppose have a form. The form has sections that correspond to different information that is requested to a user. The parent form contains all the state to be filled up and it passes it down to the sections

```<code>export default function Form() {
    const [state1, setState1] = useState();
    const [state2, setState2] = useState();
    const [state3, setState3] = useState();
    return (
        <>
            <Section1 state={state1} setState={setState1} />
            <Section2 state={state2} setState={setState2} />
            <Section3 state={state3} setState={setState3} />
        </>
    )
}
</code>```

Now let's say for some reason, <Section2 /> needs some sort of loading state

```<code>export default function Section2() {
    return (
        <div>
            {!loading ? ....} //do something with loading
        </div>
    )
}
</code>```

Should I put this loading state and its handle function up to the <Form /> parent even though the parent doesn't have any use for this state?

If I should place this state in the parent, and <Section2 /> updates it, doesn't that mean that every other section will re-render as well even though only <Section2 /> needs this? Does that have impact on performance?

I've been reading through best react design patterns and some say it is best to keep the state and handle functions at the root component. A concept of stateless and stateful components, or smart and dumb.

答:
You can do so, but you should lift up the state to the parent in case that there is a need for that loading state in other siblings components (like section1/section3).
If it's not the situation, you should keep the state closer it's used to avoid performance issues, that's lead us to your second question.

React re-render components due to state/props changes, so if the component's state changes it will re-render, or if another component consumes some props that changed, it will also cause a re-render.

 In a lot of cases this re-renders doesn't affect the website, so you will not even recognize those re-renders, but as the app grows up, it can impact the performance and that makes things be laggy.

ContentLicense: CC BY-SA 4.0

Body:
This may be considered as an opinionated question, but I was wondering if it is best to keep state at the root of the component.

For example, suppose have a form. The form has sections that correspond to different information that is requested to a user. The parent form contains all the state to be filled up and it passes it down to the sections

export default function Form() {
    const [state1, setState1] = useState();
    const [state2, setState2] = useState();
    const [state3, setState3] = useState();
    return (
        <>
            <Section1 state={state1} setState={setState1} />
            <Section2 state={state2} setState={setState2} />
            <Section3 state={state3} setState={setState3} />
        </>
    )
}

Now let's say for some reason, <Section2 /> needs some sort of loading state

export default function Section2() {
    return (

            {!loading ? ....} //do something with loading

    )
}

Should I put this loading state and its handle function up to the <Form /> parent even though the parent doesn't have any use for this state?

If I should place this state in the parent, and <Section2 /> updates it, doesn't that mean that every other section will re-render as well even though only <Section2 /> needs this? Does that have impact on performance?

I've been reading through best react design patterns and some say it is best to keep the state and handle functions at the root component. A concept of stateless and stateful components, or smart and dumb.


问:
Serial port listening through windows services in C#
I have created a windows service to listen the serial port inputs,below is my code but Im getting an error like missing assembly, I googled it but few article says to add System.WIndows.Forms Namespace,Even i added that Im getting the same error

Error 1   'VisionSystemService.VisionSystemService' does not contain a
  definition for 'BeginInvoke' and no extension method 'BeginInvoke'
  accepting a first argument of type
  'VisionSystemService.VisionSystemService' could be found (are you
  missing a using directive or an assembly reference?)

```<code> public partial class VisionSystemService : ServiceBase
    {
        SerialPort _SerialPort;
        private delegate void SetTextDeleg(string text);

        public VisionSystemService()
        {
            InitializeComponent();
            _SerialPort = new SerialPort("COM1", 19200, Parity.None, 8, StopBits.One);
            _SerialPort.Handshake = Handshake.None;
            _SerialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
            _SerialPort.ReadTimeout = 500;
            _SerialPort.WriteTimeout = 500;
            _SerialPort.Open();

        }
        void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(500);

            string data = _SerialPort.ReadExisting();
            this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });
        }

        protected override void OnStart(string[] args)
        {

        }

        private void si_DataReceived(string data)
        {

        }

        protected override void OnStop()
        {

        }
    }
</code>```

答: Your getting this error because neither your VisionSystemService class or ServiceBase have a method called BeginInvoke.  I recommend to just invoke your delegate.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have created a windows service to listen the serial port inputs,below is my code but Im getting an error like missing assembly, I googled it but few article says to add System.WIndows.Forms Namespace,Even i added that Im getting the same error

Error 1   'VisionSystemService.VisionSystemService' does not contain a
  definition for 'BeginInvoke' and no extension method 'BeginInvoke'
  accepting a first argument of type
  'VisionSystemService.VisionSystemService' could be found (are you
  missing a using directive or an assembly reference?)

 public partial class VisionSystemService : ServiceBase
    {
        SerialPort _SerialPort;
        private delegate void SetTextDeleg(string text);

        public VisionSystemService()
        {
            InitializeComponent();
            _SerialPort = new SerialPort("COM1", 19200, Parity.None, 8, StopBits.One);
            _SerialPort.Handshake = Handshake.None;
            _SerialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
            _SerialPort.ReadTimeout = 500;
            _SerialPort.WriteTimeout = 500;
            _SerialPort.Open();

        }
        void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(500);

            string data = _SerialPort.ReadExisting();
            this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });
        }

        protected override void OnStart(string[] args)
        {

        }

        private void si_DataReceived(string data)
        {

        }

        protected override void OnStop()
        {

        }
    }


问:
Build of Word-Add-In: error MSB3482: An error occurred while signing: Only certificates using RSA encryption are valid for signing ClickOnce manifests
When upgrading our solution from VS 2019 to VS 2022 and to .NET 4.8 on one of our machines the signing of a Word Add-In does not work any more. The machine was not in use for half a year so it could also be some other update stuff or so.

The csproj file has now <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>

First I got another error that I could overcome which is described here

Then I got the error error MSB3482: An error occurred while signing: Only certificates using RSA encryption are valid for signing ClickOnce manifests.

By googling I found that the error (following some translation files and the error message identifier SecurityUtil.OnlyRSACertsAreAllowed) probably comes from here in line 675
But I don't know what to make of it. EDIT: This certificate also works on other machines so there has to be some environmental issue other than the certificate content.
The used certificate has not changed and looks normal to me.

Considering the comment of Crypt32 I can say that this is a self owned Root CA that is only for development purposes. The Add-In gets re-signed later on with a better certificate. The algorithm state

Anyhow the reason for the icon of the dialog showing a red X is probably because this Root CA is not fully trusted (see last screenshot). Of course I should not enable full trust with such a certificate. On the other machines this certificates is also not trusted so this should not be the problem here.

I also saw that the private key for the certificate was not imported into my certificate store. I then also imported the private key but there is still the same error during build.
The public key says RSA 1024 bit if that is what you ment

Crypt32. Maybe the number of bits is too low?

EDIT:

答:
The short answer: I had only imported the public key parts of the certificates into the certificate store and thus could of course not sign the Add-In with the missing private key. The build error message could definitively be improved.

It looks like the import of the private keys to the certificates needed some time to kick in.


问:
How to get the access from one module's fields to second angular 13
I have an Angular app and I want to get the access to the user's field inside the message module.

Message.ts interface:

export interface Message {
  id: number;
  header: string;
  text: string;
  tag: string;
  authorUsername: string;
  likeCount: number;
  userId:number;
}
```
<p>Message service method form find all messages page:</p>
<pre class="lang-typescript prettyprint-override"><code>getAll(): Observable<any> {
    return this.httpClient.post(this.apiURL + 'api/message/get',{},this.httpOptions)
      .pipe(
        catchError(this.errorHandler)
      )
}
</code>```

My find all page component code:

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {

  messages: Message[] = [];

  // @Input() header =''
  deleted = false;
  constructor(public messageService: MessageService,
              private toastr:ToastrService) { }

  ngOnInit(): void {
    this.messageService.getAll().subscribe((data: Message[])=>{
      this.messages = data;
      console.log(this.messages);
    })

  }

  deletePost1(id:number){
    this.messageService.delete(id).subscribe(res => {
      this.toastr.success("Post Deleted");
      this.messages = this.messages.filter(item => item.id !== id);
      console.log('Post deleted successfully!');
    },
      ()=>{
      this.toastr.error("Can't delete! Something went wrong")
      })
  }

  infoPost(messageId: number){
    //showModalInfo(messageId);
    console.log("info post:" + messageId)
  }

}
```
<p>Find all page html (I hardcoded first name and last name from user) and I want to catch them from user like : <code>'{{user.firstName}}'</code></p>
<pre class="lang-html prettyprint-override"><code><div>

  <div class="content">
    <div class="col-md-3 left-body">
    </div>
    <div class="col-md-6 center-body">
      <div class="create_message_box_wrapper d-flex justify-content-center align-items-center">
        <div class="d-flex user-info-box align-items-center">
          <div class="user-avatar">
            <img src="https://picsum.photos/200/300?random=1" id="user-logo">
          </div>
          <div class="user-info">
            <p>First name: Oleg</p>
            <p>Last name: Petrenko</p>
          </div>
        </div>

        <div class="create_message_box d-flex justify-content-center align-items-center">
          Create New Message
        </div>
      </div>
      <ul>
        <li *ngFor="let message of messages">
          <app-messageblock [message]="message" (deleteEvent)="deletePost1($event)" (infoEvent)="infoPost($event)"></app-messageblock>
        </li>
      </ul>
    </div>
    <div class="col-md-3 right-body"></div>
  </div>
</div>
</code>```

User.ts interface:

export interface User {
  id: number,
  username: string,
  email: string,
  role: string,
  status: string,
  password:string,
  firstName: string,
  lastName: string,
  cityId: number,
  regionId: number,
  countryName: string,
  genderName: string,
  userId: number,
  file:File,
}
```
<p>User service method I want to use in my message find all page:</p>
<pre class="lang-typescript prettyprint-override"><code>find(id:number): Observable<any> {
    return this.httpClient.get(this.apiURL + 'api/user/' + id, this.httpOptions)
      .pipe(
        catchError(this.errorHandler)
      )
  }
</code>```

My  files hierarchy (message):

user:

答:
Assuming your find() method is inside an angular service, to get a user inside any component you need to:

Inject the service into the constructor of the component.

constructor(private userService: UserService) {}
```
<ol start="2">
<li>Call the function inside oyur component, I'll assume that you already know the current user's id, so we can call it in ngOnInit. Store the data in a variable.</li>
</ol>
<pre class="lang-js prettyprint-override"><code>user?: User;

ngOnInit(): void {
  this.userService.find(id).subscribe((user) => this.user = user);
}
</code>```

Now because the user will be undefined while we wait for a response, we will have to put a conditional statement in our html. Use {{}} to embed javascript / typescript into the html.

First name: {{user ? user.firstName : ""}}

Last name: {{user ? user.lastName : ""}}

```

Body:
I have an Angular app and I want to get the access to the user's field inside the message module.

Message.ts interface:

export interface Message {
  id: number;
  header: string;
  text: string;
  tag: string;
  authorUsername: string;
  likeCount: number;
  userId:number;
}

Message service method form find all messages page:

getAll(): Observable<any> {
    return this.httpClient.post(this.apiURL + 'api/message/get',{},this.httpOptions)
      .pipe(
        catchError(this.errorHandler)
      )
}

My find all page component code:

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {

  messages: Message[] = [];

  // @Input() header =''
  deleted = false;
  constructor(public messageService: MessageService,
              private toastr:ToastrService) { }

  ngOnInit(): void {
    this.messageService.getAll().subscribe((data: Message[])=>{
      this.messages = data;
      console.log(this.messages);
    })

  }

  deletePost1(id:number){
    this.messageService.delete(id).subscribe(res => {
      this.toastr.success("Post Deleted");
      this.messages = this.messages.filter(item => item.id !== id);
      console.log('Post deleted successfully!');
    },
      ()=>{
      this.toastr.error("Can't delete! Something went wrong")
      })
  }

  infoPost(messageId: number){
    //showModalInfo(messageId);
    console.log("info post:" + messageId)
  }

}

Find all page html (I hardcoded first name and last name from user) and I want to catch them from user like : '{{user.firstName}}'

First name: Oleg

Last name: Petrenko

          Create New Message

          <app-messageblock [message]="message" (deleteEvent)="deletePost1($event)" (infoEvent)="infoPost($event)"></app-messageblock>

User.ts interface:

export interface User {
  id: number,
  username: string,
  email: string,
  role: string,
  status: string,
  password:string,
  firstName: string,
  lastName: string,
  cityId: number,
  regionId: number,
  countryName: string,
  genderName: string,
  userId: number,
  file:File,
}

User service method I want to use in my message find all page:

find(id:number): Observable<any> {
    return this.httpClient.get(this.apiURL + 'api/user/' + id, this.httpOptions)
      .pipe(
        catchError(this.errorHandler)
      )
  }

My  files hierarchy (message):

user:

Body:
Assuming your find() method is inside an angular service, to get a user inside any component you need to:

Inject the service into the constructor of the component.

constructor(private userService: UserService) {}

Call the function inside oyur component, I'll assume that you already know the current user's id, so we can call it in ngOnInit. Store the data in a variable.

user?: User;

ngOnInit(): void {
  this.userService.find(id).subscribe((user) => this.user = user);
}

Now because the user will be undefined while we wait for a response, we will have to put a conditional statement in our html. Use {{}} to embed javascript / typescript into the html.

<p>First name: {{user ? user.firstName : ""}}</p>
<p>Last name: {{user ? user.lastName : ""}}</p>


问:
Choose rectangles with maximal intersection area
In this problem r is a fixed positive integer. You are given N rectangles, all the same size, in the plane. The sides are either vertical or horizontal. We assume the area of the intersection of all N rectangles has non-zero area. The problem is how to find N-r of these rectangles, so as to maximize the area of the intersection. This problem arises in practical microscopy when one repeatedly images a given biological specimen, and alignment changes slightly during this process, due to physical reasons (e.g. differential expansion of parts of the microscope and camera). I have expressed the problem for dimension d=2. There is a similar problem for each d>0. For d=1, an O(N log(N)) solution is obtained by sorting the lefthand endpoints of the intervals. But let's stick with d=2. If r=1, one can again solve the problem in time O(N log(N)) by sorting coordinates of the corners.

So, is the original problem solved by solving first the case (N,1) obtaining N-1 rectangles, then solving the case (N-1,1), getting N-2 rectangles, and so on, until we reduce to N-r rectangles? I would be interested to see an explicit counter-example to this optimistic attempted procedure. It would be even more interesting if the procedure works (proof please!), but that seems over-optimistic.

If r is fixed at some value r>1, and N is large, is this problem in one of the NP classes?

Thanks for any thoughts about this.

David

答:
I think I have a counter-example. Let's say you have r := N-2. I.e. you want to find two rectangles with maximum overlapping. Let's say you have to rectangles covering the same area (=maximum overlapping). Those two will be the optimal result in the end.

Now we need to construct some more rectangles, such that at least one of those two get removed in a reduction step.

Let's say we have three rectangles which overlap a lot..but they are not optimal. They have a very small overlapping area with the other two rectangles.

Now if you want to optimize the area for four rectangles, you will remove one of the two optimal rectangles, right? Or maybe you don't HAVE to, but you're not sure which decision is optimal.

So, I think your reduction algorithm is not quite correct. Atm I'm not sure if there is a good algorithm for this or in which complexity class this belongs to, though. If I have time I think about it :)


问:
TypeError: object of type 'NoneType' has no len() -- Even with Try Except
I am attempting to pull data from an api into an empty list and convert it to a dataframe. I have used a try and except for cases where the api would return a null value as well, but still keep getting this error. This is my code: (I have written a function called get_data to pull in my required datapoints from the API:

```<code>d = []

base_url = "api url inserted here"
for i in range(len(df)):
    try:
        address = base_url + df.loc[i,"column_for_api_call"]
        d.append(get_data(address))
    except (IndexError, TypeError) as error:
        print('ERROR at index {}: {!r}'.format(i, address))
        d.append(["  "])
lat = pd.DataFrame(d)
</code>```

But keep getting the error TypeError: object of type 'NoneType' has no len() after the entire code runs. What am I missing?

答:
df is None so your for-loop never gets entered. You should specify what should happen in that case:

```<code>if df is None:
    pass  # FIXME: what should happen here?
else:
    for i in range(len(df):
        address = base_url + df.loc[i,"column_for_api_call"]
        d.append(get_data(address))
</code>```

Body:
I am attempting to pull data from an api into an empty list and convert it to a dataframe. I have used a try and except for cases where the api would return a null value as well, but still keep getting this error. This is my code: (I have written a function called get_data to pull in my required datapoints from the API:

d = []

base_url = "api url inserted here"
for i in range(len(df)):
    try:
        address = base_url + df.loc[i,"column_for_api_call"]
        d.append(get_data(address))
    except (IndexError, TypeError) as error:
        print('ERROR at index {}: {!r}'.format(i, address))
        d.append(["  "])
lat = pd.DataFrame(d)

But keep getting the error TypeError: object of type 'NoneType' has no len() after the entire code runs. What am I missing?

Body:
df is None so your for-loop never gets entered. You should specify what should happen in that case:

if df is None:
    pass  # FIXME: what should happen here?
else:
    for i in range(len(df):
        address = base_url + df.loc[i,"column_for_api_call"]
        d.append(get_data(address))


问:
Can a 64-bit Windows app use an out-of-process (AX EXE) component?
A client is writing a 64-bit Windows app in some language (yet TBD) that can use COM. I have a 32-bit ActiveX EXE that includes functionality they'd like to include. All data to be marshalled between these would be simple 32-bit integers.

I have no experience in this area, but it seems like this should be possible. I've searched other answers here and many talk of using 32-bit DLLs in 64-bit apps but I didn't find anything on the point of out-of-process 32-bit COM servers in the same scenario.

答:
We just migrated an MS-Office-based application from 32-bit Office to 64-bit Office. The application uses a 32-bit out-of-process ActiveX EXE which was written in VB6 ages ago. Everything worked smoothly, no modification to the ActiveX EXE was required.

So, in my personal experience, the answer to your question

Can a 64-bit Windows app use a [32-bit] out-of-process (AX EXE) component?

is yes.


问:
Why won't my Django template display the correct date listed in the database?
My model contains a datefield, 'valid_until'. Even though an entry contains the date '12/25/2022', the update template literally displays as its contents 'mm/dd/yyyy' when the user tries to modify the date. Why? Also, there seems to be no way to create a placeholder text or even change that date format (it always renders in that same format---even though I specify '%m/%d/%y' in forms.py and settings.py contains the format '%m/%d/%y'). Why?
All of these problems seem related to the date picker feature. Are Django forms not compatible with the date picker feature?

settings.py:

```<code>TIME_ZONE = 'US/Eastern'
USE_I18N = True
USE_L10N = True
DATE_INPUT_FORMATS = '%m/%d/%y'
</code>```

models.py:

```<code>class DecisionsList(models.Model):
        summary = models.CharField(default="", max_length=75, `
 verbose_name="Decision Summary")
        description = models.CharField(max_length=100, verbose_name="Decision Description")
        valid_until = models.DateField(default=timezone.now, verbose_name="Voting End Date")
        date_created = models.DateTimeField(default=timezone.now)
</code>```

views.py:

class UpdateDecisionView(LoginRequiredMixin, UpdateView):

```<code>  model = DecisionsList
    form_class = DecisionForm
    template_name = "users/update_decision.html"
</code>```

forms.py:

```<code>class DecisionForm(forms.ModelForm):
    class Meta:
        model = DecisionsList
        fields = ['summary', 'description', 'valid_until']
        widgets = {
            'valid_until': forms.DateInput(
                format='%m/%d/%y',
                attrs={'type': 'date', 'placeholder': "Select a date"
                       }),
            'description': forms.Textarea(
                attrs={'line-height': '50px',
                       })
        }
</code>```

update_decision.html:

```<code>{% extends "users/base_users.html" %}

{% load crispy_forms_tags %}
{% load crispy_forms_filters %}

<body>

  {% block content %}

      <div class="nav">
        <a id="company" {% block company %} class="selected" {% endblock %} href=""></a>
      </div>

      <div class="containers database-containers">
        <h2>Update a Decision</h2>
      <form method="post">
        <div class="form-group">
                  {% csrf_token %}
                  {{form.summary|as_crispy_field}}
                  <div class="text-area">
                  {{form.description|as_crispy_field}}
                  </div>
                  <div class="short-field">
                  {{form.valid_until|as_crispy_field}}
                  </div>
            <input type="submit" class="btn" value="Update"/>
              <a href="{% url 'users:company' %}" class="btn">Cancel</a>
        </div>
      </form>
      </div>

  {% endblock %}

</body>
</code>```

答:
I found a solution that solved all of my Django / DatePicker issues:
Following is what I do, no external dependencies at all.:

Post that provides example of how to use a date picker in Django

models.py:

```<code>from django.db import models

class Promise(models):
    title = models.CharField(max_length=300)
    description = models.TextField(blank=True)
    made_on = models.DateField()
forms.py:

from django import forms
from django.forms import ModelForm

from .models import Promise

class DateInput(forms.DateInput):
    input_type = 'date'

class PromiseForm(ModelForm):

    class Meta:
        model = Promise
        fields = ['title', 'description', 'made_on']
        widgets = {
            'made_on': DateInput(),
        }
my view:

class PromiseCreateView(CreateView):
    model = Promise
    form_class = PromiseForm
And my template:

<form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Create" />
</form>
</code>```

Body:
My model contains a datefield, 'valid_until'. Even though an entry contains the date '12/25/2022', the update template literally displays as its contents 'mm/dd/yyyy' when the user tries to modify the date. Why? Also, there seems to be no way to create a placeholder text or even change that date format (it always renders in that same format---even though I specify '%m/%d/%y' in forms.py and settings.py contains the format '%m/%d/%y'). Why?
All of these problems seem related to the date picker feature. Are Django forms not compatible with the date picker feature?

settings.py:

TIME_ZONE = 'US/Eastern'
USE_I18N = True
USE_L10N = True
DATE_INPUT_FORMATS = '%m/%d/%y'

models.py:

class DecisionsList(models.Model):
        summary = models.CharField(default="", max_length=75, `
 verbose_name="Decision Summary")
        description = models.CharField(max_length=100, verbose_name="Decision Description")
        valid_until = models.DateField(default=timezone.now, verbose_name="Voting End Date")
        date_created = models.DateTimeField(default=timezone.now)

views.py:

class UpdateDecisionView(LoginRequiredMixin, UpdateView):

  model = DecisionsList
    form_class = DecisionForm
    template_name = "users/update_decision.html"

forms.py:

class DecisionForm(forms.ModelForm):
    class Meta:
        model = DecisionsList
        fields = ['summary', 'description', 'valid_until']
        widgets = {
            'valid_until': forms.DateInput(
                format='%m/%d/%y',
                attrs={'type': 'date', 'placeholder': "Select a date"
                       }),
            'description': forms.Textarea(
                attrs={'line-height': '50px',
                       })
        }

update_decision.html:

{% extends "users/base_users.html" %}

{% load crispy_forms_tags %}
{% load crispy_forms_filters %}

  {% block content %}

Update a Decision

      <form method="post">

                  {% csrf_token %}
                  {{form.summary|as_crispy_field}}

                  {{form.description|as_crispy_field}}

                  {{form.valid_until|as_crispy_field}}

            <input type="submit" class="btn" value="Update"/>
              Cancel

      </form>

  {% endblock %}

Body:
I found a solution that solved all of my Django / DatePicker issues:
Following is what I do, no external dependencies at all.:

Post that provides example of how to use a date picker in Django

models.py:

from django.db import models

class Promise(models):
    title = models.CharField(max_length=300)
    description = models.TextField(blank=True)
    made_on = models.DateField()
forms.py:

from django import forms
from django.forms import ModelForm

from .models import Promise

class DateInput(forms.DateInput):
    input_type = 'date'

class PromiseForm(ModelForm):

    class Meta:
        model = Promise
        fields = ['title', 'description', 'made_on']
        widgets = {
            'made_on': DateInput(),
        }
my view:

class PromiseCreateView(CreateView):
    model = Promise
    form_class = PromiseForm
And my template:

<form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Create" />
</form>


问:
How to change, edit, save /etc/hosts file from Azure Bash for Kubernetes?
I uploaded a project to kubernetes and for its gateway to redirect the services, it requires the following:

```<code>127.0.0.1 app.my.project
127.0.0.1 event-manager.my.project
127.0.0.1 logger.my.project
</code>```

and so on.

I can't run any sudo commands, so sudo nano /etc/hosts doesnt work. I tried vi /etc/hosts and it gives permission denied error. How can I edit /etc/hosts file or do some configuration on Azure to make it work like that?

Edit:

To give more information, I have uploaded a project to Kubernetes that has reverse-proxy settings.

So reaching the web-app of that project is not available via IP. Instead if I'm running the application locally, I have to edit the hosts file of the computer I'm using with

```<code>127.0.0.1 app.my.project
127.0.0.1 event-manager.my.project
127.0.0.1 logger.my.project
</code>```

and so on. So whenever I type web-app.my.project its gateway redirects to web-app part and if I write app.my.project it redirects to app part, etc.

When I uploaded it to Azure Kubernetes Service it added default-http-backend on ingress-nginx namespace which created by itself. To expose these services, I opened the Http Routing option from Azure which gave me the loadbalancer at the left side of the image. So If I'm reading the situation correctly, (I'm most probably wrong though) it is something like the image below:

So, I added hostaliases to kube-system, ingress-nginx and default namespaces to make it like I edited a hosts file when I was running the project locally. But it still gives me that default backend - 404 ingress error

Edit 2:

I have nginx-ingress-controller which allows the redirection as far as I understand. So, when I add hostaliases to it as follows:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-ingress-controller
  namespace: ingress-nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: ingress-nginx
  template:
    metadata:
      labels:
        app: ingress-nginx
      annotations:
        prometheus.io/port: '10254'
        prometheus.io/scrape: 'true'
    spec:
      hostAliases:
      - ip: "127.0.0.1"
      hostnames:
      - "app.ota.local"
      - "gateway.ota.local"
      - "treehub.ota.local"
      - "tuf-reposerver.ota.local"
      - "web-events.ota.local"
      hostNetwork: true
      serviceAccountName: nginx-ingress-serviceaccount
      containers:
        - name: nginx-ingress-controller
          image: {{ .ingress_controller_docker_image }}
          args:
            - /nginx-ingress-controller
            - --default-backend-service=$(POD_NAMESPACE)/default-http-backend
            - --configmap=$(POD_NAMESPACE)/nginx-configuration
            - --tcp-services-configmap=$(POD_NAMESPACE)/tcp-services
            - --udp-services-configmap=$(POD_NAMESPACE)/udp-services
          env:
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: POD_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
          ports:
          - name: tcp
            containerPort: 8000
          - name: http
            containerPort: 80
          - name: https
            containerPort: 443
          livenessProbe:
            failureThreshold: 3
            httpGet:
              path: /healthz
              port: 10254
              scheme: HTTP
            initialDelaySeconds: 10
            periodSeconds: 10
            successThreshold: 1
            timeoutSeconds: 1
          readinessProbe:
            failureThreshold: 3
            httpGet:
              path: /healthz
              port: 10254
              scheme: HTTP
            periodSeconds: 10
            successThreshold: 1
            timeoutSeconds: 1
</code>```

So when I edit yaml file as aforementioned, it gives the following error on Azure:

Failed to update the deployment
Failed to update the deployment 'nginx-ingress-controller'. Error: BadRequest (400) : Deployment in version "v1" cannot be handled as a Deployment: v1.Deployment.Spec: v1.DeploymentSpec.Template: v1.PodTemplateSpec.Spec: v1.PodSpec.HostAliases: []v1.HostAlias: readObjectStart: expect { or n, but found ", error found in #10 byte of ...|liases":["ip "127.0|..., bigger context ...|theus.io/scrape":"true"}},"spec":{"hostAliases":["ip "127.0.0.1""],"hostnames":["app.ota.local","g|...

If I edit the yaml file locally and try to run it from local kubectl which is connected to Azure, it gives the following error:

serviceaccount/weave-net configured
clusterrole.rbac.authorization.k8s.io/weave-net configured
clusterrolebinding.rbac.authorization.k8s.io/weave-net configured
role.rbac.authorization.k8s.io/weave-net configured
rolebinding.rbac.authorization.k8s.io/weave-net configured
daemonset.apps/weave-net configured Using cluster from kubectl
context: k8s_14

namespace/ingress-nginx unchanged deployment.apps/default-http-backend
unchanged service/default-http-backend unchanged
configmap/nginx-configuration unchanged configmap/tcp-services
unchanged configmap/udp-services unchanged
serviceaccount/nginx-ingress-serviceaccount unchanged
clusterrole.rbac.authorization.k8s.io/nginx-ingress-clusterrole
unchanged role.rbac.authorization.k8s.io/nginx-ingress-role unchanged
rolebinding.rbac.authorization.k8s.io/nginx-ingress-role-nisa-binding
unchanged
clusterrolebinding.rbac.authorization.k8s.io/nginx-ingress-clusterrole-nisa-binding
unchanged error: error validating
"/home/.../ota-community-edition/scripts/../generated/templates/ingress":
error validating data: ValidationError(Deployment.spec.template.spec):
unknown field "hostnames" in io.k8s.api.core.v1.PodSpec; if you choose
to ignore these errors, turn validation off with --validate=false
make: *** [Makefile:34: start_start-all] Error 1

答:
Adding entries to a
Pod's /etc/hosts file provides Pod-level override of hostname
resolution when DNS and other options are not applicable. You can add
these custom entries with the HostAliases field in PodSpec.

Modification not using HostAliases is not suggested because the file
is managed by the kubelet and can be overwritten on during Pod
creation/restart.

I suggest that you use hostAliases instead

```<code>apiVersion: v1
kind: Pod
metadata:
  name: hostaliases-pod
spec:
  restartPolicy: Never
  hostAliases:
  - ip: "127.0.0.1"
    hostnames:
    - "app.my.project"
    - "event-manager.my.project"
    - "logger.my.project"

  containers:
  - name: cat-hosts
    image: busybox
    command:
    - cat
    args:
    - "/etc/hosts"
</code>```

Body:
I uploaded a project to kubernetes and for its gateway to redirect the services, it requires the following:

127.0.0.1 app.my.project
127.0.0.1 event-manager.my.project
127.0.0.1 logger.my.project

and so on.

I can't run any sudo commands, so sudo nano /etc/hosts doesnt work. I tried vi /etc/hosts and it gives permission denied error. How can I edit /etc/hosts file or do some configuration on Azure to make it work like that?

Edit:

To give more information, I have uploaded a project to Kubernetes that has reverse-proxy settings.

So reaching the web-app of that project is not available via IP. Instead if I'm running the application locally, I have to edit the hosts file of the computer I'm using with

127.0.0.1 app.my.project
127.0.0.1 event-manager.my.project
127.0.0.1 logger.my.project

and so on. So whenever I type web-app.my.project its gateway redirects to web-app part and if I write app.my.project it redirects to app part, etc.

When I uploaded it to Azure Kubernetes Service it added default-http-backend on ingress-nginx namespace which created by itself. To expose these services, I opened the Http Routing option from Azure which gave me the loadbalancer at the left side of the image. So If I'm reading the situation correctly, (I'm most probably wrong though) it is something like the image below:

So, I added hostaliases to kube-system, ingress-nginx and default namespaces to make it like I edited a hosts file when I was running the project locally. But it still gives me that default backend - 404 ingress error

Edit 2:

I have nginx-ingress-controller which allows the redirection as far as I understand. So, when I add hostaliases to it as follows:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-ingress-controller
  namespace: ingress-nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: ingress-nginx
  template:
    metadata:
      labels:
        app: ingress-nginx
      annotations:
        prometheus.io/port: '10254'
        prometheus.io/scrape: 'true'
    spec:
      hostAliases:
      - ip: "127.0.0.1"
      hostnames:
      - "app.ota.local"
      - "gateway.ota.local"
      - "treehub.ota.local"
      - "tuf-reposerver.ota.local"
      - "web-events.ota.local"
      hostNetwork: true
      serviceAccountName: nginx-ingress-serviceaccount
      containers:
        - name: nginx-ingress-controller
          image: {{ .ingress_controller_docker_image }}
          args:
            - /nginx-ingress-controller
            - --default-backend-service=$(POD_NAMESPACE)/default-http-backend
            - --configmap=$(POD_NAMESPACE)/nginx-configuration
            - --tcp-services-configmap=$(POD_NAMESPACE)/tcp-services
            - --udp-services-configmap=$(POD_NAMESPACE)/udp-services
          env:
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: POD_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
          ports:
          - name: tcp
            containerPort: 8000
          - name: http
            containerPort: 80
          - name: https
            containerPort: 443
          livenessProbe:
            failureThreshold: 3
            httpGet:
              path: /healthz
              port: 10254
              scheme: HTTP
            initialDelaySeconds: 10
            periodSeconds: 10
            successThreshold: 1
            timeoutSeconds: 1
          readinessProbe:
            failureThreshold: 3
            httpGet:
              path: /healthz
              port: 10254
              scheme: HTTP
            periodSeconds: 10
            successThreshold: 1
            timeoutSeconds: 1

So when I edit yaml file as aforementioned, it gives the following error on Azure:

Failed to update the deployment
Failed to update the deployment 'nginx-ingress-controller'. Error: BadRequest (400) : Deployment in version "v1" cannot be handled as a Deployment: v1.Deployment.Spec: v1.DeploymentSpec.Template: v1.PodTemplateSpec.Spec: v1.PodSpec.HostAliases: []v1.HostAlias: readObjectStart: expect { or n, but found ", error found in #10 byte of ...|liases":["ip "127.0|..., bigger context ...|theus.io/scrape":"true"}},"spec":{"hostAliases":["ip "127.0.0.1""],"hostnames":["app.ota.local","g|...

If I edit the yaml file locally and try to run it from local kubectl which is connected to Azure, it gives the following error:

serviceaccount/weave-net configured
clusterrole.rbac.authorization.k8s.io/weave-net configured
clusterrolebinding.rbac.authorization.k8s.io/weave-net configured
role.rbac.authorization.k8s.io/weave-net configured
rolebinding.rbac.authorization.k8s.io/weave-net configured
daemonset.apps/weave-net configured Using cluster from kubectl
context: k8s_14

namespace/ingress-nginx unchanged deployment.apps/default-http-backend
unchanged service/default-http-backend unchanged
configmap/nginx-configuration unchanged configmap/tcp-services
unchanged configmap/udp-services unchanged
serviceaccount/nginx-ingress-serviceaccount unchanged
clusterrole.rbac.authorization.k8s.io/nginx-ingress-clusterrole
unchanged role.rbac.authorization.k8s.io/nginx-ingress-role unchanged
rolebinding.rbac.authorization.k8s.io/nginx-ingress-role-nisa-binding
unchanged
clusterrolebinding.rbac.authorization.k8s.io/nginx-ingress-clusterrole-nisa-binding
unchanged error: error validating
"/home/.../ota-community-edition/scripts/../generated/templates/ingress":
error validating data: ValidationError(Deployment.spec.template.spec):
unknown field "hostnames" in io.k8s.api.core.v1.PodSpec; if you choose
to ignore these errors, turn validation off with --validate=false
make: *** [Makefile:34: start_start-all] Error 1

Body:
Adding entries to a
Pod's /etc/hosts file provides Pod-level override of hostname
resolution when DNS and other options are not applicable. You can add
these custom entries with the HostAliases field in PodSpec.

Modification not using HostAliases is not suggested because the file
is managed by the kubelet and can be overwritten on during Pod
creation/restart.

I suggest that you use hostAliases instead

apiVersion: v1
kind: Pod
metadata:
  name: hostaliases-pod
spec:
  restartPolicy: Never
  hostAliases:
  - ip: "127.0.0.1"
    hostnames:
    - "app.my.project"
    - "event-manager.my.project"
    - "logger.my.project"

  containers:
  - name: cat-hosts
    image: busybox
    command:
    - cat
    args:
    - "/etc/hosts"


问:
Collapse objects in array based on id and calculate new properties in javascript
Here's a sample of a very particular dataset I am working on. I have an array of objects in the following format:

```<code>const input = [
  {year: "2010", country_id: "01", country: "India", region: "North", category: "a", value: "10", population: "100"},
  {year: "2010", country_id: "01", country: "India", region: "South", category: "a", value: "10", population: "100"},
  {year: "2010", country_id: "01", country: "India", region: "North", category: "b", value: "10", population: "100"},
  {year: "2010", country_id: "01", country: "India", region: "North", category: "c", value: "10", population: "100"},
  {year: "2015", country_id: "01", country: "India", region: "South", category: "a", value: "10", population: "100"},
  {year: "2015", country_id: "01", country: "India", region: "South", category: "a", value: "10", population: "100"},
  {year: "2015", country_id: "01", country: "India", region: "North", category: "b", value: "10", population: "100"},
  {year: "2015", country_id: "01", country: "India", region: "North", category: "c", value: "10", population: "100"},
  {year: "2015", country_id: "01", country: "India", region: "East", category: "c", value: "10", population: "100"},
  {year: "2015", country_id: "02", country: "Turkey", region: "North", category: "a", value: "15", population: "25"},
  {year: "2015", country_id: "02", country: "Turkey", region: "North", category: "b", value: "5", population: "25"}
]
</code>```

How can I collapse the objects in the array based on year and id and create a, b, c and total_population new properties in output based on the data in category, value and population from input?

One thing to note is that a, b and c are cumulative sums and total_population is a cumulative sum based on region. This means that population values are duplicated i some cases (i.e.: there are three entries in country "India" and region "North" that should total 100 and not 300.)

```<code>const output = [
  {year: "2010", id: "01", country: "India", a: 20, b: 10, c: 10, total_population: 200},
  {year: "2015", id: "01", country: "India", a: 10, b: 10, c: 20, population: 300},
  {year: "2015", id: "02", country: "Turkey", a: 15, b: 5, population: 25}
]
</code>```

My best attempt follows. Unfortunately I am constantly getting NaN when trying to execute the cumulative sum. Also, it seems that this solution does not perform well when testing it in a larger dataset.

```<code>const years = [...new Set(input.map((d) => d.year))].sort()

const country_ids = [...new Set(input.map((d) => d.country_id))].sort()

const combined_ids = {
  let array = [];

  country_ids.forEach((y, i) => {
    years.forEach((m) => {
      let obj = {};
      obj["year"] = m;
      obj["country_id"] = y;
      obj["combined_id"] = m + "-" + y;
      array.push(obj);
    });
  });

  return array;
}

const output = combined_ids.map((y, i) => {
  input.map((m) => {
    if (y.combined_id === m.year + "-" + m.country_id) {
      y.country_id = m.country_id;

      y[m.category] += !m.category
       ? 0
       : m.value === NaN
       ? 0
       : m.value === null
       ? 0
       : m.value === undefined
       ? 0
       : m.category === undefined
       ? 0
       : +m.value;

      y["total_population"] += +m.population;
      }
  });
  return y;
});

</code>```

答:
You can try below solution using array.reduce. First you need to create a dictionary to store unique population values. Then you can use another reduce to group objects and combine them together. delete will be used to make sure population for the same key is only used once:

const input = [
  {year: "2010", country_id: "01", country: "India", region: "North", category: "a", value: "10", population: "100"},
  {year: "2010", country_id: "01", country: "India", region: "South", category: "a", value: "10", population: "100"},
  {year: "2010", country_id: "01", country: "India", region: "North", category: "b", value: "10", population: "100"},
  {year: "2010", country_id: "01", country: "India", region: "North", category: "c", value: "10", population: "100"},
  {year: "2015", country_id: "01", country: "India", region: "South", category: "a", value: "10", population: "100"},
  {year: "2015", country_id: "01", country: "India", region: "South", category: "a", value: "10", population: "100"},
  {year: "2015", country_id: "01", country: "India", region: "North", category: "b", value: "10", population: "100"},
  {year: "2015", country_id: "01", country: "India", region: "North", category: "c", value: "10", population: "100"},
  {year: "2015", country_id: "01", country: "India", region: "East", category: "c", value: "10", population: "100"},
  {year: "2015", country_id: "02", country: "Turkey", region: "North", category: "a", value: "15", population: "25"},
  {year: "2015", country_id: "02", country: "Turkey", region: "North", category: "b", value: "5", population: "25"}
]

let getKey = obj => `${obj.year}-${obj.country}-${obj.region}`;

let populationDict = input.reduce((acc, cur) => {
    acc[getKey(cur)] = +cur.population;
    return acc;
}, {})

let output = input.reduce((acc, cur) => {
    let { year, country_id, country, category, value } = cur;
    let val = +value;
    let prev = acc.find(x => x.year === year && x.id === country_id && x.country === country);
    let population = populationDict[getKey(cur)];
    delete populationDict[getKey(cur)];

    if(!prev){
        acc.push({year,id: country_id,country, [category]: val, total_population: population});
    } else {
        prev[category] = prev[category] ? prev[category] + val : val;
        if(population) {
          prev.total_population += population;
        }
    }

    return acc;

}, []);

console.log(output);```

Body:
Here's a sample of a very particular dataset I am working on. I have an array of objects in the following format:

const input = [
  {year: "2010", country_id: "01", country: "India", region: "North", category: "a", value: "10", population: "100"},
  {year: "2010", country_id: "01", country: "India", region: "South", category: "a", value: "10", population: "100"},
  {year: "2010", country_id: "01", country: "India", region: "North", category: "b", value: "10", population: "100"},
  {year: "2010", country_id: "01", country: "India", region: "North", category: "c", value: "10", population: "100"},
  {year: "2015", country_id: "01", country: "India", region: "South", category: "a", value: "10", population: "100"},
  {year: "2015", country_id: "01", country: "India", region: "South", category: "a", value: "10", population: "100"},
  {year: "2015", country_id: "01", country: "India", region: "North", category: "b", value: "10", population: "100"},
  {year: "2015", country_id: "01", country: "India", region: "North", category: "c", value: "10", population: "100"},
  {year: "2015", country_id: "01", country: "India", region: "East", category: "c", value: "10", population: "100"},
  {year: "2015", country_id: "02", country: "Turkey", region: "North", category: "a", value: "15", population: "25"},
  {year: "2015", country_id: "02", country: "Turkey", region: "North", category: "b", value: "5", population: "25"}
]

How can I collapse the objects in the array based on year and id and create a, b, c and total_population new properties in output based on the data in category, value and population from input?

One thing to note is that a, b and c are cumulative sums and total_population is a cumulative sum based on region. This means that population values are duplicated i some cases (i.e.: there are three entries in country "India" and region "North" that should total 100 and not 300.)

const output = [
  {year: "2010", id: "01", country: "India", a: 20, b: 10, c: 10, total_population: 200},
  {year: "2015", id: "01", country: "India", a: 10, b: 10, c: 20, population: 300},
  {year: "2015", id: "02", country: "Turkey", a: 15, b: 5, population: 25}
]

My best attempt follows. Unfortunately I am constantly getting NaN when trying to execute the cumulative sum. Also, it seems that this solution does not perform well when testing it in a larger dataset.

const years = [...new Set(input.map((d) => d.year))].sort()

const country_ids = [...new Set(input.map((d) => d.country_id))].sort()

const combined_ids = {
  let array = [];

  country_ids.forEach((y, i) => {
    years.forEach((m) => {
      let obj = {};
      obj["year"] = m;
      obj["country_id"] = y;
      obj["combined_id"] = m + "-" + y;
      array.push(obj);
    });
  });

  return array;
}

const output = combined_ids.map((y, i) => {
  input.map((m) => {
    if (y.combined_id === m.year + "-" + m.country_id) {
      y.country_id = m.country_id;

      y[m.category] += !m.category
       ? 0
       : m.value === NaN
       ? 0
       : m.value === null
       ? 0
       : m.value === undefined
       ? 0
       : m.category === undefined
       ? 0
       : +m.value;

      y["total_population"] += +m.population;
      }
  });
  return y;
});


问:
How to create a TailwindCSS grid with a dynamic amount of grid columns?
I'm using Vue3 with TailwindCSS and want to create a grid with a dynamic grid-cols-{n} class. I know that TailwindCSS supports up to 12 columns by default but I can't customize the theme because the amount of columns is completely dynamic.

Given the following plain HTML / Js example

const amountOfItemsPerRow = 16;

const container = document.getElementById("container");

for (let i = 0; i < amountOfItemsPerRow; i++) {
  const item = document.createElement("div");
  item.innerText = i;
  container.appendChild(item);
}

container.classList.add(`grid-cols-${amountOfItemsPerRow}`); // this doesn't work if the value is greater than 12```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.tailwindcss.com"></script>

<div id="container" class="grid"></div></code>```

This code works fine if amountOfItemsPerRow is smaller or equal than 12, otherwise the CSS is broken.

Do I have to write code to setup plain CSS solving this or is there a dynamic Tailwind solution?

Another approach:

Based on the docs I tried to replace the line

```<code>container.classList.add(`grid-cols-${amountOfItemsPerRow}`);
</code>```

with

```<code>container.classList.add(`grid-template-columns:repeat(${amountOfItemsPerRow},minmax(0,1fr))`);
</code>```

to come up with a "native" approach but that didn't help.

答:
You cannot do that with plain TailwindCSS.

What @Ajay Raja suggests won't work because it only works with JIT (just-in-time); so previously to compiling the application you can use arbitrary values but once you've compiled and deployed your bundle that cannot be dynamic. It only works during build-time; so if you're using a CDN you'll not make it

What you can do is taking a look at the implementation of the class and set up some javascript listeners to dynamically set the style attribute:

From here you can see the implementation of .grid-columns-12.

.grid-columns-12 {
  grid-template-columns: repeat(12, minmax(0, 1fr));
}
```
<p>So from JS you can do something as follows:</p>
<pre class="lang-js prettyprint-override"><code>function setDynamicColumns(cols) {
  document
    .querySelector('#elementWithDynamicGrid')
    .style['grid-template-columns'] = `repeat(${cols}, minmax(0, 1fr))`
}
</code>```

I am not a Vue expert, but you could set two-way databinding like you would on Angular or React.

What you were doing here

container.classList.add(`grid-template-columns:repeat(${amountOfItemsPerRow},minmax(0,1fr))`)
```
<p>Was not working because you were applying a <code>style</code> directive into the <code>class</code> attribute</p>
<hr />
<p>Another approach to tackle this problem would be to generate the necessary amount of classes at build time so then you can use them safely at runtime:</p>
<p>If you take a look at the docs here</p>
<p>You can add your own custom grid modifiers by modifying the <code>tailwind.config.js</code> file.</p>
<pre class="lang-js prettyprint-override"><code>module.exports = {
  theme: {
    extend: {
      gridTemplateColumns: {
      // Simple 16 column grid
      '16': 'repeat(16, minmax(0, 1fr))',
      }
    }
  }
}
</code>```

So you can add a function that generates a reasonable number of columns there as follows:

//tailwind.config.js
function generateGridColumns(lastValue) {
   let obj = {}
   for(let i = 13; i < lastValue; i++) {
     obj[`${i}`] = `repeat(${i}, minmax(0, 1fr))`
   }
   return obj
}

module.exports = {
  theme: {
    extend: {
      gridTemplateColumns: {
         ...generateGridColumns(100) // This generates the columns from 12 until 100
      }
    }
  }
}
```

Please bear in mind that when purging your tailwindCSS builds you need to indicate to keep all grid-columns-* classes since the purger cannot guess that you're going to use them

Body:
I'm using Vue3 with TailwindCSS and want to create a grid with a dynamic grid-cols-{n} class. I know that TailwindCSS supports up to 12 columns by default but I can't customize the theme because the amount of columns is completely dynamic.

Given the following plain HTML / Js example

const amountOfItemsPerRow = 16;

const container = document.getElementById("container");

for (let i = 0; i < amountOfItemsPerRow; i++) {
  const item = document.createElement("div");
  item.innerText = i;
  container.appendChild(item);
}

container.classList.add(`grid-cols-${amountOfItemsPerRow}`); // this doesn't work if the value is greater than 12

This code works fine if amountOfItemsPerRow is smaller or equal than 12, otherwise the CSS is broken.

Do I have to write code to setup plain CSS solving this or is there a dynamic Tailwind solution?

Another approach:

Based on the docs I tried to replace the line

container.classList.add(`grid-cols-${amountOfItemsPerRow}`);

with

container.classList.add(`grid-template-columns:repeat(${amountOfItemsPerRow},minmax(0,1fr))`);

to come up with a "native" approach but that didn't help.

Body:
You cannot do that with plain TailwindCSS.

What @Ajay Raja suggests won't work because it only works with JIT (just-in-time); so previously to compiling the application you can use arbitrary values but once you've compiled and deployed your bundle that cannot be dynamic. It only works during build-time; so if you're using a CDN you'll not make it

What you can do is taking a look at the implementation of the class and set up some javascript listeners to dynamically set the style attribute:

From here you can see the implementation of .grid-columns-12.

.grid-columns-12 {
  grid-template-columns: repeat(12, minmax(0, 1fr));
}

So from JS you can do something as follows:

function setDynamicColumns(cols) {
  document
    .querySelector('#elementWithDynamicGrid')
    .style['grid-template-columns'] = `repeat(${cols}, minmax(0, 1fr))`
}

I am not a Vue expert, but you could set two-way databinding like you would on Angular or React.

What you were doing here

container.classList.add(`grid-template-columns:repeat(${amountOfItemsPerRow},minmax(0,1fr))`)

Was not working because you were applying a style directive into the class attribute

Another approach to tackle this problem would be to generate the necessary amount of classes at build time so then you can use them safely at runtime:

If you take a look at the docs here

You can add your own custom grid modifiers by modifying the tailwind.config.js file.

module.exports = {
  theme: {
    extend: {
      gridTemplateColumns: {
      // Simple 16 column grid
      '16': 'repeat(16, minmax(0, 1fr))',
      }
    }
  }
}

So you can add a function that generates a reasonable number of columns there as follows:

//tailwind.config.js
function generateGridColumns(lastValue) {
   let obj = {}
   for(let i = 13; i < lastValue; i++) {
     obj[`${i}`] = `repeat(${i}, minmax(0, 1fr))`
   }
   return obj
}

module.exports = {
  theme: {
    extend: {
      gridTemplateColumns: {
         ...generateGridColumns(100) // This generates the columns from 12 until 100
      }
    }
  }
}

Please bear in mind that when purging your tailwindCSS builds you need to indicate to keep all grid-columns-* classes since the purger cannot guess that you're going to use them


问:
Replace a string like "<toto>*<titi>" with "<toto>fixed string<titi>"
How to (inside a bash script) replace a string like <toto>*<titi> with <toto>fixed string<titi> using sed, provided that * is a wildcard?

答:
I suspect that this would do it:

```<code>sed -E 's/<toto>[^<]*<titi>/<toto>fixed string<titi>/g'
</code>```

...but I'd try to make sure that the opening tag <titi> is always the first one following <toto>. My sed line will not replace something in

```<code><toto>something<foo>another value<titi> ...
</code>```

since it breaks at the first peek at < (the [^<]* - which means: any amount of anything but <) and requires that it's followed by <titi>

Body:
I suspect that this would do it:

sed -E 's/<toto>[^<]*<titi>/<toto>fixed string<titi>/g'

...but I'd try to make sure that the opening tag <titi> is always the first one following <toto>. My sed line will not replace something in

<toto>something<foo>another value<titi> ...

since it breaks at the first peek at < (the [^<]* - which means: any amount of anything but <) and requires that it's followed by <titi>


问:
Numeric UDL operator template
I'm trying to define what Pablo Halpern calls a numeric UDL operator template. I want it to return a lambda that would count how many characters at the beginning of a char array are from the given set.

Here's my test code:

```<code>template <char... c>
constexpr auto operator ""_cntany() {
  return [](const char* s){
    unsigned n = 0;
    while (((*s==c) || ...)) { ++n; ++s; }
    return n;
  };
}

int main(int argc, char** argv) {
  return ("test"_cntany)(argv[1]);
}
</code>```

But this doesn't compile with GCC 11.2 (https://godbolt.org/z/TdbKzTMW8).
Here's the error I'm getting:

```<code><source>: In function 'int main(int, char**)':
<source>:11:15: error: no matching function for call to 'operator""_cntany<"test">()'
  11 |       return ("test"_cntany)(argv[1]);
      |               ^~~~~~~~~~~~~
<source>:2:20: note: candidate: 'template<char ...c> constexpr auto operator""_cntany()'
    2 |     constexpr auto operator ""_cntany() {
      |                    ^~~~~~~~
<source>:2:20: note:   template argument deduction/substitution failed:
<source>:11:15: error: '"test"' is not a valid template argument for type 'char' because string literals can never be used in this context
  11 |       return ("test"_cntany)(argv[1]);
     |               ^~~~~~~~~~~~~
Compiler returned: 1
</code>```

What am I doing wrong?

答:
template user-defined literals need to accept numeric values such as 0123_cntany, so you may need to just use user-defined string-literal:

```<code>#include <cstddef>
#include <string_view>

constexpr auto operator ""_cntany(const char* s, std::size_t count) {
  return [sv = std::string_view(s, count)](const char* s){
    unsigned n = 0;
    while (sv.contains(*s)) { ++n; ++s; }
    return n;
  };
}
</code>```

Title: Numeric UDL operator template

Body:
I'm trying to define what Pablo Halpern calls a numeric UDL operator template. I want it to return a lambda that would count how many characters at the beginning of a char array are from the given set.

Here's my test code:

template <char... c>
constexpr auto operator ""_cntany() {
  return [](const char* s){
    unsigned n = 0;
    while (((*s==c) || ...)) { ++n; ++s; }
    return n;
  };
}

int main(int argc, char** argv) {
  return ("test"_cntany)(argv[1]);
}

But this doesn't compile with GCC 11.2 (https://godbolt.org/z/TdbKzTMW8).
Here's the error I'm getting:

<source>: In function 'int main(int, char**)':
<source>:11:15: error: no matching function for call to 'operator""_cntany<"test">()'
  11 |       return ("test"_cntany)(argv[1]);
      |               ^~~~~~~~~~~~~
<source>:2:20: note: candidate: 'template<char ...c> constexpr auto operator""_cntany()'
    2 |     constexpr auto operator ""_cntany() {
      |                    ^~~~~~~~
<source>:2:20: note:   template argument deduction/substitution failed:
<source>:11:15: error: '"test"' is not a valid template argument for type 'char' because string literals can never be used in this context
  11 |       return ("test"_cntany)(argv[1]);
     |               ^~~~~~~~~~~~~
Compiler returned: 1

What am I doing wrong?

Body:
template user-defined literals need to accept numeric values such as 0123_cntany, so you may need to just use user-defined string-literal:

#include <cstddef>
#include <string_view>

constexpr auto operator ""_cntany(const char* s, std::size_t count) {
  return [sv = std::string_view(s, count)](const char* s){
    unsigned n = 0;
    while (sv.contains(*s)) { ++n; ++s; }
    return n;
  };
}


问:
looping through arrays of arrays
I have an arrays of arrays (some thing like graph), How to iterate all arrays?

```<code>var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];
</code>```

Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM

答:
if you just want to print all the members,how about this?</p>

```<code>var items = parentArray.toString().split(",");
for(var i=0,j=items.length;i<j;i++)
    console.log(items[i]);
</code>```

Title: looping through arrays of arrays

Body:
I have an arrays of arrays (some thing like graph), How to iterate all arrays?

var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];

Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM

Body:
if you just want to print all the members,how about this?

var items = parentArray.toString().split(",");
for(var i=0,j=items.length;i<j;i++)
    console.log(items[i]);


问:
Grav 1.7 Installation fails bc of call to undefined method

Cross post from https://github.com/getgrav/grav/issues/3523

(don't kill me, I didn't know that it's frowned upon)

I am not sure if this is the place to ask for help, so tell me if it's not (and maybe where to ask).

I am trying to update to the latest Grav release 1.7.29 from (originally 1.6.24, while troubleshooting today updated to) 1.6.31 (using direct-install.

I tried updating with self-upgrade and direct-install <latestVersionURL>.
But, while trying to install, it gives me the following error:

Installing upgrade... [30-Jan-2022 17:04:37 Europe/Cityxy] PHP Fatal
error: Uncaught Error: Call to undefined method
Grav\Common\Utils::basename() in
/var/www/virtual/name/html/tmp/Grav-61f6b713f0bb9/zip/grav-update/system/src/Grav/Installer/VersionUpdate.php:29

Stack trace:

#0 /var/www/virtual/name/html/tmp/Grav-61f6b713f0bb9/zip/grav-update/system/src/Grav/Installer/VersionUpdater.php(126):
Grav\Installer\VersionUpdate->__construct('/var/www/virtua...',
Object(Grav\Installer\VersionUpdater))
#1 /var/www/virtual/name/html/tmp/Grav-61f6b713f0bb9/zip/grav-update/system/src/Grav/Installer/VersionUpdater.php(38):
Grav\Installer\VersionUpdater->loadUpdates()
#2 /var/www/virtual/name/html/tmp/Grav-61f6b713f0bb9/zip/grav-update/system/src/Grav/Installer/Install.php(239):
Grav\Installer\VersionUpdater->__construct('core/grav',
'/var/www/virtua...', '1.7.29', Object(Grav\Installer\Versions))
#3 /var/www/virtual/name/html/tmp/Grav-61f6b713f0bb9/zip/grav-update/system/src/Grav/Installer/Install.php(184):
Grav\Installer\Install->prepare()
#4 /var/www/virtual/name/html/system/src/Gra in /var/www/virtual/eduref/html/tmp/Grav-61f6b713f0bb9/zip/grav-update/system/src/Grav/Installer/VersionUpdate.php
on line 29

From my understanding the files between versions have been changed, and looking at the Grav documentation, the called method basenames() is now in Grav/Common/URI, not in Grav/Common/Utils.

So I assume I located the problem, but have no idea on fixing it. Since I am not very well versed on this whole topic of managing websites (never set up the site, only maintaining it), I would really appreciate a safe answer on how to update Grav to the newest version which doesn't risk me destroying the functioning of the website.

Thank you for helping! :)

Tried with:
PHP: 7.3 & 7.4
Grav: 1.6.24 & 1.6.31
Admin: 1.9.10
Host: Uberspace
via SSH

答:
Particular issue fixed:
https://github.com/getgrav/grav/issues/3523

following issue open:
https://github.com/getgrav/grav/issues/3532


问:
Custom sound for NotificationChannel for Android 11 not working
I have push notifications with custom sounds working until android 10. Since Android 11 the sound attached to the notification channel stopped playing when the notification is presented as drop down style. It works when it is presented as full screen activity.

Here is the example source code how the notification channel is created

```<code>private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

    String channelId = "media_playback_channel_v_01_1_sound"
    String channelName = "Channel High"
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
        channel.setDescription("My custom sound");
        channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);

        AudioAttributes.Builder builder = new AudioAttributes.Builder();
        builder.setUsage(AudioAttributes.USAGE_NOTIFICATION);
    String basePath = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.alarm_sound);
    Uri alarmSound = Uri.parse(basePath);
        channel.setSound(alarmSound, builder.build());

        channel.enableVibration(true);
        channel.enableLights(true);
        channel.setLightColor(Color.RED);
    }
}
</code>```

I use the notification channel above and fire the notification as follow:

```<code>private void fireNotification(Context context) {
    String channelId = "media_playback_channel_v_01_1_sound"
        NotificationChannel channel = getManager().getNotificationChannel(channelId);

        PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(context, 100,
                fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        String contentText = getString(R.string.call_notification_incoming_from, from);

        Bundle args = new Bundle();
        args.putInt(CallActivity.INTENT_CALL_NOTIFICATION_ID, ActiveCall.ANDROID_10_PUSH_CALL_NTFN_ID);
        args.putBoolean(CallActivity.INTENT_FROM_CALL_NOTIFICATION, true);
        args.putString(CallActivity.INTENT_NOTIFICATION_CALL_ID, fullScreenIntent.getStringExtra(CallActivity.INTENT_NOTIFICATION_CALL_ID));

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, type)
                        .setSmallIcon(iconRes)
                        .setContentTitle(getString(R.string.app_name))
                        .setContentText(contentText)
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setCategory(NotificationCompat.CATEGORY_CALL)
                        .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                        .setOngoing(true)
                        .setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_ALL)
                        .setTimeoutAfter(Consts.MINUTE)
                        .addExtras(args);

    notificationBuilder.addAction(
        R.drawable.ic_accept_call,
                getString(R.string.call_notification_incoming_answer),
                answerPendingIntent);
        notificationBuilder.addAction(
                        R.drawable.ic_decline_bttn,
                        getString(R.string.call_notification_incoming_reject),
                        rejectPendingIntent
                );
        notificationBuilder.setFullScreenIntent(fullScreenPendingIntent, true);

    // Build
        Notification notification = notificationBuilder.build();
    notification.sound = notificationSoundUri;
        notification.flags |= (Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_INSISTENT Notification.FLAG_NO_CLEAR);
        notification.ledARGB = Color.RED;
        notification.ledOnMS = 300;
        notification.ledOffMS = 1000;

    // Notify
        NotificationManager notificationManager = getManager();
        notificationManager.notify(id, notification);
}
</code>```

Note that the same code plays the sound in Android 10, while it does not on Android 11.

答:
Finally, after researching a lot, I found a solution. All you need is this:-

While Creating Notification Channel, create different channels for Silent Notification, Custom Sound Notification, etc.

```<code>  // The custom sound file name you want
  val soundName = "beep"
  val soundUri = Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://${packageName}/raw/${soundName}")

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      val importance = NotificationManager.IMPORTANCE_HIGH
      val audioAttributes = AudioAttributes.Builder()
          .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
          .setUsage(AudioAttributes.USAGE_NOTIFICATION)
          .build()

      // Here The CHANNEL_ID is the main thing for creating a channel. Use this same CHANNEL_ID in Notification Builder Also.
      val channel = NotificationChannel(CHANNEL_ID, getString(R.string.app_name), importance).apply {
          description = getString(R.string.app_name)
          setSound(null, audioAttributes) // Give Null if you want silent notification
          // setSound(soundUri, audioAttributes)
      }
      notificationManager.createNotificationChannel(channel)
  }
</code>```

Notification Builder:-

```<code>        // Here The CHANNEL_ID needs to be same like the above created channel id. Because it defines how notification sound come.
    val builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(smallIcon)

    with(notificationManager) {
        notify(notificationId, builder.build())
    }
</code>```

Body:
I have push notifications with custom sounds working until android 10. Since Android 11 the sound attached to the notification channel stopped playing when the notification is presented as drop down style. It works when it is presented as full screen activity.

Here is the example source code how the notification channel is created

private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

    String channelId = "media_playback_channel_v_01_1_sound"
    String channelName = "Channel High"
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
        channel.setDescription("My custom sound");
        channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);

        AudioAttributes.Builder builder = new AudioAttributes.Builder();
        builder.setUsage(AudioAttributes.USAGE_NOTIFICATION);
    String basePath = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.alarm_sound);
    Uri alarmSound = Uri.parse(basePath);
        channel.setSound(alarmSound, builder.build());

        channel.enableVibration(true);
        channel.enableLights(true);
        channel.setLightColor(Color.RED);
    }
}

I use the notification channel above and fire the notification as follow:

private void fireNotification(Context context) {
    String channelId = "media_playback_channel_v_01_1_sound"
        NotificationChannel channel = getManager().getNotificationChannel(channelId);

        PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(context, 100,
                fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        String contentText = getString(R.string.call_notification_incoming_from, from);

        Bundle args = new Bundle();
        args.putInt(CallActivity.INTENT_CALL_NOTIFICATION_ID, ActiveCall.ANDROID_10_PUSH_CALL_NTFN_ID);
        args.putBoolean(CallActivity.INTENT_FROM_CALL_NOTIFICATION, true);
        args.putString(CallActivity.INTENT_NOTIFICATION_CALL_ID, fullScreenIntent.getStringExtra(CallActivity.INTENT_NOTIFICATION_CALL_ID));

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, type)
                        .setSmallIcon(iconRes)
                        .setContentTitle(getString(R.string.app_name))
                        .setContentText(contentText)
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setCategory(NotificationCompat.CATEGORY_CALL)
                        .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                        .setOngoing(true)
                        .setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_ALL)
                        .setTimeoutAfter(Consts.MINUTE)
                        .addExtras(args);

    notificationBuilder.addAction(
        R.drawable.ic_accept_call,
                getString(R.string.call_notification_incoming_answer),
                answerPendingIntent);
        notificationBuilder.addAction(
                        R.drawable.ic_decline_bttn,
                        getString(R.string.call_notification_incoming_reject),
                        rejectPendingIntent
                );
        notificationBuilder.setFullScreenIntent(fullScreenPendingIntent, true);

    // Build
        Notification notification = notificationBuilder.build();
    notification.sound = notificationSoundUri;
        notification.flags |= (Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_INSISTENT Notification.FLAG_NO_CLEAR);
        notification.ledARGB = Color.RED;
        notification.ledOnMS = 300;
        notification.ledOffMS = 1000;

    // Notify
        NotificationManager notificationManager = getManager();
        notificationManager.notify(id, notification);
}

Note that the same code plays the sound in Android 10, while it does not on Android 11.

Body:
Finally, after researching a lot, I found a solution. All you need is this:-

While Creating Notification Channel, create different channels for Silent Notification, Custom Sound Notification, etc.

  // The custom sound file name you want
  val soundName = "beep"
  val soundUri = Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://${packageName}/raw/${soundName}")

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      val importance = NotificationManager.IMPORTANCE_HIGH
      val audioAttributes = AudioAttributes.Builder()
          .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
          .setUsage(AudioAttributes.USAGE_NOTIFICATION)
          .build()

      // Here The CHANNEL_ID is the main thing for creating a channel. Use this same CHANNEL_ID in Notification Builder Also.
      val channel = NotificationChannel(CHANNEL_ID, getString(R.string.app_name), importance).apply {
          description = getString(R.string.app_name)
          setSound(null, audioAttributes) // Give Null if you want silent notification
          // setSound(soundUri, audioAttributes)
      }
      notificationManager.createNotificationChannel(channel)
  }

Notification Builder:-

        // Here The CHANNEL_ID needs to be same like the above created channel id. Because it defines how notification sound come.
    val builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(smallIcon)

    with(notificationManager) {
        notify(notificationId, builder.build())
    }


问:
How to simulate click to specific background window (not in focus)?
I am trying to click a window that is in the background (without focus), without moving the mouse cursor (so I can continue to use my screen and mouse normally).

Using Python win32gui the application isn't registering the click. Using AutoHotkey I couldn't find a way to simulate the click (I only managed to write to it because I didn't find anything like win.click or ahk.controlclick). Can I do it with AutoHotkey or is there anything else I can use?

The code which doesn't work:

```<code>def click(x, y):
    hWnd = win32gui.FindWindow(None, "Spotify")
    lParam = win32api.MAKELONG(x, y)

    hWnd1= win32gui.FindWindowEx(hWnd, None, None, None)
    win32gui.SendMessage(hWnd1, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
    win32gui.SendMessage(hWnd1, win32con.WM_LBUTTONUP, None, lParam)
</code>```

答:
A trivial approach that is not very robust, is using PyAutoGUI
you just need to

install it using pip install pyautogui or if you are using poetry, you can install by using the following command poetry add pyautogui

then use the function pyautogui.click(x, y) and pass int values to them

you can also move the cursor to pyautogui.moveTo(x,y) absolute movement or you can move it relative to the current cursor position by using pyautogui.move(x, y)

A more robust approach is to use an image of where you want to move the mouse and use pyautogui.locateOnScreen('path_to_image')

Body:
I am trying to click a window that is in the background (without focus), without moving the mouse cursor (so I can continue to use my screen and mouse normally).

Using Python win32gui the application isn't registering the click. Using AutoHotkey I couldn't find a way to simulate the click (I only managed to write to it because I didn't find anything like win.click or ahk.controlclick). Can I do it with AutoHotkey or is there anything else I can use?

The code which doesn't work:

def click(x, y):
    hWnd = win32gui.FindWindow(None, "Spotify")
    lParam = win32api.MAKELONG(x, y)

    hWnd1= win32gui.FindWindowEx(hWnd, None, None, None)
    win32gui.SendMessage(hWnd1, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
    win32gui.SendMessage(hWnd1, win32con.WM_LBUTTONUP, None, lParam)


问:
Calling async event in flutter_bloc
I am trying to fetch data from API as soon as the flutter app loads but I am unable to achieve so

```<code>class MarketBloc extends Bloc<MarketListEvent, MarketListState> {
  MarketBloc() : super(MarketLoading()) {
    on<MarketSelectEvent>((event, emit) async {
      emit(MarketLoading());
      final data = await ApiCall().getData(event.value!);
      globalData = data;
      emit(MarketDataFetched(marDat: globalData.data, dealType: event.value));
    });

  }
}
</code>```

I have called MarketLoading state as the initial state and I want to call MarketSelectEvent just after that but in the current code, action is required to do so and i want to achieve it without any action.

答:
You have 2 options:

add an event from the UI as soon you instantiate the MarketBloc

```<code>  MarketBloc()..add(MarketSelectEvent())
</code>```

add an event in the initialization code

```<code>  MarketBloc() : super(MarketLoading()) {
    add(MarketSelectEvent());
  }
</code>```

Title: Calling async event in flutter_bloc

Body:
I am trying to fetch data from API as soon as the flutter app loads but I am unable to achieve so

class MarketBloc extends Bloc<MarketListEvent, MarketListState> {
  MarketBloc() : super(MarketLoading()) {
    on<MarketSelectEvent>((event, emit) async {
      emit(MarketLoading());
      final data = await ApiCall().getData(event.value!);
      globalData = data;
      emit(MarketDataFetched(marDat: globalData.data, dealType: event.value));
    });

  }
}

I have called MarketLoading state as the initial state and I want to call MarketSelectEvent just after that but in the current code, action is required to do so and i want to achieve it without any action.

Body:
You have 2 options:

add an event from the UI as soon you instantiate the MarketBloc

  MarketBloc()..add(MarketSelectEvent())

add an event in the initialization code

  MarketBloc() : super(MarketLoading()) {
    add(MarketSelectEvent());
  }


问:
Returning the word with multiple instances of a character using regex
I tried finding a solution by using only re.compile and findall but I can't seem to get it. I am looking to return the string which has multiple instances of any character inside (e.g macdonalds kfc burgerking) and the result should be

[(macdonalds, ad),(burgerking,rg)]

I tried the code

p = re.compile(r`\w+(.)\1{1,}\w+`)

p.findall('macdonalds kfc burgerking')

but it could only search for instances that concur simultaneously. (e.g Baaaabaaa sheep)

答:
With Python re, you can use

import re
rx = re.compile(r'\w*?(\w)\w*\1\w*')
rx_extract_dupe = re.compile(r'(.)(?=.*\1)')
text = 'macdonalds kfc burgerking'
matches = rx.finditer(text)
print( [(x.group(), "".join(rx_extract_dupe.findall(x.group()))) for x in matches] )
# => [('macdonalds', 'ad'), ('burgerking', 'rg')]
```
<p>See this Python demo. With <code>\w*?(\w)\w*\1\w*</code> regex, you extract all words with at least one char repetition, and then <code>(.)(?=.*\1)</code> with <code>.findall()</code> applied to the match gets the list of duplicated chars.</p>
<p>If you install the PyPi regex library you can use</p>
<pre class="lang-py prettyprint-override"><code>import regex
rx = regex.compile(r'(?:\w*?(\w)(?=\w*\1))+\w*')
text = 'macdonalds kfc burgerking'
print( [(x.group(), "".join(x.captures(1)) ) for x in rx.finditer(text)] )
# => [('macdonalds', 'ad'), ('burgerking', 'rg')]
</code>```

See the Python demo.

Details:

(?:\w*?(\w)(?=\w*\1))+ - one or more sequences of

\w*?  - zero or more word chars, as few as possible

(\w) - Group 1: any single word char

(?=\w*\1) - that is followed with zero or more word chars and then the same word char as captured in Group 1

\w* - any zero or more word chars.

The x.group()  contains a match value and x.captures(1) contains all occurrences of the repeated characters in a word.

Body:
With Python re, you can use

import re
rx = re.compile(r'\w*?(\w)\w*\1\w*')
rx_extract_dupe = re.compile(r'(.)(?=.*\1)')
text = 'macdonalds kfc burgerking'
matches = rx.finditer(text)
print( [(x.group(), "".join(rx_extract_dupe.findall(x.group()))) for x in matches] )
# => [('macdonalds', 'ad'), ('burgerking', 'rg')]

See this Python demo. With \w*?(\w)\w*\1\w* regex, you extract all words with at least one char repetition, and then (.)(?=.*\1) with .findall() applied to the match gets the list of duplicated chars.

If you install the PyPi regex library you can use

import regex
rx = regex.compile(r'(?:\w*?(\w)(?=\w*\1))+\w*')
text = 'macdonalds kfc burgerking'
print( [(x.group(), "".join(x.captures(1)) ) for x in rx.finditer(text)] )
# => [('macdonalds', 'ad'), ('burgerking', 'rg')]

See the Python demo.

Details:

(?:\w*?(\w)(?=\w*\1))+ - one or more sequences of

\w*?  - zero or more word chars, as few as possible

(\w) - Group 1: any single word char

(?=\w*\1) - that is followed with zero or more word chars and then the same word char as captured in Group 1

\w* - any zero or more word chars.

The x.group()  contains a match value and x.captures(1) contains all occurrences of the repeated characters in a word.


问:
Should state only be in a root component?
This may be considered as an opinionated question, but I was wondering if it is best to keep state at the root of the component.

For example, suppose have a form. The form has sections that correspond to different information that is requested to a user. The parent form contains all the state to be filled up and it passes it down to the sections

```<code>export default function Form() {
    const [state1, setState1] = useState();
    const [state2, setState2] = useState();
    const [state3, setState3] = useState();
    return (
        <>
            <Section1 state={state1} setState={setState1} />
            <Section2 state={state2} setState={setState2} />
            <Section3 state={state3} setState={setState3} />
        </>
    )
}
</code>```

Now let's say for some reason, <Section2 /> needs some sort of loading state

```<code>export default function Section2() {
    return (
        <div>
            {!loading ? ....} //do something with loading
        </div>
    )
}
</code>```

Should I put this loading state and its handle function up to the <Form /> parent even though the parent doesn't have any use for this state?

If I should place this state in the parent, and <Section2 /> updates it, doesn't that mean that every other section will re-render as well even though only <Section2 /> needs this? Does that have impact on performance?

I've been reading through best react design patterns and some say it is best to keep the state and handle functions at the root component. A concept of stateless and stateful components, or smart and dumb.

答:
Should I put this loading state and its handle function up to the  parent even though the parent doesn't have any use for this state?

No. If the parent doesn't use it, it is better to define the state in child component and if the child component share same state value, you can use useContext to use the state as a global state. This will only rerender component that use useContext when the context value change and to prevent some rerender on some component you can use React.memo or useMemo.

If I should place this state in the parent, and  updates it, doesn't that mean that every other section will re-render as well even though only  needs this? Does that have impact on performance?

Yes it will rerender everything including the children components of the Parent.

Body:
This may be considered as an opinionated question, but I was wondering if it is best to keep state at the root of the component.

For example, suppose have a form. The form has sections that correspond to different information that is requested to a user. The parent form contains all the state to be filled up and it passes it down to the sections

export default function Form() {
    const [state1, setState1] = useState();
    const [state2, setState2] = useState();
    const [state3, setState3] = useState();
    return (
        <>
            <Section1 state={state1} setState={setState1} />
            <Section2 state={state2} setState={setState2} />
            <Section3 state={state3} setState={setState3} />
        </>
    )
}

Now let's say for some reason, <Section2 /> needs some sort of loading state

export default function Section2() {
    return (

            {!loading ? ....} //do something with loading

    )
}

Should I put this loading state and its handle function up to the <Form /> parent even though the parent doesn't have any use for this state?

If I should place this state in the parent, and <Section2 /> updates it, doesn't that mean that every other section will re-render as well even though only <Section2 /> needs this? Does that have impact on performance?

I've been reading through best react design patterns and some say it is best to keep the state and handle functions at the root component. A concept of stateless and stateful components, or smart and dumb.


问:
How to make sure background fills the whole flex row which overflows?
How to make sure that background-color fills the whole flex row which overflows to the right? Currently, it only fills a portion of it that fits on the screen.

Here's an example:

main {
  position: relative;
  display: flex;
  flex-direction: column;
  background-color: white;
  overflow-x: scroll;
}

.wrapper {
  display: flex;
  flex-direction: row;
}
.wrapper:hover {
  background-color: rgba(0, 0, 0, 0.5);
}
.content {
  min-width: 150px;
  min-height: 20px;
  padding: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <div class='wrapper'>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
  </div>
  <div class='wrapper'>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
  </div>
</main></code>```

答:
The .wrapper content is overflowing, but it does not overflow
You could remove the overflow-x:scroll from main, and use overflow-x:auto in the .wrapper

Body:
How to make sure that background-color fills the whole flex row which overflows to the right? Currently, it only fills a portion of it that fits on the screen.

Here's an example:

main {
  position: relative;
  display: flex;
  flex-direction: column;
  background-color: white;
  overflow-x: scroll;
}

.wrapper {
  display: flex;
  flex-direction: row;
}
.wrapper:hover {
  background-color: rgba(0, 0, 0, 0.5);
}
.content {
  min-width: 150px;
  min-height: 20px;
  padding: 20px;
}

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content


问:
HTML Object SVG image does not display
I had an HTML Object tag like this:

```<code><object class="someclass" id="someid" type="image/svg+xml" data="/relative/path/to/svg/file.svg">Your browser does not support SVG files, and so your visualization cannot dislpay</object>
</code>```

This displayed my SVG image file fine. However, I wanted to move the SVG image file outside of the website root, so that users that do not have an account cannot see the file. So the data attribute would become a link to an intermediate page, which would construct the path to the SVG image and show it to the browser.

Now I have:

```<code> <object class="someclass" id="someid" type="image/svg+xml" data="/some/intermediate/page?image=/parameter/file.svg">Your browser does not support SVG files, and so your visualization cannot dislpay</object>
</code>```

However, this does not display the image. When I use an Img tag instead, it does display when I right click it and select 'view image'. I tried things such as urlencode the query part of the URL, urlencoding the entire string, replacing the question mark for %3F, switching between Object and Img tags, but it does not seem to work.

Thanks for the help!

答:
Though the OP has solved his problem, I came across a similar error in which the object tag was unable to render the data. The error turned out to be due to the X-Frame-Options, which in some cases is by default set to DENY.

If this is the case, you need to set to the appropriate value to be able to render.

Title: HTML Object SVG image does not display

Body:
I had an HTML Object tag like this:

<object class="someclass" id="someid" type="image/svg+xml" data="/relative/path/to/svg/file.svg">Your browser does not support SVG files, and so your visualization cannot dislpay</object>

This displayed my SVG image file fine. However, I wanted to move the SVG image file outside of the website root, so that users that do not have an account cannot see the file. So the data attribute would become a link to an intermediate page, which would construct the path to the SVG image and show it to the browser.

Now I have:

 <object class="someclass" id="someid" type="image/svg+xml" data="/some/intermediate/page?image=/parameter/file.svg">Your browser does not support SVG files, and so your visualization cannot dislpay</object>

However, this does not display the image. When I use an Img tag instead, it does display when I right click it and select 'view image'. I tried things such as urlencode the query part of the URL, urlencoding the entire string, replacing the question mark for %3F, switching between Object and Img tags, but it does not seem to work.

Thanks for the help!