问:
get positions of true within array of booleans

So in this table,  Each row of the table contains sales data for a product (car, train, or plane) from January through July. Suppose you enter a month and a product into the worksheet. Write a formula that gives the total sales of that product during the given month.
so, in this case, I tried to use array functions in excel 2016, I tried to use the exact function to get positions of "car" in the product column, like this  =exact("car", product)  and by using ctrl shift enter we get values of true and false, now we want to find a position of true values and sum up its corresponding sales in a concrete month,
I am trying to use offset function and match function to find the position of the month but it's hard to find the multiple positions of the car. how can we solve it?

答:
=SUM(FILTER(INDEX(B1:C5,,XMATCH(A8,B1:C1)),A1:A5=A7)) when using Office 365 or
=SUMPRODUCT(MMULT(--(A2:A5=A7),--(B1:C1=A8)),B2:C5) (confirmed with ctrl+shift+enter) for prior versions.

Change the ranges to match your ranges.


来源: stackexchange

问:
g_utf8_collate() returns 0 for two Japanese strings which are not equal
The environment on Linux SLES 15SP2:

```<code>$ egrep 'LANG|LC_' catserver.log_SRP-30932.20220209
export LC_ALL=de_DE.UTF-8
export DB_LANG=de_DE.UTF-8
export LANG=de_DE.UTF-8
</code>```

result of comparing two Japanese strings p1 and p2 with g_utf8_collate() and with strcmp() and the hex representation of the two strings:

```<code>p1: [ゲルハルト・A・リッター] p2: [ゲアハルト・A・リッター] g_utf8_collate(): 0 strcmp(): 1
p1: e382b2e383abe3838fe383abe38388e383bb41e383bbe383aae38383e382bfe383bc
p2: e382b2e382a2e3838fe383abe38388e383bb41e383bbe383aae38383e382bfe383bc
...
p1: [チャールズ・A・ビアード] p2: [ゲルハルト・A・リッター] g_utf8_collate(): 0 strcmp(): 1
p1: e38381e383a3e383bce383abe382bae383bb41e383bbe38393e382a2e383bce38389
p2: e382b2e383abe3838fe383abe38388e383bb41e383bbe383aae38383e382bfe383bc
</code>```

I don't know what these Japanese strings mean. They're from a bibliographic database where our Library Management System is failing due to the above problem with g_utf8_collate() and I've inserted the strcmp() and the hex dump in the tons of C-code to understand the failure.

答:
Background

Look at the pair: only one character is different:

ゲルハルト・A・リッター = Geruharuto A rittā

ゲアハルト・A・リッター = geaharuto A rittā

These are two ways to write the name Gerhard A. Ritter in Katakanas. Japanese speakers do that for the same reason why English speakers would create the name Maria Sharapova although the real name is Мари́я Шара́пова - it is the closest way to write that name in a different system. And sometimes there is not only one way to do so.

In this case both ways to write "Gerhard" can be considered same. However, I cannot imagine a collation that exists which interpretes two entirely different Kanas as same - this cannot be correct.

Now the other pair, which has nothing in common besides the latin A:

チャールズ・A・ビアード = chāruzu A biādo = Charles A. Beard

ゲルハルト・A・リッター = geruharuto A rittā (same as first p1)

Charles also has a japanese article in Wikipedia, so you can see his name exactly written like here. These are two different persons and everything besides ・A・ mismatches - in no way can any collation see these as same - there must be a bigger mistake that happens.

Library wise you just have to expect different writing systems for the same name, especially when wanting to look things up/find them (again), since there's no rule whose name must be written in which writing system. Examples:

Latin letters
Katakana (japanese)
Hebrew
Cyrillic (russian)
Arabic
Greek

Ken Ishii
ケン・イシイ
קן_אישיי
Кен Исии
كين إيشي
Κεν Ίσιι

Michael Schumacher
ミハエル・シューマッハ
מיכאל שומאכר
Михаэ́ль Шума́хер
مايكل شوماخر
Μίχαελ Σουμάχερ

Solution

glib wise there's

a Red Hat ticket describing similar impossible results, and

the question Glib::ustring and Japanese characters along with answers.

Both point out: you cannot have a locale of de_DE.UTF-8 and then collation wise compare non-German input. If you want to use g_utf8_collate() on Katakanas you have to set your locale to e.g. ja_JP.UTF-8.

Your new problem may become: recognize the writing system from the characters and set the locale accordingly. However, this already easily clashes with latin letters being used in many alphabets (English, German, Turkish...).

ContentLicense: CC BY-SA 4.0

Body:
The environment on Linux SLES 15SP2:

$ egrep 'LANG|LC_' catserver.log_SRP-30932.20220209
export LC_ALL=de_DE.UTF-8
export DB_LANG=de_DE.UTF-8
export LANG=de_DE.UTF-8

result of comparing two Japanese strings p1 and p2 with g_utf8_collate() and with strcmp() and the hex representation of the two strings:

p1: [ゲルハルト・A・リッター] p2: [ゲアハルト・A・リッター] g_utf8_collate(): 0 strcmp(): 1
p1: e382b2e383abe3838fe383abe38388e383bb41e383bbe383aae38383e382bfe383bc
p2: e382b2e382a2e3838fe383abe38388e383bb41e383bbe383aae38383e382bfe383bc
...
p1: [チャールズ・A・ビアード] p2: [ゲルハルト・A・リッター] g_utf8_collate(): 0 strcmp(): 1
p1: e38381e383a3e383bce383abe382bae383bb41e383bbe38393e382a2e383bce38389
p2: e382b2e383abe3838fe383abe38388e383bb41e383bbe383aae38383e382bfe383bc

I don't know what these Japanese strings mean. They're from a bibliographic database where our Library Management System is failing due to the above problem with g_utf8_collate() and I've inserted the strcmp() and the hex dump in the tons of C-code to understand the failure.


问:
JSON.stringify is distorting code adding \ inside strings?
I am trying to save local storage info but what happens is I am getting \ added to all the items that are strings I mean as some answers stated it is caused by double stringfy ? issue is my blob action that saves the local storage refuse to handle the it unless is it is stringifed, long story short could this double stringfy needed for the function cause issues later, I have no problem when parsing back but the look of the saved elements looks really weird  ?

//const ls = JSON.stringify(localStorage);
// "id":"\"159e17e9-19b7-453d-8e10-a411c7424586\"
// "groups":"{\"bee7bdc4-d888-46e6-93d7-ed0c\" : :[{\"id\":\"0e6e6426-4d79-4eea-9180-06111dd2a0e3\"}]

const config = {a: 'fdfgdg', b: 2}
console.log(JSON.stringify(config))```

答:
As others have pointed out, things aren't going as planned because you are stringifying localStorage itself, as well as improperly stringifying and parsing your data.

It would be much easier just to save the object directly to localStorage and then retrieve it as needed, without having to fool around with stringifying and parsing. While these methods are necessary, all they accomplish is to convert your data into the format useable by localStorage anyway, but the data itself stays converted, that is, a float 122.55 is converted into a string "122.55" and it stays that way.

Wouldn't it be so much easier if you could directly store the number 122.55 and retrieve it that way also?

Have a look at localDataStorage, where you can transparently set/get any of the following "types": Array, Boolean, Date, Float, Integer, Null, Object or String. It seamlessly converts your data, stores it, and allows you to retrieve it just the way it went it. Store an object and get it back. Store a date and get it back. Store a number or a boolean and get those back.

Examples:

```<code>localDataStorage.set( 'key1', false );
localDataStorage.get( 'key1' );   -->   false (boolean)

localDataStorage.set( 'key2', 122.55 );
localDataStorage.get( 'key2' );   -->   122.55 (float)

var obj = {
    id: '159e17e9-19b7-453d-8e10-a411c7424586',
    groups: '000e17e9-19b7-453d-8e10-a411c7424500'
}
localDataStorage.set( 'key3', obj );
localDataStorage.get( 'key3' );   -->   {id: '159e17e9-19b7-453d-8e10-a411c7424586', groups: '000e17e9-19b7-453d-8e10-a411c7424500'} (object)

localDataStorage.set( 'key4', "this is \"something\"" );
localDataStorage.get( 'key4' );   -->   'this is "something"' (string)
</code>```

All of the conversion work is done in the background for you: just set/get and go.

[DISCLAIMER] I am the author of the utility [/DISCLAIMER]

Body:
As others have pointed out, things aren't going as planned because you are stringifying localStorage itself, as well as improperly stringifying and parsing your data.

It would be much easier just to save the object directly to localStorage and then retrieve it as needed, without having to fool around with stringifying and parsing. While these methods are necessary, all they accomplish is to convert your data into the format useable by localStorage anyway, but the data itself stays converted, that is, a float 122.55 is converted into a string "122.55" and it stays that way.

Wouldn't it be so much easier if you could directly store the number 122.55 and retrieve it that way also?

Have a look at localDataStorage, where you can transparently set/get any of the following "types": Array, Boolean, Date, Float, Integer, Null, Object or String. It seamlessly converts your data, stores it, and allows you to retrieve it just the way it went it. Store an object and get it back. Store a date and get it back. Store a number or a boolean and get those back.

Examples:

localDataStorage.set( 'key1', false );
localDataStorage.get( 'key1' );   -->   false (boolean)

localDataStorage.set( 'key2', 122.55 );
localDataStorage.get( 'key2' );   -->   122.55 (float)

var obj = {
    id: '159e17e9-19b7-453d-8e10-a411c7424586',
    groups: '000e17e9-19b7-453d-8e10-a411c7424500'
}
localDataStorage.set( 'key3', obj );
localDataStorage.get( 'key3' );   -->   {id: '159e17e9-19b7-453d-8e10-a411c7424586', groups: '000e17e9-19b7-453d-8e10-a411c7424500'} (object)

localDataStorage.set( 'key4', "this is \"something\"" );
localDataStorage.get( 'key4' );   -->   'this is "something"' (string)

All of the conversion work is done in the background for you: just set/get and go.

[DISCLAIMER] I am the author of the utility [/DISCLAIMER]


问:
Programmatically styling Android's CheckBox
I got a class which extends Activity and programmatically adding some View items.

```<code>CheckBox checkBox = new CheckBox(this, null, android.R.style.Widget_CompoundButton_Star);
</code>```

I'd like to set some checkBoxes styled as the Android SDK stars. I can't see any check box after I set its style to that Widget_CompoundButton_Star. Although that SDK style apparently works when directly placing in a xml.

Am I missing something here? THX

// As Pragnani said. Using android.R.attr.starStyle instead works.

答:
This is my working solution:</p>
```<code>CheckBox checkBox = new CheckBox(new ContextThemeWrapper(this, R.style.CheckBoxStyle))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I got a class which extends Activity and programmatically adding some View items.

CheckBox checkBox = new CheckBox(this, null, android.R.style.Widget_CompoundButton_Star);

I'd like to set some checkBoxes styled as the Android SDK stars. I can't see any check box after I set its style to that Widget_CompoundButton_Star. Although that SDK style apparently works when directly placing in a xml.

Am I missing something here? THX

// As Pragnani said. Using android.R.attr.starStyle instead works.

Body:
This is my working solution:

CheckBox checkBox = new CheckBox(new ContextThemeWrapper(this, R.style.CheckBoxStyle))


问:
How can I have PHP avoid lazy evaluation?
I have an interesting question about the way PHP evaluates boolean expressions.   When you have, for example,

```<code>$expression = $expression1 and $expression2;
</code>```

or

```<code>if ($expression1 and $expression2)
</code>```

PHP first checks if $expression1 evaluates to true. If this is not the case, then $expression2 is simply skipped to avoid unnecessary calculations.  In a script I am writing, I have:

```<code>if ($validator->valid("title") and $validator->valid("text"))
</code>```

I need to have the second statement ($validator->valid("text")) evaluated even if the first one evaluates to false.  I would like to ask you whether there is some easy way to force PHP to always evaluate both statements. Thank you!

答:
```<code>$isValidTitle = $validator->valid("title");
$isValidText = $validator->valid("text");
if($isValidTitle && $isValidText)
{
    ...
}
</code>```

Will that suit?

LastEditorDisplayName: Eddie

ContentLicense: CC BY-SA 2.5

Body:
I have an interesting question about the way PHP evaluates boolean expressions.   When you have, for example,

$expression = $expression1 and $expression2;

or

if ($expression1 and $expression2)

PHP first checks if $expression1 evaluates to true. If this is not the case, then $expression2 is simply skipped to avoid unnecessary calculations.  In a script I am writing, I have:

if ($validator->valid("title") and $validator->valid("text"))

I need to have the second statement ($validator->valid("text")) evaluated even if the first one evaluates to false.  I would like to ask you whether there is some easy way to force PHP to always evaluate both statements. Thank you!

Body:
$isValidTitle = $validator->valid("title");
$isValidText = $validator->valid("text");
if($isValidTitle && $isValidText)
{
    ...
}

Will that suit?

OwnerDisplayName: Kalium


问:
does gobject depend on glib or glib depend on gobject?
I read a wikipedia page on gobject where it says,

Depending only on GLib and libc, GObject is a cornerstone of GNOME and is used throughout GTK, Pango, ATK

but this GLib API reference page lists GObject in its dependencies and this GObject API reference page lists GLib in its dependencies

If what said on wikipedia page is true,
How are they in each others dependencies? shouldn't it be only present under GObject's dependencies and not under GLib dependencies?

I'm confused about what depends on what or is it the case that they both depend on each other? if yes, how?

答:
This is a quirk of the documentation website: it currently conflates dependencies and related libraries. Since I'm maintaining both the tool that generates the documentation website and the website itself, I'll try and fix this as soon as I can.

To answer your question: the GLib project is composed by multiple C libraries:

GLib, a low level C library of useful data types and cross-platform API, useful when writing C code that needs to be portable to various platforms and architectures

GObject, an object oriented type system written in C

GIO, a set of interfaces and classes that provide, among other things, a complex set of primitives for accessing file systems and their contents; a low level networking interface; an IPC interface based on D-Bus; and various other high level API for writing complex applications

GModule, a cross-platform wrapper around loading shared modules at run time and resolving their symbols

All of these libraries are part of GLib.

On a lower level, the GLib C library sits below every other one, with GObject depending on GLib and GModule; and GIO depending on GObject.


问:
How to use basic deleteview
I start use DeleteView of django.views.generic.

However I am still confused about DeleteView

Document says you don't need to do anything in DeleteView apart from UpdateView,CreateView

So,,,,is this correct??

It doesn't delete the item.

in urls.py

```<code>path('preaction/<int:pk>/delete', PreActionDeleteView.as_view(),
     name="pre-action-delete"),
</code>```

in views.py

```<code>class PreActionDeleteView(LoginRequiredMixin, DeleteView):
    model = PreAction
    success_url = reverse_lazy("pre-action-list")

    def delete(self, request, *args, **kwargs):
        success_url = self.get_success_url()
        messages_text = "deleted"
        messages.success(self.request, messages_text)
        return HttpResponseRedirect(success_url)
</code>```

答:
Document says you don't need to do anything in DeleteView apart from

Since you are overriding delete() method, you have to delete the specified object manually which in you case is just to call self.object.delete():

```<code>def delete(self, request, *args, **kwargs):
    self.object = self.get_object()
    success_url = self.get_success_url()
    self.object.delete()

    messages_text = "deleted"
    messages.success(self.request, messages_text)
    return HttpResponseRedirect(success_url)
</code>```

To get more information on how things get handled, see this well-structured flow diagram.

Title: How to use basic deleteview

Body:
I start use DeleteView of django.views.generic.

However I am still confused about DeleteView

Document says you don't need to do anything in DeleteView apart from UpdateView,CreateView

So,,,,is this correct??

It doesn't delete the item.

in urls.py

path('preaction/<int:pk>/delete', PreActionDeleteView.as_view(),
     name="pre-action-delete"),

in views.py

class PreActionDeleteView(LoginRequiredMixin, DeleteView):
    model = PreAction
    success_url = reverse_lazy("pre-action-list")

    def delete(self, request, *args, **kwargs):
        success_url = self.get_success_url()
        messages_text = "deleted"
        messages.success(self.request, messages_text)
        return HttpResponseRedirect(success_url)

Body:
Document says you don't need to do anything in DeleteView apart from

Since you are overriding delete() method, you have to delete the specified object manually which in you case is just to call self.object.delete():

def delete(self, request, *args, **kwargs):
    self.object = self.get_object()
    success_url = self.get_success_url()
    self.object.delete()

    messages_text = "deleted"
    messages.success(self.request, messages_text)
    return HttpResponseRedirect(success_url)

To get more information on how things get handled, see this well-structured flow diagram.


问:
How To Fix Python Threading Module Problem
In the code below, when I press Button 1, the application does not respond and I cannot use other Button 2.
Threading module was required for this.
I have created Threads for Threadingle main() and process(), but when the program opens and I press Button 1, the application does not respond and I cannot press Button 2.
What's the problem?</p>
```<code>from tkinter import *
import threading

def process():
    while True:
        print("Hello World")
processThread = threading.Thread(target=process)

def main():

    mainWindow = Tk()
    mainWindow.resizable(FALSE, FALSE)

    mainWindow.title("Text")
    mainWindow.geometry("500x250")

    recButton=Button(mainWindow)
    recButton.config(text="Button 1", font=("Arial", "13"), bg="red",fg="white", width="15", command=processThread.run)
    recButton.place(x=15,y=10)

    stopButton=Button(mainWindow)
    stopButton.config(text="Button 2", font=("Calibri", "13"), bg="orange",fg="white", width="15", command="")
    stopButton.place(x=15,y=55)

    textBox = Text(mainWindow, height="14", width="37")
    textBox.place(x=180, y=10)

    mainWindow.mainloop()
mainThread = threading.Thread(target=main)
mainThread.start()
</code>```

答:
use processThread.start to start the thread instead of processThread.run infact processThread.run will just call the process method and which will not return control to your event loop hence application goes wild

command=processThread.start

```<code>from tkinter import *
import threading

def process():
    while True:
        print("Hello World")
processThread = threading.Thread(target=process)

def main():

    mainWindow = Tk()
    mainWindow.resizable(FALSE, FALSE)

    mainWindow.title("Text")
    mainWindow.geometry("500x250")

    recButton=Button(mainWindow)
    recButton.config(text="Button 1", font=("Arial", "13"), bg="red",fg="white", width="15", command=processThread.start)
    recButton.place(x=15,y=10)

    stopButton=Button(mainWindow)
    stopButton.config(text="Button 2", font=("Calibri", "13"), bg="orange",fg="white", width="15", command="")
    stopButton.place(x=15,y=55)

    textBox = Text(mainWindow, height="14", width="37")
    textBox.place(x=180, y=10)

    mainWindow.mainloop()
mainThread = threading.Thread(target=main)
mainThread.start()
</code>```

Modified the above code for start and stop button functionality. Here we are using flag when this is true thread will be running if flag if false the thread will stop. Remember we can't start a stopped thread because of this we have to create new thread.

```<code>import time
from tkinter import *
import threading

flag = True

def printHello():
    global flag
    while flag:
        print("Hello World")
        time.sleep(1)

"""
starts the thread
"""
def startProcess():
    global flag
    flag = True
    processThread = threading.Thread(target=printHello)
    processThread.start()

"""
stops the thread
"""
def stopProcess():
    global flag
    flag = False

def main():
    mainWindow = Tk()
    mainWindow.resizable(FALSE, FALSE)

    mainWindow.title("Text")
    mainWindow.geometry("500x250")

    recButton = Button(mainWindow)
    recButton.config(text="Button 1", font=("Arial", "13"), bg="red", fg="white", width="15",
                     command=startProcess)
    recButton.place(x=15, y=10)

    stopButton = Button(mainWindow)
    stopButton.config(text="Button 2", font=("Calibri", "13"), bg="orange", fg="white", width="15", command=stopProcess)
    stopButton.place(x=15, y=55)

    textBox = Text(mainWindow, height="14", width="37")
    textBox.place(x=180, y=10)

    mainWindow.mainloop()

mainThread = threading.Thread(target=main)
mainThread.start()
</code>```

Body:
In the code below, when I press Button 1, the application does not respond and I cannot use other Button 2.
Threading module was required for this.
I have created Threads for Threadingle main() and process(), but when the program opens and I press Button 1, the application does not respond and I cannot press Button 2.
What's the problem?

from tkinter import *
import threading

def process():
    while True:
        print("Hello World")
processThread = threading.Thread(target=process)

def main():

    mainWindow = Tk()
    mainWindow.resizable(FALSE, FALSE)

    mainWindow.title("Text")
    mainWindow.geometry("500x250")

    recButton=Button(mainWindow)
    recButton.config(text="Button 1", font=("Arial", "13"), bg="red",fg="white", width="15", command=processThread.run)
    recButton.place(x=15,y=10)

    stopButton=Button(mainWindow)
    stopButton.config(text="Button 2", font=("Calibri", "13"), bg="orange",fg="white", width="15", command="")
    stopButton.place(x=15,y=55)

    textBox = Text(mainWindow, height="14", width="37")
    textBox.place(x=180, y=10)

    mainWindow.mainloop()
mainThread = threading.Thread(target=main)
mainThread.start()

Body:
use processThread.start to start the thread instead of processThread.run infact processThread.run will just call the process method and which will not return control to your event loop hence application goes wild

command=processThread.start

from tkinter import *
import threading

def process():
    while True:
        print("Hello World")
processThread = threading.Thread(target=process)

def main():

    mainWindow = Tk()
    mainWindow.resizable(FALSE, FALSE)

    mainWindow.title("Text")
    mainWindow.geometry("500x250")

    recButton=Button(mainWindow)
    recButton.config(text="Button 1", font=("Arial", "13"), bg="red",fg="white", width="15", command=processThread.start)
    recButton.place(x=15,y=10)

    stopButton=Button(mainWindow)
    stopButton.config(text="Button 2", font=("Calibri", "13"), bg="orange",fg="white", width="15", command="")
    stopButton.place(x=15,y=55)

    textBox = Text(mainWindow, height="14", width="37")
    textBox.place(x=180, y=10)

    mainWindow.mainloop()
mainThread = threading.Thread(target=main)
mainThread.start()

Modified the above code for start and stop button functionality. Here we are using flag when this is true thread will be running if flag if false the thread will stop. Remember we can't start a stopped thread because of this we have to create new thread.

import time
from tkinter import *
import threading

flag = True

def printHello():
    global flag
    while flag:
        print("Hello World")
        time.sleep(1)

"""
starts the thread
"""
def startProcess():
    global flag
    flag = True
    processThread = threading.Thread(target=printHello)
    processThread.start()

"""
stops the thread
"""
def stopProcess():
    global flag
    flag = False

def main():
    mainWindow = Tk()
    mainWindow.resizable(FALSE, FALSE)

    mainWindow.title("Text")
    mainWindow.geometry("500x250")

    recButton = Button(mainWindow)
    recButton.config(text="Button 1", font=("Arial", "13"), bg="red", fg="white", width="15",
                     command=startProcess)
    recButton.place(x=15, y=10)

    stopButton = Button(mainWindow)
    stopButton.config(text="Button 2", font=("Calibri", "13"), bg="orange", fg="white", width="15", command=stopProcess)
    stopButton.place(x=15, y=55)

    textBox = Text(mainWindow, height="14", width="37")
    textBox.place(x=180, y=10)

    mainWindow.mainloop()

mainThread = threading.Thread(target=main)
mainThread.start()


问:
Using swap function does not produce expected result
What am I doing wrong? I would like to understand how I could get the function to swap the numbers.</p>
```<code>void findsmallest(int* a, int* b, int* c)
{

    if(a > b)
        swap(a, b);
    if(b > c)
        swap(b, c);
    if (a > c)
        swap(a, c);

}

int main()
{

    int a,b,c;
    int smallest, middle, last;
    cin >> a >> b >> c;
    findsmallest(a, b, c);
    return 0;

}
</code>```

答:
```<code>void findsmallest(int* a, int* b, int* c)
{
    if (*a > *b)
        swap(*a, *b);
    if (*a > *c)
        swap(*a, *c);
    if (*b > *c)
        swap(*b, *c);
}

int main()
{
    int a, b, c;
    cin >> a >> b >> c;
    findsmallest(&a, &b, &c);
    return 0;
}
</code>```

because swap use references, not pointers, then u must give an object, not pointer to object
the operand * depointered, operand & take a point of object

Body:
What am I doing wrong? I would like to understand how I could get the function to swap the numbers.

void findsmallest(int* a, int* b, int* c)
{

    if(a > b)
        swap(a, b);
    if(b > c)
        swap(b, c);
    if (a > c)
        swap(a, c);

}

int main()
{

    int a,b,c;
    int smallest, middle, last;
    cin >> a >> b >> c;
    findsmallest(a, b, c);
    return 0;

}

Body:
void findsmallest(int* a, int* b, int* c)
{
    if (*a > *b)
        swap(*a, *b);
    if (*a > *c)
        swap(*a, *c);
    if (*b > *c)
        swap(*b, *c);
}

int main()
{
    int a, b, c;
    cin >> a >> b >> c;
    findsmallest(&a, &b, &c);
    return 0;
}

because swap use references, not pointers, then u must give an object, not pointer to object
the operand * depointered, operand & take a point of object


问:
Programmatically Connecting a GitHub repo to a Google Cloud Project
I'm working on a Terraform project that will set up all the GCP resources needed for a large project spanning multiple GitHub repos. My goal is to be able to recreate the cloud infrastructure from scratch completely with Terraform.

The issue I'm running into is in order to setup build triggers with Terraform within GCP, the GitHub repo that is setting off the trigger first needs to be connected. Currently, I've only been able to do that manually via the Google Cloud Build dashboard. I'm not sure if this is possible via Terraform or with a script but I'm looking for any solution I can automate this with. Once the projects are connected updating everything with Terraform is working fine.

TLDR; How can I programmatically connect a GitHub project with a GCP project instead of using the dashboard?

答:
Currently there is no way to programmatically connect a GitHub repo to a Google Cloud Project. This must be done manually via Google Cloud.

My workaround is to manually connect an "admin" project, build containers and save them to that project's artifact registry, and then deploy the containers from the registry in the programmatically generated project.


问:
Flutter Build Error: Process 'command 'E:\Flutter Apps\flutter\bin\flutter.bat'' finished with non-zero exit value 1
I got this error when I try to generate a signed apk in the android studio of my flutter app - Process 'command 'E:\Flutter Apps\flutter\bin\flutter.bat'' finished with non-zero exit value 1

I am able to run the app in both emulator and on my device but this error shows up only when I try to build a signed apk.

```<code>flutter doctor
[√] Flutter (Channel dev, v1.2.0, on Microsoft Windows [Version 10.0.17763.253], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[√] Android Studio (version 3.3)
[√] VS Code (version 1.30.2)
[√] Connected device (1 available)

• No issues found!

</code>```

Any way to fix this?

Tried flutter clean

android studio Build > clean project and rebuild project(same error)

I am doing Build > Generated signed apk > apk > release > V1(Jar signature) > Finish to build the app

答:
Go to your root directory of the flutter project by using the cmd command.

write the command flutter clean, then from your android get dependencies to rebuild the cleaned.

if not solved,  go to your pubspec.yaml and check your flutter asset indentation. eg

```<code>flutter:

  uses-material-design: true

  assets:

   - images/momo.jpg
</code>```

it works for me absolutely.

Body:
I got this error when I try to generate a signed apk in the android studio of my flutter app - Process 'command 'E:\Flutter Apps\flutter\bin\flutter.bat'' finished with non-zero exit value 1

I am able to run the app in both emulator and on my device but this error shows up only when I try to build a signed apk.

flutter doctor
[√] Flutter (Channel dev, v1.2.0, on Microsoft Windows [Version 10.0.17763.253], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[√] Android Studio (version 3.3)
[√] VS Code (version 1.30.2)
[√] Connected device (1 available)

• No issues found!

Any way to fix this?

Tried flutter clean

android studio Build > clean project and rebuild project(same error)

I am doing Build > Generated signed apk > apk > release > V1(Jar signature) > Finish to build the app

Body:
Go to your root directory of the flutter project by using the cmd command.

write the command flutter clean, then from your android get dependencies to rebuild the cleaned.

if not solved,  go to your pubspec.yaml and check your flutter asset indentation. eg

flutter:

  uses-material-design: true

  assets:

   - images/momo.jpg

it works for me absolutely.


问:
React Hooks useState() with Object
What is the correct way of updating state, in a nested object, in React with Hooks?

```<code>export Example = () => {
  const [exampleState, setExampleState] = useState(
  {masterField: {
        fieldOne: "a",
        fieldTwo: {
           fieldTwoOne: "b"
           fieldTwoTwo: "c"
           }
        }
   })
</code>```

How would one use setExampleState to update exampleState to a (appending an field)?

```<code>const a = {
masterField: {
        fieldOne: "a",
        fieldTwo: {
           fieldTwoOne: "b",
           fieldTwoTwo: "c"
           }
        },
  masterField2: {
        fieldOne: "c",
        fieldTwo: {
           fieldTwoOne: "d",
           fieldTwoTwo: "e"
           }
        },
   }
}

</code>```

b (Changing values)?

```<code>const b = {masterField: {
        fieldOne: "e",
        fieldTwo: {
           fieldTwoOne: "f"
           fieldTwoTwo: "g"
           }
        }
   })
</code>```

答:
In 2022

If you are looking for the same functionality as this.setState ( came from the class components ) in functional components then this is the answer that helps you a lot.

For Example

You have a state like below and want to update the specific field only from the whole state then you need to use the object destructing every time and sometimes it will be irritating.

```<code>const [state, setState] = useState({first: 1, second: 2});

// results will be state = {first: 3} instead of {first: 3, second: 2}
setState({first: 3})

// To resolve that you need to use object destructing every time
// results will be state = {first: 3, second: 2}
setState(prev => ({...prev, first: 3}))
</code>```

To solve that I came up with the useReducer approach. Please check useReducer.

const stateReducer = (state, action) => ({
  ...state,
  ...(typeof action === 'function' ? action(state) : action),
});
```
```const [state, setState] = useReducer(stateReducer, {first: 1, second: 2});

// results will be state = {first: 3, second: 2}
setState({first: 3})

// you can also access the previous state callback if you want
// results will remain same, state = {first: 3, second: 2}
setState(prev => ({...prev, first: 3}))
```
<p>You can store that <code>stateReducer</code> in <code>utils</code> files and import it in every file if you want.</p>
<p>Here is the <code>custom hook</code> if you want.</p>
```import React from 'react';

export const stateReducer = (state, action) => ({
  ...state,
  ...(typeof action === 'function' ? action(state) : action),
});

const useReducer = (initial, lazyInitializer = null) => {
  const [state, setState] = React.useReducer(stateReducer, initial, init =>
    lazyInitializer ? lazyInitializer(init) : init
  );

  return [state, setState];
};

export default useReducer;
```
<p><strong>Typescript</strong></p>
```import React, { Dispatch } from "react";

type SetStateAction<S> = S | ((prev: S) => S);

type STATE<R> = [R, Dispatch<SetStateAction<Partial<R>>>];

const stateReducer = (state, action) => ({
  ...state,
  ...(typeof action === "function" ? action(state) : action),
});

const useReducer = <S>(initial, lazyInitializer = null): STATE<S> => {
  const [state, setState] = React.useReducer(stateReducer, initial, (init) =>
    lazyInitializer ? lazyInitializer(init) : init,
  );

  return [state, setState];
};

export default useReducer;
```

Title: React Hooks useState() with Object

Body:
What is the correct way of updating state, in a nested object, in React with Hooks?

export Example = () => {
  const [exampleState, setExampleState] = useState(
  {masterField: {
        fieldOne: "a",
        fieldTwo: {
           fieldTwoOne: "b"
           fieldTwoTwo: "c"
           }
        }
   })

How would one use setExampleState to update exampleState to a (appending an field)?

const a = {
masterField: {
        fieldOne: "a",
        fieldTwo: {
           fieldTwoOne: "b",
           fieldTwoTwo: "c"
           }
        },
  masterField2: {
        fieldOne: "c",
        fieldTwo: {
           fieldTwoOne: "d",
           fieldTwoTwo: "e"
           }
        },
   }
}

b (Changing values)?

const b = {masterField: {
        fieldOne: "e",
        fieldTwo: {
           fieldTwoOne: "f"
           fieldTwoTwo: "g"
           }
        }
   })

Body:
In 2022

If you are looking for the same functionality as this.setState ( came from the class components ) in functional components then this is the answer that helps you a lot.

For Example

You have a state like below and want to update the specific field only from the whole state then you need to use the object destructing every time and sometimes it will be irritating.

const [state, setState] = useState({first: 1, second: 2});

// results will be state = {first: 3} instead of {first: 3, second: 2}
setState({first: 3})

// To resolve that you need to use object destructing every time
// results will be state = {first: 3, second: 2}
setState(prev => ({...prev, first: 3}))

To solve that I came up with the useReducer approach. Please check useReducer.

const stateReducer = (state, action) => ({
  ...state,
  ...(typeof action === 'function' ? action(state) : action),
});

const [state, setState] = useReducer(stateReducer, {first: 1, second: 2});

// results will be state = {first: 3, second: 2}
setState({first: 3})

// you can also access the previous state callback if you want
// results will remain same, state = {first: 3, second: 2}
setState(prev => ({...prev, first: 3}))

You can store that stateReducer in utils files and import it in every file if you want.

Here is the custom hook if you want.

import React from 'react';

export const stateReducer = (state, action) => ({
  ...state,
  ...(typeof action === 'function' ? action(state) : action),
});

const useReducer = (initial, lazyInitializer = null) => {
  const [state, setState] = React.useReducer(stateReducer, initial, init =>
    lazyInitializer ? lazyInitializer(init) : init
  );

  return [state, setState];
};

export default useReducer;

Typescript

import React, { Dispatch } from "react";

type SetStateAction<S> = S | ((prev: S) => S);

type STATE<R> = [R, Dispatch<SetStateAction<Partial<R>>>];

const stateReducer = (state, action) => ({
  ...state,
  ...(typeof action === "function" ? action(state) : action),
});

const useReducer = <S>(initial, lazyInitializer = null): STATE<S> => {
  const [state, setState] = React.useReducer(stateReducer, initial, (init) =>
    lazyInitializer ? lazyInitializer(init) : init,
  );

  return [state, setState];
};

export default useReducer;


问:
My button is stuck on the Y/vertical axis
I've messed with the display and position style properties but no matter what I try my element is stuck on the vertical axis.
I copied the CSS code from a button generator website and all works perfectly, I even added a function to it in javascript but I'm completely stuck on positioning it.
I'm only a few weeks into self-teaching myself to code and at the moment javascript is my strong point but obviously, CSS and HTML come in handy too. Any help is appreciated.

```<code>#startButton {
    box-shadow: 0px 0px 12px 2px #3dc21b;
    background:linear-gradient(to bottom, #44c767 5%, #5cbf2a 100%);
    background-color:#44c767;
    border-radius:28px;
    border:1px solid #18ab29;
    display:inline-block;
    cursor:pointer;
    color:#ffffff;
    font-family:Verdana;
    font-size:18px;
    padding:16px 31px;
    text-decoration:none;
    text-shadow:0px 1px 0px #2f6627;
    position: relative;
    top: 50%;
    left: calc(50% - 30px);
}
.startButton:hover {
    background:linear-gradient(to bottom, #5cbf2a 5%, #44c767 100%);
    background-color:#5cbf2a;
}
.startButton:active {
    position:relative;
    top:1px;
}
</code>```

I have the element 'on its own in HTML if that makes any sense, it's not in its own div or head or body. I'm not sure if that makes a difference though.
Thanks!

Edit: I've got as far as figuring out the elements don't just overlap like I thought. I've learnt my problem is that the 'space' for the button element is stuck below the canvas. I now need a way to overlap these elements.

答:
The reason is that the parent element (body in your case) does not have a static height.

Therefore you can add a parent element with static height and wrap your #startButton.

Edit your html:

  <button id="startButton"> #Startbutton </button>

```
<p>Add static height to the parent element (e.g. <code>300px</code>):</p>
<pre class="lang-css prettyprint-override"><code>.parent {
  height: 300px;
}
</code>```

Fiddle: https://jsfiddle.net/kongallis/chqn18us/6/

Refer also to: https://stackoverflow.com/questions/9765402/why-is-is-top50-in-css-not-working#:~:text=To%20answer%20your%20question%20why,a%20unit%20other%20than%20percent.

Body:
I've messed with the display and position style properties but no matter what I try my element is stuck on the vertical axis.
I copied the CSS code from a button generator website and all works perfectly, I even added a function to it in javascript but I'm completely stuck on positioning it.
I'm only a few weeks into self-teaching myself to code and at the moment javascript is my strong point but obviously, CSS and HTML come in handy too. Any help is appreciated.

#startButton {
    box-shadow: 0px 0px 12px 2px #3dc21b;
    background:linear-gradient(to bottom, #44c767 5%, #5cbf2a 100%);
    background-color:#44c767;
    border-radius:28px;
    border:1px solid #18ab29;
    display:inline-block;
    cursor:pointer;
    color:#ffffff;
    font-family:Verdana;
    font-size:18px;
    padding:16px 31px;
    text-decoration:none;
    text-shadow:0px 1px 0px #2f6627;
    position: relative;
    top: 50%;
    left: calc(50% - 30px);
}
.startButton:hover {
    background:linear-gradient(to bottom, #5cbf2a 5%, #44c767 100%);
    background-color:#5cbf2a;
}
.startButton:active {
    position:relative;
    top:1px;
}

I have the element 'on its own in HTML if that makes any sense, it's not in its own div or head or body. I'm not sure if that makes a difference though.
Thanks!

Edit: I've got as far as figuring out the elements don't just overlap like I thought. I've learnt my problem is that the 'space' for the button element is stuck below the canvas. I now need a way to overlap these elements.

Body:
The reason is that the parent element (body in your case) does not have a static height.

Therefore you can add a parent element with static height and wrap your #startButton.

Edit your html:

<div class="parent">
  <button id="startButton"> #Startbutton </button>
</div>

Add static height to the parent element (e.g. 300px):

.parent {
  height: 300px;
}

Fiddle: https://jsfiddle.net/kongallis/chqn18us/6/

Refer also to: https://stackoverflow.com/questions/9765402/why-is-is-top50-in-css-not-working#:~:text=To%20answer%20your%20question%20why,a%20unit%20other%20than%20percent.


问:
A method I cannot find in Python official documentation
I was reading python cookbook and came upon this recipe:

If you have a slice instance s, you can get more information about it by looking at its
s.start, s.stop, and s.step attributes, respectively. For example:

>>> a = slice(5, 50, 2)
>>> a.start
5
>>> a.stop
50
>>> a.step
2
>>>
```
<p>In addition, you can map a slice onto a sequence of a specific size by using its indi
ces(size) method. This returns a tuple (start, stop, step) where all values have
been suitably limited to fit within bounds (as to avoid IndexError exceptions when
indexing). For example:</p>
<pre class="lang-sh prettyprint-override"><code>>>> s = 'HelloWorld'
>>> a.indices(len(s))
(5, 10, 2)
>>> for i in range(*a.indices(len(s))):
... print(s[i])
...
W
r
d
</code>```

I looked up indices() method in Python official documentation but couldn't find it. Is the book making a mistake here? If not, what does this method do?

答:
I found the documentation not quite clear, so after understanding what it actually does, I decided to share the explanation in my words:

A Slice object defines start:stop:step values, and is a way to effectively pack those 3 values into a single object (variable):

>>> s = Slice(1, 2)
>>> text[1:2] == text[s]
True
```
<p>As you can see above, a slice is automatically unpacked, using colon <code>:</code> separators. You can't unpack it using comma <code>,</code> separators and need to do it manually like so:</p>
<pre class="lang-py prettyprint-override"><code>>>> s.start, s.stop, s.step
(1, 2, None)
</code>```

Perhaps default values being None is something that should be fixed (default start should be 0, default step should be 1, and you must precise the stop), but it works when slicing, also with literals:

>>> slice(1)
slice(None, 1, None)
>>> "Hello World"[slice(1)]
'H'
>>> "Hello World"[None:1:None]
'H'
```
<p>However, not only you can't unpack a slice using an asterisk, but also <code>range</code> will not work with <code>None</code>:</p>
<pre class="lang-py prettyprint-override"><code>>>> s = slice(10, 20)
>>> range(*s)
Traceback (most recent call last):
  File "<blender_console>", line 1, in <module>
TypeError: range() argument after * must be an iterable, not slice

>>> range(s.start, s.stop, s.step)
Traceback (most recent call last):
  File "<blender_console>", line 1, in <module>
TypeError: 'NoneType' object cannot be interpreted as an integer
</code>```

You need to replace None with default values:

>>> s = slice(13)
>>> args = (s.start or 0, s.stop, 1 if s.step is None else s.step)
>>> args
(0, 13, 1)

>>> args = (s.start or 0, s.stop, s.step or 1)  # step == 0 is invalid anyway
>>> args
(0, 13, 1)

>>> range(*args)
range(0, 13)
```
<p>However, while slicing will automatically clamp values to a valid range, using <code>range</code> object and accessing an element using a single integer index, rather than a slice, can cause an <em>IndexError</em>:</p>
<pre class="lang-py prettyprint-override"><code>>>> text = "Hello World"
>>> s = slice(7, 20)
>>> text[s]
'orld'
>>> for i in range(s.start, s.stop):
...     print(i)
...     print(text[i])
...
7
o
8
r
9
l
10
d
11

Traceback (most recent call last):
  File "<blender_console>", line 3, in <module>
IndexError: string index out of range
</code>```

So using slice together with range() require both manual unpacking and clamping to values in bounds. Both problems are solved with slice.indices():

>>> text = "Hello World"
>>> s = slice(7, 20)
>>> [text[i] for i in range(*s.indices(len(text)))]
['o', 'r', 'l', 'd']
```

slice.indices() expects an argument and doesn't accept float("inf"), so if for some reason you want to resign from clamping, you need to fall back to a previous method or use s.indices(s.stop) if stop is positive (not clamping with negative stop doesn't make sense anyway).

Body:
I was reading python cookbook and came upon this recipe:

If you have a slice instance s, you can get more information about it by looking at its
s.start, s.stop, and s.step attributes, respectively. For example:

>>> a = slice(5, 50, 2)
>>> a.start
5
>>> a.stop
50
>>> a.step
2
>>>

In addition, you can map a slice onto a sequence of a specific size by using its indi
ces(size) method. This returns a tuple (start, stop, step) where all values have
been suitably limited to fit within bounds (as to avoid IndexError exceptions when
indexing). For example:

>>> s = 'HelloWorld'
>>> a.indices(len(s))
(5, 10, 2)
>>> for i in range(*a.indices(len(s))):
... print(s[i])
...
W
r
d

I looked up indices() method in Python official documentation but couldn't find it. Is the book making a mistake here? If not, what does this method do?

Body:
I found the documentation not quite clear, so after understanding what it actually does, I decided to share the explanation in my words:

A Slice object defines start:stop:step values, and is a way to effectively pack those 3 values into a single object (variable):

>>> s = Slice(1, 2)
>>> text[1:2] == text[s]
True

As you can see above, a slice is automatically unpacked, using colon : separators. You can't unpack it using comma , separators and need to do it manually like so:

>>> s.start, s.stop, s.step
(1, 2, None)

Perhaps default values being None is something that should be fixed (default start should be 0, default step should be 1, and you must precise the stop), but it works when slicing, also with literals:

>>> slice(1)
slice(None, 1, None)
>>> "Hello World"[slice(1)]
'H'
>>> "Hello World"[None:1:None]
'H'

However, not only you can't unpack a slice using an asterisk, but also range will not work with None:

>>> s = slice(10, 20)
>>> range(*s)
Traceback (most recent call last):
  File "<blender_console>", line 1, in <module>
TypeError: range() argument after * must be an iterable, not slice

>>> range(s.start, s.stop, s.step)
Traceback (most recent call last):
  File "<blender_console>", line 1, in <module>
TypeError: 'NoneType' object cannot be interpreted as an integer

You need to replace None with default values:

>>> s = slice(13)
>>> args = (s.start or 0, s.stop, 1 if s.step is None else s.step)
>>> args
(0, 13, 1)

>>> args = (s.start or 0, s.stop, s.step or 1)  # step == 0 is invalid anyway
>>> args
(0, 13, 1)

>>> range(*args)
range(0, 13)

However, while slicing will automatically clamp values to a valid range, using range object and accessing an element using a single integer index, rather than a slice, can cause an IndexError:

>>> text = "Hello World"
>>> s = slice(7, 20)
>>> text[s]
'orld'
>>> for i in range(s.start, s.stop):
...     print(i)
...     print(text[i])
...
7
o
8
r
9
l
10
d
11

Traceback (most recent call last):
  File "<blender_console>", line 3, in <module>
IndexError: string index out of range

So using slice together with range() require both manual unpacking and clamping to values in bounds. Both problems are solved with slice.indices():

>>> text = "Hello World"
>>> s = slice(7, 20)
>>> [text[i] for i in range(*s.indices(len(text)))]
['o', 'r', 'l', 'd']

slice.indices() expects an argument and doesn't accept float("inf"), so if for some reason you want to resign from clamping, you need to fall back to a previous method or use s.indices(s.stop) if stop is positive (not clamping with negative stop doesn't make sense anyway).


问:
Discord.js - how do I edit message.embed() statements?
I am making a ping command -
It is very simple to code, but I haven't got the slightest idea how to edit the embed I'm using. Here is my code - I'm using a command handler explaining the exports.run statement.

const Discord = require('discord.js')

exports.run = (bot, message, args) => {
const pingUpdate = new Discord.MessageEmbed()
.setColor('#0099ff')
.setDescription('pinging...')
message.channel.send(pingUpdate);
}

exports.help = {
  name: 'ping'
}
```
<p>I need to edit the ping update embed to make the .description edit to perform this (simple ping calculation)</p>
```message.channel.send('pinging...').then((m) => m.edit(`${m.createdTimestamp - message.createdTimestamp}ms`))
```

This would make the description change from 'pinging...' to 'examplepingms'

Thank you in advance

答:
You don't actually have to create a new embed. You can edit the original:

UPDATE: Per the docs, it is recommended to create new embeds, but you use the original embed to pre-populate the new embed. Then, just update what you need and edit the message with the new embed:

```<code>// the original embed posted during collected.on('end')
const embed = new MessageEmbed()
                    .setColor('0xff4400')
                    .setTitle(`My Awesome Embed`)
                    .setDescription('\u200b')
                    .setAuthor(collected.first().user.username, collected.first().user.displayAvatarURL())
                    .setImage(`https://via.placeholder.com/400x300.png/808080/000000?text=Placeholder`)
                    .setTimestamp(new Date())
                    .setThumbnail('https://via.placeholder.com/200x200.png/808080/000000?text=Placeholder');

// In the original embed, I have a placeholder image that the user
// can replace by posting a new message with the image they want
client.on('messageCreate', async message => {
    // adding image to original embed
    if (message.attachments.size > 0 && !message.author.bot) {
        // get all messages with attachments
        const messages = await client.channels.cache.get('<CHANNEL>').messages.fetch();

        // get the newest message by the user
        const d = messages.filter(msg => msg.embeds.length > 0).filter(m => message.author.username === m.embeds[0].author.name).first();

        // create new embed using original as starter
        const tempEmbed = new MessageEmbed(d.embeds[0])

        // update desired values
        tempEmbed.setImage(message.attachments.first().url);

        // edit/update the message
        d.edit({ embeds: [tempEmbed] });

        // delete the posted image
        message.delete();
    }
});
</code>```

Body:
I am making a ping command -
It is very simple to code, but I haven't got the slightest idea how to edit the embed I'm using. Here is my code - I'm using a command handler explaining the exports.run statement.

const Discord = require('discord.js')

exports.run = (bot, message, args) => {
const pingUpdate = new Discord.MessageEmbed()
.setColor('#0099ff')
.setDescription('pinging...')
message.channel.send(pingUpdate);
}

exports.help = {
  name: 'ping'
}

I need to edit the ping update embed to make the .description edit to perform this (simple ping calculation)

message.channel.send('pinging...').then((m) => m.edit(`${m.createdTimestamp - message.createdTimestamp}ms`))

This would make the description change from 'pinging...' to 'examplepingms'

Thank you in advance

Body:
You don't actually have to create a new embed. You can edit the original:

UPDATE: Per the docs, it is recommended to create new embeds, but you use the original embed to pre-populate the new embed. Then, just update what you need and edit the message with the new embed:

// the original embed posted during collected.on('end')
const embed = new MessageEmbed()
                    .setColor('0xff4400')
                    .setTitle(`My Awesome Embed`)
                    .setDescription('\u200b')
                    .setAuthor(collected.first().user.username, collected.first().user.displayAvatarURL())
                    .setImage(`https://via.placeholder.com/400x300.png/808080/000000?text=Placeholder`)
                    .setTimestamp(new Date())
                    .setThumbnail('https://via.placeholder.com/200x200.png/808080/000000?text=Placeholder');

// In the original embed, I have a placeholder image that the user
// can replace by posting a new message with the image they want
client.on('messageCreate', async message => {
    // adding image to original embed
    if (message.attachments.size > 0 && !message.author.bot) {
        // get all messages with attachments
        const messages = await client.channels.cache.get('<CHANNEL>').messages.fetch();

        // get the newest message by the user
        const d = messages.filter(msg => msg.embeds.length > 0).filter(m => message.author.username === m.embeds[0].author.name).first();

        // create new embed using original as starter
        const tempEmbed = new MessageEmbed(d.embeds[0])

        // update desired values
        tempEmbed.setImage(message.attachments.first().url);

        // edit/update the message
        d.edit({ embeds: [tempEmbed] });

        // delete the posted image
        message.delete();
    }
});


问:
Why is `!!(a||!a)` always true?
I'm a Java rookie and in School we got some homework. I shall explain boolean terms but I don't understand one of them.

The question is

Why is this expression always true?

```<code>!!(a||!a)
</code>```

I understand the part in the brackets but what do the two exclamation marks in front of it?

If the first a = true  --> !a = not true --> !! ( double negation = true?) a = true and the second !a = not true --> !!a = true --> !!!a = not true

and if I'm right , why is this expression alsways true? That beats me.

Could any of you explain that to me?

Thanks for your help!

答:
!!(a||!a)

Using one of the axioms of Boolean Algebra, a double negation cancels out everything.

so it would be equivalent to say (a||!a).

Assuming, we set a = true; many programing languages use lazy evaluation of conditional statements, the conditional statement would evaluate to true and execute whatever was inside the body of the if statement.

If we set a = false , then the right hand side of the conditional statement becomes true... as !a is the inverse of a meaning if a == false, !a == true.

Title: Why is `!!(a||!a)` always true?

Body:
I'm a Java rookie and in School we got some homework. I shall explain boolean terms but I don't understand one of them.

The question is

Why is this expression always true?

!!(a||!a)

I understand the part in the brackets but what do the two exclamation marks in front of it?

If the first a = true  --> !a = not true --> !! ( double negation = true?) a = true and the second !a = not true --> !!a = true --> !!!a = not true

and if I'm right , why is this expression alsways true? That beats me.

Could any of you explain that to me?

Thanks for your help!


问:
Calling a sheet from a menu item
I have a macOS app that has to display a small dialog with some information when the user presses the menu item "Info".

I've tried calling doing this with a .sheet but can't get it to display the sheet. Code:

```<code>@main
struct The_ThingApp: App {
    private let dataModel = DataModel()
    @State var showsAlert = false
    @State private var isShowingSheet = false

    var body: some Scene {
       WindowGroup {
          ContentView()
          .environmentObject(self.dataModel)
       }
       .commands {
            CommandMenu("Info") {
                Button("Get Info") {
                    print("getting info")
                    isShowingSheet.toggle()
                }
                .sheet(isPresented: $isShowingSheet) {
                    VStack {
                        Text("Some stuff to be shown")
                            .font(.title)
                            .padding(50)
                        Button("Dismiss",
                               action: { isShowingSheet.toggle() })
                    }
                }
            }
       }
    }
}
</code>```

How would I display a sheet from a menu item?

However, if a sheet is not the way to do it (I think given the simplicity of what I need to show, it would be it), how would you suggest I do it? I tried creating a new view, like I did with the preferences window, but I can't call it either from the menu.

答:
put the sheet directly on ContentView:

```<code>@main
struct The_ThingApp: App {

    @State private var isShowingSheet = false

    var body: some Scene {
        WindowGroup {
            ContentView()
                // here VV
                .sheet(isPresented: $isShowingSheet) {
                    VStack {
                        Text("Some stuff to be shown")
                            .font(.title)
                            .padding(50)
                        Button("Dismiss",
                               action: { isShowingSheet.toggle() })
                    }
                }
        }

        .commands {
            CommandMenu("Info") {
                Button("Get Info") {
                    print("getting info")
                    isShowingSheet.toggle()
                }
            }
        }
    }
}
</code>```

Title: Calling a sheet from a menu item

Body:
I have a macOS app that has to display a small dialog with some information when the user presses the menu item "Info".

I've tried calling doing this with a .sheet but can't get it to display the sheet. Code:

@main
struct The_ThingApp: App {
    private let dataModel = DataModel()
    @State var showsAlert = false
    @State private var isShowingSheet = false

    var body: some Scene {
       WindowGroup {
          ContentView()
          .environmentObject(self.dataModel)
       }
       .commands {
            CommandMenu("Info") {
                Button("Get Info") {
                    print("getting info")
                    isShowingSheet.toggle()
                }
                .sheet(isPresented: $isShowingSheet) {
                    VStack {
                        Text("Some stuff to be shown")
                            .font(.title)
                            .padding(50)
                        Button("Dismiss",
                               action: { isShowingSheet.toggle() })
                    }
                }
            }
       }
    }
}

How would I display a sheet from a menu item?

However, if a sheet is not the way to do it (I think given the simplicity of what I need to show, it would be it), how would you suggest I do it? I tried creating a new view, like I did with the preferences window, but I can't call it either from the menu.

Body:
put the sheet directly on ContentView:

@main
struct The_ThingApp: App {

    @State private var isShowingSheet = false

    var body: some Scene {
        WindowGroup {
            ContentView()
                // here VV
                .sheet(isPresented: $isShowingSheet) {
                    VStack {
                        Text("Some stuff to be shown")
                            .font(.title)
                            .padding(50)
                        Button("Dismiss",
                               action: { isShowingSheet.toggle() })
                    }
                }
        }

        .commands {
            CommandMenu("Info") {
                Button("Get Info") {
                    print("getting info")
                    isShowingSheet.toggle()
                }
            }
        }
    }
}


问:
Create column from another dataframe with condition
I want to assign the labels in the df1 to df2 depending of df1['MinNum'] and df1['MaxMum']

```<code>df1
    Label                       MinNum  MaxNum
0   Rivière                     0       0
1   Sols minéraux bruts         1       2
2   Sols peu évolués lithiques  3       4
</code>```
```<code>df2
    SOIL_ID
0   0.0
1   1.0
2   2.0
4   4.0
</code>```

The condition is:

```<code>if df1['MinNum'] <= df2['SOIL_ID'] <= df1['MaxNum'] assign df1['Label'] to new label column for df2
</code>```

I want to have this

```<code>    SOIL_ID  label
0   0.0      Rivière
1   1.0      Sols minéraux bruts
2   2.0      Sols minéraux bruts
4   4.0      Sols peu évolués lithiques
</code>```

答:
Probably not the most efficient way but I would create an intermediate DataFrame because df1 is not very easy to use.

df3 = pd.DataFrame(columns=["Sol_ID", "label"])
for i, row in df1.iterrows():
    for j in range(row["MinNum"], row["MaxNum"]+1):
        df3 = df3.append({"Sol_ID": j, "label": row["label"]}, ignore_index=True)
```
<p>Which gives you a proper indexing:</p>
```    Sol_ID  label
0   0   Rivière
1   1   Sols minéraux purs
2   2   Sols minéraux purs
3   3   Sols peu évolués lithiques
4   4   Sols peu évolués lithiques
```
<p>Then you can merge the 2 DataFrames:</p>
<pre class="lang-py prettyprint-override"><code>df2.merge(df3, on="Sol_ID")
</code>```

OUTPUT:

  Sol_ID  label
0   0   Rivière
1   1   Sols minéraux purs
2   2   Sols minéraux purs
3   4   Sols peu évolués lithiques
```

Body:
I want to assign the labels in the df1 to df2 depending of df1['MinNum'] and df1['MaxMum']

df1
    Label                       MinNum  MaxNum
0   Rivière                     0       0
1   Sols minéraux bruts         1       2
2   Sols peu évolués lithiques  3       4

df2
    SOIL_ID
0   0.0
1   1.0
2   2.0
4   4.0

The condition is:

if df1['MinNum'] <= df2['SOIL_ID'] <= df1['MaxNum'] assign df1['Label'] to new label column for df2

I want to have this

    SOIL_ID  label
0   0.0      Rivière
1   1.0      Sols minéraux bruts
2   2.0      Sols minéraux bruts
4   4.0      Sols peu évolués lithiques

Body:
Probably not the most efficient way but I would create an intermediate DataFrame because df1 is not very easy to use.

df3 = pd.DataFrame(columns=["Sol_ID", "label"])
for i, row in df1.iterrows():
    for j in range(row["MinNum"], row["MaxNum"]+1):
        df3 = df3.append({"Sol_ID": j, "label": row["label"]}, ignore_index=True)

Which gives you a proper indexing:

    Sol_ID  label
0   0   Rivière
1   1   Sols minéraux purs
2   2   Sols minéraux purs
3   3   Sols peu évolués lithiques
4   4   Sols peu évolués lithiques

Then you can merge the 2 DataFrames:

df2.merge(df3, on="Sol_ID")

OUTPUT:

  Sol_ID  label
0   0   Rivière
1   1   Sols minéraux purs
2   2   Sols minéraux purs
3   4   Sols peu évolués lithiques


问:
List of List not retaining the contents
so I have a recursive program where I am trying to generate all the permutations of a String. I intend to store the permutations in a list of list called ans.

Every single current permutation is stored in the container list which is used to populate the ans list. I am suspecting , since list is a reference type so maybe I am loosing the values in ans list because the container list is getting manipulated? Am I an idiot

```<code>

import java.util.*;
public class practice_3 {
   static String str="abc";
   static List<List<Character>> ans=new ArrayList<List<Character>>();

public static void permString(ArrayList container )
{
    if(container.size()==str.length())
        {System.out.println(container);

        ans.add(container);
        return;
        }

    for(int i=0;i<str.length();i++)
    {
        if(!container.contains(str.charAt(i)))
        {
            container.add(str.charAt(i));
            permString(container);
            container.remove(container.size()-1);

        }

    }

}
public static void main(String[] args) {

    ArrayList<Character> container=new ArrayList<>();

    permString(container);
    System.out.println(ans);
    System.out.println("container end="+container);

}

}
</code>```

答:
You are correct, as container was passed by reference the changes made in container from point to point reflects within ans (Collection of Collection) as well.

To avoid this, you need to clone / create a new copy of the container at the time of storing into the ans collection. This can be easily achieved by following.

```<code>ans.add(new ArrayList<Character>(container));
</code>```

Title: List of List not retaining the contents

Body:
so I have a recursive program where I am trying to generate all the permutations of a String. I intend to store the permutations in a list of list called ans.

Every single current permutation is stored in the container list which is used to populate the ans list. I am suspecting , since list is a reference type so maybe I am loosing the values in ans list because the container list is getting manipulated? Am I an idiot

import java.util.*;
public class practice_3 {
   static String str="abc";
   static List<List<Character>> ans=new ArrayList<List<Character>>();

public static void permString(ArrayList container )
{
    if(container.size()==str.length())
        {System.out.println(container);

        ans.add(container);
        return;
        }

    for(int i=0;i<str.length();i++)
    {
        if(!container.contains(str.charAt(i)))
        {
            container.add(str.charAt(i));
            permString(container);
            container.remove(container.size()-1);

        }

    }

}
public static void main(String[] args) {

    ArrayList<Character> container=new ArrayList<>();

    permString(container);
    System.out.println(ans);
    System.out.println("container end="+container);

}

}

Body:
You are correct, as container was passed by reference the changes made in container from point to point reflects within ans (Collection of Collection) as well.

To avoid this, you need to clone / create a new copy of the container at the time of storing into the ans collection. This can be easily achieved by following.

ans.add(new ArrayList<Character>(container));


问:
Duplicate Button Baseline from Material UI in header

@material-ui/core - 4.3.1

react - 16.8.6/16.9.0

webpack - 4.38.0/4.39.1

In our project when we have a material ui button in one component, then in a separate component on the same page we use an expansion panel or another type of button we have a second instance of MuiButtonBase imported into the header. This is causing our custom styles to be overwritten and styles to be dumped all together.

We've followed the steps from https://material-ui.com/getting-started/faq/#i-have-several-instances-of-styles-on-the-page

We've also tried the steps found on https://github.com/mui-org/material-ui/issues/15610

Neither of these has fixed this for us. :(

```<code> splitChunks: {
      chunks: 'async',
      minChunks: 2,
      name: 'vendor',
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
        },
      }
    },
  },
</code>```

```<code>import {
  Modal, Button,
} from '@material-ui/core';

() => (
  <Modal open={open}>
          <Button className={classes.cancel} onClick={onCancel}>{cancelText}</Button>
          <Button className={classes.delete} onClick={onConfirm}>{confirmText}</Button>
  </Modal>
);
</code>```

```<code>import {
  ExpansionPanel, ExpansionPanelSummary, ExpansionPanelDetails,
} from '@material-ui/core';

() => (
<ExpansionPanel expanded={expanded}>
        <ExpansionPanelSummary onClick={toggle} className={classes.summary} expandIcon={<ExpandMore />}>
          <span>
            {name}
          </span>
        </ExpansionPanelSummary>
        <ExpansionPanelDetails>
          {children}
        </ExpansionPanelDetails>
      </ExpansionPanel>
);
</code>```

It'd be great if we didn't have two MuiButtonBases causing our styles to be overridden.

答:
I had the same problem. I searched a lot and what fixed it for me was that I changed all imports from @material-ui/core to @mui/material.

Side note: Also not listed, but just wanted to say that the cache rtl and ltr needed to be present on the topest component, and mui recognizes by html dir attribute.

Body:
@material-ui/core - 4.3.1

react - 16.8.6/16.9.0

webpack - 4.38.0/4.39.1

In our project when we have a material ui button in one component, then in a separate component on the same page we use an expansion panel or another type of button we have a second instance of MuiButtonBase imported into the header. This is causing our custom styles to be overwritten and styles to be dumped all together.

We've followed the steps from https://material-ui.com/getting-started/faq/#i-have-several-instances-of-styles-on-the-page

We've also tried the steps found on https://github.com/mui-org/material-ui/issues/15610

Neither of these has fixed this for us. :(

 splitChunks: {
      chunks: 'async',
      minChunks: 2,
      name: 'vendor',
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
        },
      }
    },
  },

import {
  Modal, Button,
} from '@material-ui/core';

() => (
  <Modal open={open}>
          <Button className={classes.cancel} onClick={onCancel}>{cancelText}</Button>
          <Button className={classes.delete} onClick={onConfirm}>{confirmText}</Button>
  </Modal>
);

import {
  ExpansionPanel, ExpansionPanelSummary, ExpansionPanelDetails,
} from '@material-ui/core';

() => (
<ExpansionPanel expanded={expanded}>
        <ExpansionPanelSummary onClick={toggle} className={classes.summary} expandIcon={<ExpandMore />}>

            {name}

        </ExpansionPanelSummary>
        <ExpansionPanelDetails>
          {children}
        </ExpansionPanelDetails>
      </ExpansionPanel>
);

It'd be great if we didn't have two MuiButtonBases causing our styles to be overridden.


问:
Scroll into view in JS
I have an HTML code, having a big table. and  I need to scroll to access all of the rows.

And I made the thead as a sticky tag. because I need this tag everywhere. (position: sticky; top: 0;)

But, when I want to use firstCell.scrollIntoView(); in JavaScript, firstCell will be covered by thead!

You can see the sample in this link

In this example, the Target is the first cell in the Table, and by clicking the button, it has to scroll into view of the Target

but Target will be at the backside of thead

how can I fix this problem?

答:
After scrolling into view, check if the bottom of the head overlaps the top of the target by taking their getBoundingClientRects. If so, call window.scrollBy by the difference.

const headTr = document.querySelector('thead tr');
document.querySelector('button').addEventListener('click', () => {
  const target = document.getElementById('target');
  target.scrollIntoView();
  const diff = target.getBoundingClientRect().top - target.getBoundingClientRect().bottom;
  if (diff < 0) {
    window.scrollBy(0, diff);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button style="position: fixed; top: 5px; right: 5px;">ScrollIntoView (for Target)</button>
<table>
  <thead>
    <tr style='position: sticky; top: 0;'>
      <td>XYZ</td>
      <td>XYZ</td>
      <td>XYZ</td>
      <td>XYZ</td>
      <td>XYZ</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td id=target style="color: red;">Target</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    </tr>
  </tbody>
</table></code>```

Title: Scroll into view in JS

Body:
After scrolling into view, check if the bottom of the head overlaps the top of the target by taking their getBoundingClientRects. If so, call window.scrollBy by the difference.

const headTr = document.querySelector('thead tr');
document.querySelector('button').addEventListener('click', () => {
  const target = document.getElementById('target');
  target.scrollIntoView();
  const diff = target.getBoundingClientRect().top - target.getBoundingClientRect().bottom;
  if (diff < 0) {
    window.scrollBy(0, diff);
  }
});

<button style="position: fixed; top: 5px; right: 5px;">ScrollIntoView (for Target)</button>
<table>
  <thead>
    <tr style='position: sticky; top: 0;'>
      <td>XYZ</td>
      <td>XYZ</td>
      <td>XYZ</td>
      <td>XYZ</td>
      <td>XYZ</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td id=target style="color: red;">Target</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    <tr>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
      <td>abc</td>
    </tr>
    </tr>
  </tbody>
</table>


问:
Split many dataframes by a column, and save as different dataframes
I have many dataframes. I would like to split them based on the values in a column (a factor). Then I would like to store the result of the split in separate data frame that have a specific name.

For the sake of a mrp, consider some generated data,

```<code>for (i in 1:10) {
assign(paste("df_",i,sep = ""), data.frame(x = rep(1,12), y  = c(rep("a",4),rep("b",4),rep("c",4))))
}
</code>```

here we have 10 dfs, df_1, df_2... to df_10. (real data is similar to generated data, but in real data column z is different for each df).

Now, I want to split the dfs by 'y' (column 2).

For 1 df, I can do the following;

```<code>splitdf <- split(df_1,df_1$y)
namessplit <- c("a","b","c")
for (i in 1:length(splitdf)) {
  assign(paste("df_1_",namessplit[[i]],sep = ""),splitdf[[i]])
}
</code>```

While this works for 1 df, how can I do it for all the dfs?

Big thanks in advance!

答:
It is not recommended to create multiple objects in the global env, but if we want to know how to create the objects from a nested list - Loop over the outer list sequence and then in the inner list sequence, paste the corresponding names to assign the extracted inner list element

```<code>lst1 <- lapply(mget(ls(pattern = "^df_\\d+$")), \(x) split(x, x$y))
for(i in seq_along(lst1)) {
   for(j in seq_along(lst1[[i]]))  {
   assign(paste0(names(lst1)[i], "_", names(lst1[[i]][j])), lst1[[i]][[j]])
  }
}
</code>```

-checking for objects created in the global env

```<code>> ls(pattern = "^df_\\d+_[a-z]+$")
 [1] "df_1_a"  "df_1_b"  "df_1_c"  "df_10_a" "df_10_b" "df_10_c" "df_2_a"  "df_2_b"  "df_2_c"  "df_3_a"  "df_3_b"  "df_3_c"  "df_4_a"
[14] "df_4_b"  "df_4_c"  "df_5_a"  "df_5_b"  "df_5_c"  "df_6_a"  "df_6_b"  "df_6_c"  "df_7_a"  "df_7_b"  "df_7_c"  "df_8_a"  "df_8_b"
[27] "df_8_c"  "df_9_a"  "df_9_b"  "df_9_c"
</code>```

Body:
I have many dataframes. I would like to split them based on the values in a column (a factor). Then I would like to store the result of the split in separate data frame that have a specific name.

For the sake of a mrp, consider some generated data,

for (i in 1:10) {
assign(paste("df_",i,sep = ""), data.frame(x = rep(1,12), y  = c(rep("a",4),rep("b",4),rep("c",4))))
}

here we have 10 dfs, df_1, df_2... to df_10. (real data is similar to generated data, but in real data column z is different for each df).

Now, I want to split the dfs by 'y' (column 2).

For 1 df, I can do the following;

splitdf <- split(df_1,df_1$y)
namessplit <- c("a","b","c")
for (i in 1:length(splitdf)) {
  assign(paste("df_1_",namessplit[[i]],sep = ""),splitdf[[i]])
}

While this works for 1 df, how can I do it for all the dfs?

Big thanks in advance!

Body:
It is not recommended to create multiple objects in the global env, but if we want to know how to create the objects from a nested list - Loop over the outer list sequence and then in the inner list sequence, paste the corresponding names to assign the extracted inner list element

lst1 <- lapply(mget(ls(pattern = "^df_\\d+$")), \(x) split(x, x$y))
for(i in seq_along(lst1)) {
   for(j in seq_along(lst1[[i]]))  {
   assign(paste0(names(lst1)[i], "_", names(lst1[[i]][j])), lst1[[i]][[j]])
  }
}

-checking for objects created in the global env

> ls(pattern = "^df_\\d+_[a-z]+$")
 [1] "df_1_a"  "df_1_b"  "df_1_c"  "df_10_a" "df_10_b" "df_10_c" "df_2_a"  "df_2_b"  "df_2_c"  "df_3_a"  "df_3_b"  "df_3_c"  "df_4_a"
[14] "df_4_b"  "df_4_c"  "df_5_a"  "df_5_b"  "df_5_c"  "df_6_a"  "df_6_b"  "df_6_c"  "df_7_a"  "df_7_b"  "df_7_c"  "df_8_a"  "df_8_b"
[27] "df_8_c"  "df_9_a"  "df_9_b"  "df_9_c"


答:
Since the thead has a sticky position, its size doesn't get taken into account when calculating the available space.

A workaround would be using scrollIntoView({ behavior: 'smooth', block: 'end' }) in place of scrollIntoView().

This only works because the height of the thead is equal to the height of the tr, so if it aligns the scroll to the bottom, it's not covered anymore.

Title: Scroll into view in JS

Body:
I have an HTML code, having a big table. and  I need to scroll to access all of the rows.

And I made the thead as a sticky tag. because I need this tag everywhere. (position: sticky; top: 0;)

But, when I want to use firstCell.scrollIntoView(); in JavaScript, firstCell will be covered by thead!

You can see the sample in this link

In this example, the Target is the first cell in the Table, and by clicking the button, it has to scroll into view of the Target

but Target will be at the backside of thead

how can I fix this problem?


问:
Calling a jQuery plugin in a Backbone render method
I have a render method in Backbone that goes basically like this:

```<code>render: function () {
  $.tmpl(this.template, attrs).appendTo(this.el);
  return this;
},
</code>```

which is called from a router action:

```<code>action: function () {
  $('#container').empty();
  $('#container').append(myView.render().el);
},
</code>```

Now, I want to apply a plugin on label elements inside this view. My first thought was to call the plugin inside render:

```<code>render: function () {
  $.tmpl(this.template, attrs).appendTo(this.el);
  this.$('label').inFieldLabels();
  return this;
},
</code>```

but this doesn't work (I'm assuming this is because the element hasn't been added to the DOM yet). It does work if I call the plugin in the router action though:

```<code>action: function () {
  $('#container').empty();
  $('#container').append(myView.render().el);
  myView.$('label').inFieldLabels();
},
</code>```

I'd rather not do this, because the plugin is part of the view, not the router, so it doesn't make sense to be calling it inside the action. Is there a better way to do this?

答:
Beter do it this way:</p>

```<code>action: function () {
    var container = $('#container');

    container.empty();
    myView.render(container);
},

render: function (container) {
    $(this.el)
        .append($.tmpl(this.template, attrs))
        .appendTo(container);
    $('label', this.el).inFieldLabels();
    return this;
},
</code>```

Body:
I have a render method in Backbone that goes basically like this:

render: function () {
  $.tmpl(this.template, attrs).appendTo(this.el);
  return this;
},

which is called from a router action:

action: function () {
  $('#container').empty();
  $('#container').append(myView.render().el);
},

Now, I want to apply a plugin on label elements inside this view. My first thought was to call the plugin inside render:

render: function () {
  $.tmpl(this.template, attrs).appendTo(this.el);
  this.$('label').inFieldLabels();
  return this;
},

but this doesn't work (I'm assuming this is because the element hasn't been added to the DOM yet). It does work if I call the plugin in the router action though:

action: function () {
  $('#container').empty();
  $('#container').append(myView.render().el);
  myView.$('label').inFieldLabels();
},

I'd rather not do this, because the plugin is part of the view, not the router, so it doesn't make sense to be calling it inside the action. Is there a better way to do this?

Body:
Beter do it this way:

action: function () {
    var container = $('#container');

    container.empty();
    myView.render(container);
},

render: function (container) {
    $(this.el)
        .append($.tmpl(this.template, attrs))
        .appendTo(container);
    $('label', this.el).inFieldLabels();
    return this;
},


问:
Not able to use Google fonts in Flutter sliverappbar
I am using Google Fonts in my app. I have successfully done so across my app but for some reason I cannot use it in SliverAppBar. The error I get is:

The constructor being called isn't a const constructor.

My code I am trying to change the font for is:

```<code>SliverAppBar(
          pinned: true,
          snap: false,
          floating: false,
          expandedHeight: 200.0,

          leading: new IconButton(
            color: Colors.black38,
            icon: new Icon(Icons.arrow_back),
            onPressed: () {
              Navigator.pushReplacementNamed(
                  context,
                  '/');
            },
          ),

          backgroundColor: Globals().appBar,
          flexibleSpace: const FlexibleSpaceBar(
            title:
            Text('Inventory', style: GoogleFonts.acme(color: Globals().white_text,fontSize: 20),) ,
            // Text('Inventory'),
            background: FittedBox(fit:BoxFit.cover,child: Image(image:AssetImage('images/bag.jpg'))),
          ),
        ),
</code>```

If I the simple Text box you see in the code  // Text('Inventory'), then I don't have an issue. how do you use Google Fonts in the SliverAppbar?

答:
So, I think that the google_fonts package class doesn't implement a const constructor, because, by default, it's going to do an HTTP Internet request for the font. This means that the font is loaded at RUNTIME, which means it can't be a const. Even if you turn that functionality off with "GoogleFonts.config.allowRuntimeFetching = false;", I don't think the package author intends for you to use it that way; hence no const constructor.

The only workaround for this is to just use the regular method of adding custom fonts without the google_fonts package. This is actually safer, since the font will be baked into your application and can safely be used without Internet. The only drawback would be that it will make your application larger.

Here is a link to the current method of adding custom fonts:

https://docs.flutter.dev/cookbook/design/fonts

Body:
I am using Google Fonts in my app. I have successfully done so across my app but for some reason I cannot use it in SliverAppBar. The error I get is:

The constructor being called isn't a const constructor.

My code I am trying to change the font for is:

SliverAppBar(
          pinned: true,
          snap: false,
          floating: false,
          expandedHeight: 200.0,

          leading: new IconButton(
            color: Colors.black38,
            icon: new Icon(Icons.arrow_back),
            onPressed: () {
              Navigator.pushReplacementNamed(
                  context,
                  '/');
            },
          ),

          backgroundColor: Globals().appBar,
          flexibleSpace: const FlexibleSpaceBar(
            title:
            Text('Inventory', style: GoogleFonts.acme(color: Globals().white_text,fontSize: 20),) ,
            // Text('Inventory'),
            background: FittedBox(fit:BoxFit.cover,child: Image(image:AssetImage('images/bag.jpg'))),
          ),
        ),

If I the simple Text box you see in the code  // Text('Inventory'), then I don't have an issue. how do you use Google Fonts in the SliverAppbar?