问:
Image in Button tkinter
I am having a problem in making a login image to a button. I have succeeded in making the image with a transparent background, but I can't succeed to make the button with transparent background.

I attached a screenshot that shows what I mean. The upper 'login' is a image (with transparent background), the lower is Login button but there is a white background around it. I want to make a button with transparent background.

```<code>self.login_image = Image.open('images/LoginButton.png')
self.login_image = ImageTk.PhotoImage(self.login_image)
self.main_screen_canvas.create_image(700, 300, image=self.login_image)

self.login_button = Button(self.main_screen_canvas, borderwidth=0, image=self.login_image)

self.login_button.place(x=300,y=400)
</code>```

What should I do?

BackgroundImage
LoginButtonImage

答:
Here's how to do what I was suggesting in the comment which uses the technique shown in another answer of mine to simulate a tkinter Button on a Canvas that has a transparent image placed on it (instead of text).

One issue I ran into was that fact that your 2421 × 1210 pixel background image was larger than my screen. To deal with it I added a fitrect() helper function to determine a new smaller size for it that would fit. I wrote it a long time ago, but have found it handy to have around many times (like now). Note that in the code ll and ur refer to the lower-left and upper-right corners of the rectangles involved.

Here's the resulting code:

```<code>from PIL import Image, ImageTk
import tkinter as tk

class CanvasButton:
    """ Create left mouse button clickable canvas image object.

    The x, y coordinates are relative to the top-left corner of the canvas.
    """
    flash_delay = 100  # Milliseconds.

    def __init__(self, canvas, x, y, image_source, command, state=tk.NORMAL):
        self.canvas = canvas

        if isinstance(image_source, str):
            self.btn_image = tk.PhotoImage(file=image_source)
        else:
            self.btn_image = image_source

        self.canvas_btn_img_obj = canvas.create_image(x, y, anchor='nw', state=state,
                                                      image=self.btn_image)
        canvas.tag_bind(self.canvas_btn_img_obj, "<ButtonRelease-1>",
                        lambda event: (self.flash(), command()))

    def flash(self):
        self.set_state(tk.HIDDEN)
        self.canvas.after(self.flash_delay, self.set_state, tk.NORMAL)

    def set_state(self, state):
        """ Change canvas button image's state.

        Normally, image objects are created in state tk.NORMAL. Use value
        tk.DISABLED to make it unresponsive to the mouse, or use tk.HIDDEN to
        make it invisible.
        """
        self.canvas.itemconfigure(self.canvas_btn_img_obj, state=state)

def fitrect(r1_ll_x, r1_ll_y, r1_ur_x, r1_ur_y, r2_ll_x, r2_ll_y, r2_ur_x, r2_ur_y):
    """ Find the largest rectangle that will fit within rectangle r2 that has
        rectangle r1's aspect ratio.

        Note: Either the width or height of the resulting rect will be
              identical to the corresponding dimension of rect r2.
    """
    # Calculate aspect ratios of rects r1 and r2.
    deltax1, deltay1 = (r1_ur_x - r1_ll_x), (r1_ur_y - r1_ll_y)
    deltax2, deltay2 = (r2_ur_x - r2_ll_x), (r2_ur_y - r2_ll_y)
    aspect1, aspect2 = (deltay1 / deltax1), (deltay2 / deltax2)

    # Compute size of resulting rect depending on which aspect ratio is bigger.
    if aspect1 > aspect2:
        result_ll_y, result_ur_y = r2_ll_y, r2_ur_y
        delta = deltay2 / aspect1
        result_ll_x = r2_ll_x + (deltax2 - delta) / 2.0
        result_ur_x = result_ll_x + delta
    else:
        result_ll_x, result_ur_x = r2_ll_x, r2_ur_x
        delta = deltax2 * aspect1
        result_ll_y = r2_ll_y + (deltay2 - delta) / 2.0
        result_ur_y = result_ll_y + delta

    return result_ll_x, result_ll_y, result_ur_x, result_ur_y

def btn_clicked():
    """ Prints to console a message every time the button is clicked """
    print("Button Clicked")

background_image_path = 'background_image.jpg'
button_image_path = 'button_image.png'

root = tk.Tk()
root.update_idletasks()
background_img = Image.open(background_image_path)  # Must use PIL for JPG images.

scrnwidth, scrnheight = root.winfo_screenwidth(), root.winfo_screenheight()
bgrdwidth, bgrdheight = background_img.size
border_width, border_height = 20, 20  # Allow room for window's decorations.

# Determine a background image size that will fit on screen with a border.
bgr_ll_x, bgr_ll_y, bgr_ur_x, bgr_ur_y = fitrect(
                                0, 0, bgrdwidth, bgrdheight,
                                0, 0, scrnwidth-border_width, scrnheight-border_height)
bgr_width, bgr_height = int(bgr_ur_x-bgr_ll_x), int(bgr_ur_y-bgr_ll_y)

# Resize background image to calculated size.
background_img = ImageTk.PhotoImage(background_img.resize((bgr_width, bgr_height)))

# Create Canvas same size as fitted background image.
canvas = tk.Canvas(root, bd=0, highlightthickness=0, width=bgr_width, height=bgr_height)
canvas.pack(fill=tk.BOTH)

# Put background image on Canvas.
background = canvas.create_image(0, 0, anchor='nw', image=background_img)

# Put CanvasButton on Canvas centered at the bottom.
button_img = tk.PhotoImage(file=button_image_path)
btn_x, btn_y = (bgr_width/2), (bgr_height-button_img.height())

canvas_btn1 = CanvasButton(canvas, btn_x, btn_y, button_img, btn_clicked)

root.mainloop()

</code>```

And here's the result of running it:

Title: Image in Button tkinter

Body:
I am having a problem in making a login image to a button. I have succeeded in making the image with a transparent background, but I can't succeed to make the button with transparent background.

I attached a screenshot that shows what I mean. The upper 'login' is a image (with transparent background), the lower is Login button but there is a white background around it. I want to make a button with transparent background.

self.login_image = Image.open('images/LoginButton.png')
self.login_image = ImageTk.PhotoImage(self.login_image)
self.main_screen_canvas.create_image(700, 300, image=self.login_image)

self.login_button = Button(self.main_screen_canvas, borderwidth=0, image=self.login_image)

self.login_button.place(x=300,y=400)

What should I do?

BackgroundImage
LoginButtonImage

Body:
Here's how to do what I was suggesting in the comment which uses the technique shown in another answer of mine to simulate a tkinter Button on a Canvas that has a transparent image placed on it (instead of text).

One issue I ran into was that fact that your 2421 × 1210 pixel background image was larger than my screen. To deal with it I added a fitrect() helper function to determine a new smaller size for it that would fit. I wrote it a long time ago, but have found it handy to have around many times (like now). Note that in the code ll and ur refer to the lower-left and upper-right corners of the rectangles involved.

Here's the resulting code:

from PIL import Image, ImageTk
import tkinter as tk

class CanvasButton:
    """ Create left mouse button clickable canvas image object.

    The x, y coordinates are relative to the top-left corner of the canvas.
    """
    flash_delay = 100  # Milliseconds.

    def __init__(self, canvas, x, y, image_source, command, state=tk.NORMAL):
        self.canvas = canvas

        if isinstance(image_source, str):
            self.btn_image = tk.PhotoImage(file=image_source)
        else:
            self.btn_image = image_source

        self.canvas_btn_img_obj = canvas.create_image(x, y, anchor='nw', state=state,
                                                      image=self.btn_image)
        canvas.tag_bind(self.canvas_btn_img_obj, "<ButtonRelease-1>",
                        lambda event: (self.flash(), command()))

    def flash(self):
        self.set_state(tk.HIDDEN)
        self.canvas.after(self.flash_delay, self.set_state, tk.NORMAL)

    def set_state(self, state):
        """ Change canvas button image's state.

        Normally, image objects are created in state tk.NORMAL. Use value
        tk.DISABLED to make it unresponsive to the mouse, or use tk.HIDDEN to
        make it invisible.
        """
        self.canvas.itemconfigure(self.canvas_btn_img_obj, state=state)

def fitrect(r1_ll_x, r1_ll_y, r1_ur_x, r1_ur_y, r2_ll_x, r2_ll_y, r2_ur_x, r2_ur_y):
    """ Find the largest rectangle that will fit within rectangle r2 that has
        rectangle r1's aspect ratio.

        Note: Either the width or height of the resulting rect will be
              identical to the corresponding dimension of rect r2.
    """
    # Calculate aspect ratios of rects r1 and r2.
    deltax1, deltay1 = (r1_ur_x - r1_ll_x), (r1_ur_y - r1_ll_y)
    deltax2, deltay2 = (r2_ur_x - r2_ll_x), (r2_ur_y - r2_ll_y)
    aspect1, aspect2 = (deltay1 / deltax1), (deltay2 / deltax2)

    # Compute size of resulting rect depending on which aspect ratio is bigger.
    if aspect1 > aspect2:
        result_ll_y, result_ur_y = r2_ll_y, r2_ur_y
        delta = deltay2 / aspect1
        result_ll_x = r2_ll_x + (deltax2 - delta) / 2.0
        result_ur_x = result_ll_x + delta
    else:
        result_ll_x, result_ur_x = r2_ll_x, r2_ur_x
        delta = deltax2 * aspect1
        result_ll_y = r2_ll_y + (deltay2 - delta) / 2.0
        result_ur_y = result_ll_y + delta

    return result_ll_x, result_ll_y, result_ur_x, result_ur_y

def btn_clicked():
    """ Prints to console a message every time the button is clicked """
    print("Button Clicked")

background_image_path = 'background_image.jpg'
button_image_path = 'button_image.png'

root = tk.Tk()
root.update_idletasks()
background_img = Image.open(background_image_path)  # Must use PIL for JPG images.

scrnwidth, scrnheight = root.winfo_screenwidth(), root.winfo_screenheight()
bgrdwidth, bgrdheight = background_img.size
border_width, border_height = 20, 20  # Allow room for window's decorations.

# Determine a background image size that will fit on screen with a border.
bgr_ll_x, bgr_ll_y, bgr_ur_x, bgr_ur_y = fitrect(
                                0, 0, bgrdwidth, bgrdheight,
                                0, 0, scrnwidth-border_width, scrnheight-border_height)
bgr_width, bgr_height = int(bgr_ur_x-bgr_ll_x), int(bgr_ur_y-bgr_ll_y)

# Resize background image to calculated size.
background_img = ImageTk.PhotoImage(background_img.resize((bgr_width, bgr_height)))

# Create Canvas same size as fitted background image.
canvas = tk.Canvas(root, bd=0, highlightthickness=0, width=bgr_width, height=bgr_height)
canvas.pack(fill=tk.BOTH)

# Put background image on Canvas.
background = canvas.create_image(0, 0, anchor='nw', image=background_img)

# Put CanvasButton on Canvas centered at the bottom.
button_img = tk.PhotoImage(file=button_image_path)
btn_x, btn_y = (bgr_width/2), (bgr_height-button_img.height())

canvas_btn1 = CanvasButton(canvas, btn_x, btn_y, button_img, btn_clicked)

root.mainloop()

And here's the result of running it:


来源: stackexchange

问:
Multiple Trips to the Db
I have those group of CheckBox Lists and Repeaters (about 8 controls needed to be loaded from my db) and for each control, I have a method in my DataAccess Layer to select the information and get it back to my control.

But There's a page that I need all those 8 controls to be loaded on the same time .. so each method will be a trip to the db and I understand that's what affects the performance. So can I have like a new method to create the connection and open it, then I can call multiple methods to access the db and load the info then close the connection at the end.

Any ideas if those 8 connections are okay for performance ? and what do you think about this idea and how can it be applied in a practical way ?

答:
If the data is read-only, you could cache it.

Then, each trip to the database will only be made once.

ContentLicense: CC BY-SA 3.0

Title: Multiple Trips to the Db


问:
how to implement multiple script tags specific to the user that will inject a widget into their website?
I'm trying to create a service where users can embed a customer feedback widget in their website, similar to https://appzi.com. I'm thinking about using NodeJS for the BE but I'm confused as to how to generate unique script tags for each widget? And how to host those scripts? i searched all over google but couldn't find anything.</p>

ContentLicense: CC BY-SA 4.0

Body:
For hosting you could serve the files on an api endpoint and then res.send the files back with a fastify api. You could use a script tag and as a source use your api url and add a id to your script tag to identify. <script src="https://yourapientpoint.something.com" id="widgetId" /> You can then in your widget subtract this id to determine the look of your widget.
Alternatively you could check https://www.jsdelivr.com/


问:
Laravel, how to show a related table's associated name in my home.blade.php?
I know the question might be unclear, but let me elaborate. I have a home page for my website (home.blade.php), where I list the items like this.

```<code>@foreach ($products as $product)
    <div class="m-auto text-center">
        <h2>
            <a href="/products/{{ $product->id }}">
                {{ $product->name }}
            </a>
        </h2>
        <p>
            Manufacturer: {{ $product->manufacturer }}
        </p>
        <p>
            Price: {{ $product->price }}
        </p>
        <p>
            In stock: {{ $product->stock }}
        </p>
        <a href="seller/{{ $product->sellerID }}">
            Seller's site
        </a>
        <hr>
    </div>
@endforeach
</code>```

I want to show the name attribute of my seller table instead of the Seller's site. With the product table, it's in a many-many relationship. And I store a sellerID attribute in my product table as a foreign key, which references the seller's table id attribute. As for my HomeController.php, the function currently passing the values looks like this.

public function index()
{
    $products = Product::all();
    return view('home', [
        'products' => $products
    ]);
}
```

I know that I shouldn't do a query in any view, but I can't figure out how I should do the query in the controller. Can someone help me with this?
Also, please ignore the bad-looking site, I'm currently trying to do the backend first, and the frontend comes later.

答:
I'm not sure if I understood you entirely, because I got confused.

If you have many-to-many relationship, you can't have sellerID. Foreing id can be used in one-to-many or one-to-one relationships.

In order to have many-to-many relationship, you need to have a pivot table.

```<code>product_seller
id, product_id, seller_id
</code>```

In conttoller

```<code>Product::with('sellers')->get();
</code>```

In view, there is another problem. You will have many sellers, but you want to display only one, which one? I assume you either have a wrong relationship, or wrong view, or misexplained problem. But if I go based on many to many:

```<code>@foreach ($product->sellers as $seller)
    <a href="seller/{{ $seller->id }}">Seller's site</a>
@endforeach
</code>```

Body:
I know the question might be unclear, but let me elaborate. I have a home page for my website (home.blade.php), where I list the items like this.

@foreach ($products as $product)

            id }}">
                {{ $product->name }}

            Manufacturer: {{ $product->manufacturer }}

            Price: {{ $product->price }}

            In stock: {{ $product->stock }}

        sellerID }}">
            Seller's site

@endforeach

I want to show the name attribute of my seller table instead of the Seller's site. With the product table, it's in a many-many relationship. And I store a sellerID attribute in my product table as a foreign key, which references the seller's table id attribute. As for my HomeController.php, the function currently passing the values looks like this.

public function index()
{
    $products = Product::all();
    return view('home', [
        'products' => $products
    ]);
}

I know that I shouldn't do a query in any view, but I can't figure out how I should do the query in the controller. Can someone help me with this?
Also, please ignore the bad-looking site, I'm currently trying to do the backend first, and the frontend comes later.

Body:
I'm not sure if I understood you entirely, because I got confused.

If you have many-to-many relationship, you can't have sellerID. Foreing id can be used in one-to-many or one-to-one relationships.

In order to have many-to-many relationship, you need to have a pivot table.

product_seller
id, product_id, seller_id

In conttoller

Product::with('sellers')->get();

In view, there is another problem. You will have many sellers, but you want to display only one, which one? I assume you either have a wrong relationship, or wrong view, or misexplained problem. But if I go based on many to many:

@foreach ($product->sellers as $seller)
    <a href="seller/{{ $seller->id }}">Seller's site</a>
@endforeach


问:
Possible to get 'regex source' from match?
I can get the source of a regex when it's defined separately. For example:

let r1 = new RegExp("el*");
console.log(r1.source);
// el*```
</div>
</div>
</p>
<p>Or:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let r2 = /el*/;
console.log(r2.source);
// el*</code>```

Is there a way to extract that if the regex isn't defined separately? For example, something along the lines of:

```<code>let m = "Hello".match(/el*/);
console.log(m.source?);
</code>```

答:
No,

quoting the documents of the match() function

Return value

An Array whose contents depend on the presence or absence of the
global (g) flag, or null if no matches are found.

So the return value is an array (you can test it by Array.isArray(m)// true)

However, the returned array has some extra information about the ocurred match (like groups, index and original input) but none of them include the original regex used to get the match

So there is no way to get that information from the match because its not returned by the matching function

Body:
I can get the source of a regex when it's defined separately. For example:

let r1 = new RegExp("el*");
console.log(r1.source);
// el*

Or:

let r2 = /el*/;
console.log(r2.source);
// el*

Is there a way to extract that if the regex isn't defined separately? For example, something along the lines of:

let m = "Hello".match(/el*/);
console.log(m.source?);


答:
There certainly maybe a cleaner approach but the following will work and provide a single function to do either yearly, quarterly or monthly updates as follows:

```<code>import pandas as pd
from collections import namedtuple

# Control tuple defining the date parameters for changing dataframe
DateControl = namedtuple('DateControl', ['Year', 'Quarter', 'Month'])

def updateFrame(df:pd.DataFrame, pcnt_val: float, **args) -> pd.DataFrame:
    # Function to update a specified year, quarter of Month by pcnt_val amount
    dtecol = args.pop('DTECOL', None)
    colList = args.pop('Columns', [])
    control = DateControl(args.pop('Year', None),
                          args.pop('Quarter', None),
                          args.pop('Month', None)
                         )

    def EvalDate(ds: pd.Series, row: int, selection: DateControl) -> bool:
        # Evaluate the truth of a date based on control arguments
        yr = False
        qtr = False
        mnth = False
        if selection.Year is None:
            yr = True
        else:
            if ds[row].year == selection.Year:
                yr = True
        if selection.Quarter is None:
            qtr = True
        else:
            if ds[row].quarter == selection.Quarter:
                qtr = True
        if selection.Month is None:
            mnth = True
        else:
            if ds[row].month == selection.Month:
                mnth = True
        return yr and qtr and mnth

    # Use control to update all cols named in colList
    mask = list(EvalDate(df[dtecol], x, control) for x in range(len(df[dtecol])))
    mod = list((1.0 + pcnt_val) if x else 1.0 for x in mask)
    print(mask)
    print(mod)
    for c in colList:
         df[c] = list(df.iloc[x][c] * mod[x] for x in range(len(df[c])))
    return df
</code>```

The updateFrame function takes two positional arguments:

. df - the dataframe to be updated

. pcnt_val - the percentage to be added to the current value

The function also takes some keyword variables to include:

DTECOL - which is the Name of the df column containing dates

Columns - a list of column headings within the Df to be changed

Year - a year value or None if all years are to be changed

Quarter - a specific quarter integer 1 thru 4 inclusive or None

Month -  a specific month to be changed or None

Applying this function to your dataframe df as follows:

```<code>dg = updateFrame(df, .25, DTECOL='Date', Columns=['Col_1', 'Col_2'], Year=2021, Quarter=3)
</code>```

Yields:

```<code>    Date    Col_1   Col_2   Col_3   Col_4   Col_5
0   2021-01-01  10.0    20.0    10  20  10
1   2021-02-01  10.0    20.0    10  20  10
2   2021-03-01  10.0    20.0    10  20  10
3   2021-04-01  10.0    20.0    10  20  10
4   2021-05-01  10.0    20.0    10  20  10
5   2021-06-01  10.0    20.0    10  20  10
6   2021-07-01  12.5    25.0    10  20  10
7   2021-08-01  12.5    25.0    10  20  10
8   2021-09-01  12.5    25.0    10  20  10
9   2021-10-01  10.0    20.0    10  20  10
10  2021-11-01  10.0    20.0    10  20  10
11  2021-12-01  10.0    20.0    10  20  10
</code>```

Given that you would like to provide updates for all 4 quarters in one call this is how I would do it:
add new function:

```<code>def updateByQuarter(df:pd.DataFrame, changes: list, **args) -> pd.DataFrame:
    #  Given a quarterly change list of the form tuple(qtrid, chgval) Update the dataframe
    for chg in changes:
        args['Quarter'] = chg[0]
        df updateFrame(df, chg[1], **args)
    return df
</code>```

Then create a list of changes by quarter

```<code># List of tuples defining the quarter and percent change
qtrChg = [(1, 0.02),(2, 0.035),(3, -0.018),(4, 0.125)]
</code>```

The use:

```<code>df = updateByQuarter(df, [(1, 0.02), (2, 0.04), (3, -0.02), (4, 0.15)], DTECOL='Date', Columns=['Col_1', 'Col_2'])
</code>```

This yields:

```<code>         Date  Col_1  Col_2  Col_3  Col_4  Col_5
0  2021-01-01   10.2   20.4     10     20     10
1  2021-02-01   10.2   20.4     10     20     10
2  2021-03-01   10.2   20.4     10     20     10
3  2021-04-01   10.4   20.8     10     20     10
4  2021-05-01   10.4   20.8     10     20     10
5  2021-06-01   10.4   20.8     10     20     10
6  2021-07-01    9.8   19.6     10     20     10
7  2021-08-01    9.8   19.6     10     20     10
8  2021-09-01    9.8   19.6     10     20     10
9  2021-10-01   11.5   23.0     10     20     10
10 2021-11-01   11.5   23.0     10     20     10
11 2021-12-01   11.5   23.0     10     20     10
</code>```

Title: Data manipulation in pandas on monthly, quarterly and annual level on multiple columns

Body:
I need to create a function which take an input as dictionary and update column values in the dataframe. My data looks following

Date
Col_1
Col_2
Col_3
Col_4
Col_5

01/01/2021
10
20
10
20
10

02/01/2021
10
20
10
20
10

03/01/2021
10
20
10
20
10

04/01/2021
10
20
10
20
10

05/01/2021
10
20
10
20
10

06/01/2021
10
20
10
20
10

07/01/2021
10
20
10
20
10

08/01/2021
10
20
10
20
10

09/01/2021
10
20
10
20
10

10/01/2021
10
20
10
20
10

11/01/2021
10
20
10
20
10

12/01/2021
10
20
10
20
10

Now, if pass monthly level update in percentage for 'Col_1' and 'Col_2', say

{Date: ['01/01/2021','02/01/2021','03/01/2021','04/01/2021','05/01/2021','06/01/2021',
        '07/01/2021','08/01/2021','09/01/2021','10/01/2021','11/01/2021','12/01/2021',],
 'Col_1': [20,20,20,20,30,30,40,40,20,20,20,20],
 'Col_2': [0,0,0,0,0,0,0,0,0,0,10,10]}

After performing this my desired out looks like this for monthly change

Date
Col_1
Col_2
Col_3
Col_4
Col_5

01/01/2021
12
20
10
20
10

02/01/2021
12
20
10
20
10

03/01/2021
12
20
10
20
10

04/01/2021
12
20
10
20
10

05/01/2021
13
20
10
20
10

06/01/2021
13
20
10
20
10

07/01/2021
14
20
10
20
10

08/01/2021
14
20
10
20
10

09/01/2021
12
20
10
20
10

10/01/2021
12
20
10
20
10

11/01/2021
12
24
10
20
10

12/01/2021
12
24
10
20
10

Similarly, I want to update my data on Quarterly and Yearly Level too. I am able to do the Yearly update, here is my code. Please help me with MONTHY AND QUARTERLY updation based on the inputs.

Thank you!!

dic = {'col_1':10,'col_2':-5)
year = 2021
def update_df(dic,df,year):
    df = df[df['date'].dt.year == year]
    df = (df+df.select_dtypes(include = 'number').mul(pd.Series(dic)/100)).combine_first(df)[df.columns]
    return df

I am trying like this

def update_df(dic,df,year,choice):
    if choice == annual:
        df = df[df['date'].dt.year == year]
        df = (df+df.select_dtypes(include =
'number').mul(pd.Series(dic)/100)).combine_first(df)[df.columns]
    elif choice == quarterly :
        df["quarter"] = df.date.dt.quarter
        df = (df+df.select_dtypes(include =
        'number').mul(pd.Series(dic)/100)).combine_first(df)[df.columns]
    else choice == monthly :
        df["month"] = df.date.dt.month
        df = (df+df.select_dtypes(include =
        'number').mul(pd.Series(dic)/100)).combine_first(df)[df.columns]
    return df

Body:
There certainly maybe a cleaner approach but the following will work and provide a single function to do either yearly, quarterly or monthly updates as follows:

import pandas as pd
from collections import namedtuple

# Control tuple defining the date parameters for changing dataframe
DateControl = namedtuple('DateControl', ['Year', 'Quarter', 'Month'])

def updateFrame(df:pd.DataFrame, pcnt_val: float, **args) -> pd.DataFrame:
    # Function to update a specified year, quarter of Month by pcnt_val amount
    dtecol = args.pop('DTECOL', None)
    colList = args.pop('Columns', [])
    control = DateControl(args.pop('Year', None),
                          args.pop('Quarter', None),
                          args.pop('Month', None)
                         )

    def EvalDate(ds: pd.Series, row: int, selection: DateControl) -> bool:
        # Evaluate the truth of a date based on control arguments
        yr = False
        qtr = False
        mnth = False
        if selection.Year is None:
            yr = True
        else:
            if ds[row].year == selection.Year:
                yr = True
        if selection.Quarter is None:
            qtr = True
        else:
            if ds[row].quarter == selection.Quarter:
                qtr = True
        if selection.Month is None:
            mnth = True
        else:
            if ds[row].month == selection.Month:
                mnth = True
        return yr and qtr and mnth

    # Use control to update all cols named in colList
    mask = list(EvalDate(df[dtecol], x, control) for x in range(len(df[dtecol])))
    mod = list((1.0 + pcnt_val) if x else 1.0 for x in mask)
    print(mask)
    print(mod)
    for c in colList:
         df[c] = list(df.iloc[x][c] * mod[x] for x in range(len(df[c])))
    return df

The updateFrame function takes two positional arguments:

. df - the dataframe to be updated

. pcnt_val - the percentage to be added to the current value

The function also takes some keyword variables to include:

DTECOL - which is the Name of the df column containing dates

Columns - a list of column headings within the Df to be changed

Year - a year value or None if all years are to be changed

Quarter - a specific quarter integer 1 thru 4 inclusive or None

Month -  a specific month to be changed or None

Applying this function to your dataframe df as follows:

dg = updateFrame(df, .25, DTECOL='Date', Columns=['Col_1', 'Col_2'], Year=2021, Quarter=3)

Yields:

    Date    Col_1   Col_2   Col_3   Col_4   Col_5
0   2021-01-01  10.0    20.0    10  20  10
1   2021-02-01  10.0    20.0    10  20  10
2   2021-03-01  10.0    20.0    10  20  10
3   2021-04-01  10.0    20.0    10  20  10
4   2021-05-01  10.0    20.0    10  20  10
5   2021-06-01  10.0    20.0    10  20  10
6   2021-07-01  12.5    25.0    10  20  10
7   2021-08-01  12.5    25.0    10  20  10
8   2021-09-01  12.5    25.0    10  20  10
9   2021-10-01  10.0    20.0    10  20  10
10  2021-11-01  10.0    20.0    10  20  10
11  2021-12-01  10.0    20.0    10  20  10

Given that you would like to provide updates for all 4 quarters in one call this is how I would do it:
add new function:

def updateByQuarter(df:pd.DataFrame, changes: list, **args) -> pd.DataFrame:
    #  Given a quarterly change list of the form tuple(qtrid, chgval) Update the dataframe
    for chg in changes:
        args['Quarter'] = chg[0]
        df updateFrame(df, chg[1], **args)
    return df

Then create a list of changes by quarter

# List of tuples defining the quarter and percent change
qtrChg = [(1, 0.02),(2, 0.035),(3, -0.018),(4, 0.125)]

The use:

df = updateByQuarter(df, [(1, 0.02), (2, 0.04), (3, -0.02), (4, 0.15)], DTECOL='Date', Columns=['Col_1', 'Col_2'])

This yields:

         Date  Col_1  Col_2  Col_3  Col_4  Col_5
0  2021-01-01   10.2   20.4     10     20     10
1  2021-02-01   10.2   20.4     10     20     10
2  2021-03-01   10.2   20.4     10     20     10
3  2021-04-01   10.4   20.8     10     20     10
4  2021-05-01   10.4   20.8     10     20     10
5  2021-06-01   10.4   20.8     10     20     10
6  2021-07-01    9.8   19.6     10     20     10
7  2021-08-01    9.8   19.6     10     20     10
8  2021-09-01    9.8   19.6     10     20     10
9  2021-10-01   11.5   23.0     10     20     10
10 2021-11-01   11.5   23.0     10     20     10
11 2021-12-01   11.5   23.0     10     20     10


问:
Validating Data In A WinForm
I have created a dialog box in my WinForms application. This has many text boxes and ok/cancel buttons. When the user clicks ok, I only want the dialog box to close if all entries are valid. I can see how to do this with the "Validating" events for each control separately. That is fine. But these only seem to fire when a control loses focus. However, empty text boxes in my dialog are also invalid input which means the user may never have focused on that control. I would prefer to just validate all controls on clicking OK.

I can't work out how to do this though. Overriding the onclick of the OK button doesn't seem to have an option for stopping the window from closing. The Form IsClosing event does by setting Cancel = true. But this doesn't seem to be able to distinguish between whether the OK or Cancel button is clicked. Obviously if the cancel button is clicked I don't care about validation and want to allow the form to close regardless.

What is the best approach for doing this?]

Update:
I already had CausesValidation set to true on both my form and ok button but my validation event does not get fired when I click the ok button. I mention this as it was suggested as a solution below.

答:
You can also use this simple code. just introducing a simple Boolean variable named hasError can do the job.</p>

```<code>    public partial class Form1 : Form
    {
        private bool hasError;
        public Form1()
        {
            InitializeComponent();
        }

        private void OkBtn_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear(); hasError=false;
            if (ValidateTxt.Text.Length == 0)
            {
                errorProvider1.SetError(ValidateTxt, "must have a value");
                hasError=true;
            }
            if (!hasError)
            {
                //Do what you want to do and close your application
                Close();
            }

        }

        private void CancelBtn_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
</code>```

Title: Validating Data In A WinForm

Body:
You can also use this simple code. just introducing a simple Boolean variable named hasError can do the job.

    public partial class Form1 : Form
    {
        private bool hasError;
        public Form1()
        {
            InitializeComponent();
        }

        private void OkBtn_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear(); hasError=false;
            if (ValidateTxt.Text.Length == 0)
            {
                errorProvider1.SetError(ValidateTxt, "must have a value");
                hasError=true;
            }
            if (!hasError)
            {
                //Do what you want to do and close your application
                Close();
            }

        }

        private void CancelBtn_Click(object sender, EventArgs e)
        {
            Close();
        }
    }


问:
Can't connect to MySQL server on 'localhost' (10061)
I recently installed MySQL 5 on Windows 2003 and tried configuring an instance. Everything worked fine until I got to "Applying Security settings", at which point it gave me the above error (Can't connect to MySQL server on 'localhost' (10061)).

I do have a port 3306 exception in my firewall for 'MySQL Server'.

答: I did not have Mysql server installed, that package was missing and I got it from this link https://dev.mysql.com/downloads/installer/</p>


问:
Python linear algebra in a finite field
Is there a way to do linear algebra and matrix manipulation in a finite field in Python? I need to be able to find the null space of a non-square matrix in the finite field F2. I currently can't find a way to do this. I have tried the galois package, but it does not support the scipy null space function. It is easy to compute the null space in sympy, however I do not know how to work in a finite field in sympy.</p>

答:
I'm the author of the galois library you mentioned. As noted by other comments, this capability is easy to add, so I added it in galois#259. It is now available in v0.0.24 (released today 02/12/2022).

Here is the documentation for computing the null space FieldArray.null_space() that you desire.

Here's an example computing the row space and left null space.

In [1]: import galois

In [2]: GF = galois.GF(2)

In [3]: m, n = 7, 3

In [4]: A = GF.Random((m, n)); A
Out[4]:
GF([[1, 1, 0],
    [0, 0, 0],
    [1, 0, 0],
    [1, 1, 1],
    [0, 0, 1],
    [1, 1, 1],
    [0, 1, 0]], order=2)

In [5]: R = A.row_space(); R
Out[5]:
GF([[1, 0, 0],
    [0, 1, 0],
    [0, 0, 1]], order=2)

In [6]: LN = A.left_null_space(); LN
Out[6]:
GF([[1, 0, 0, 0, 1, 1, 0],
    [0, 1, 0, 0, 0, 0, 0],
    [0, 0, 1, 0, 1, 1, 1],
    [0, 0, 0, 1, 0, 1, 0]], order=2)

# The left null space annihilates the rows of A
In [7]: LN @ A
Out[7]:
GF([[0, 0, 0],
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]], order=2)

# The dimension of the row space and left null space sum to m
In [8]: R.shape[0] + LN.shape[0] == m
Out[8]: True
```
<p>Here's the column space and null space.</p>
<pre class="lang-py prettyprint-override"><code>In [9]: C = A.column_space(); C
Out[9]:
GF([[1, 0, 0, 0, 1, 0, 1],
    [0, 0, 1, 0, 0, 0, 1],
    [0, 0, 0, 1, 1, 1, 0]], order=2)

In [10]: N = A.null_space(); N
Out[10]: GF([], shape=(0, 3), order=2)

# If N has dimension > 0, then A @ N.T == 0

In [11]: C.shape[0] + N.shape[0] == n
Out[11]: True
</code>```

Title: Python linear algebra in a finite field

Body:
I'm the author of the galois library you mentioned. As noted by other comments, this capability is easy to add, so I added it in galois#259. It is now available in v0.0.24 (released today 02/12/2022).

Here is the documentation for computing the null space FieldArray.null_space() that you desire.

Here's an example computing the row space and left null space.

In [1]: import galois

In [2]: GF = galois.GF(2)

In [3]: m, n = 7, 3

In [4]: A = GF.Random((m, n)); A
Out[4]:
GF([[1, 1, 0],
    [0, 0, 0],
    [1, 0, 0],
    [1, 1, 1],
    [0, 0, 1],
    [1, 1, 1],
    [0, 1, 0]], order=2)

In [5]: R = A.row_space(); R
Out[5]:
GF([[1, 0, 0],
    [0, 1, 0],
    [0, 0, 1]], order=2)

In [6]: LN = A.left_null_space(); LN
Out[6]:
GF([[1, 0, 0, 0, 1, 1, 0],
    [0, 1, 0, 0, 0, 0, 0],
    [0, 0, 1, 0, 1, 1, 1],
    [0, 0, 0, 1, 0, 1, 0]], order=2)

# The left null space annihilates the rows of A
In [7]: LN @ A
Out[7]:
GF([[0, 0, 0],
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]], order=2)

# The dimension of the row space and left null space sum to m
In [8]: R.shape[0] + LN.shape[0] == m
Out[8]: True

Here's the column space and null space.

In [9]: C = A.column_space(); C
Out[9]:
GF([[1, 0, 0, 0, 1, 0, 1],
    [0, 0, 1, 0, 0, 0, 1],
    [0, 0, 0, 1, 1, 1, 0]], order=2)

In [10]: N = A.null_space(); N
Out[10]: GF([], shape=(0, 3), order=2)

# If N has dimension > 0, then A @ N.T == 0

In [11]: C.shape[0] + N.shape[0] == n
Out[11]: True


问:
Erlang io:formatting a binary to hex
Can I format an Erlang binary so that each byte is written in hex? I.e.,

```<code>> io:format(???, [<<255, 16>>]).
<<FF, 10>>
</code>```

I don't see an obvious way to do it in io:format documentation, but perhaps I am simply missing one? Converting a binary to list and formatting its elements separately is too inefficient.

ContentLicense: CC BY-SA 2.5

Title: Erlang io:formatting a binary to hex

Body:
Can I format an Erlang binary so that each byte is written in hex? I.e.,

> io:format(???, [<<255, 16>>]).
<<FF, 10>>

I don't see an obvious way to do it in io:format documentation, but perhaps I am simply missing one? Converting a binary to list and formatting its elements separately is too inefficient.

Body:
As of OTP24, there is

1> binary:encode_hex(<<1,2,3,4,5,6,255>>).
<<"010203040506FF">>


问:
Should virtual dispatch happen when a virtual method is called within a virtual method using object?
```<code>struct B
{
  virtual void bar () {}
  virtual void foo () { bar(); }
};

struct D : B
{
  virtual void bar () {}
  virtual void foo () {}
};
</code>```

Now we call foo() using an object of B as,

```<code>B obj;
obj.foo();  // calls B::bar()
</code>```

Question:
Should bar() will be resolved through virtual dispatch or it will be resolved using the static type of the object (i.e. B).

答:
EDIT: I think I misunderstood your question. I'm pretty sure it depends on how smart the compiler's optimizer is. A naive implementation would of course still go through a virtual lookup. The only way to know for sure for a particular implementation is to compile the code and look at the disassembly to see if it's smart enough to make the direct call.

Original answer:

It will be virtually dispatched. This is more obvious when you consider that within a class method, a method call works out to something like this->bar();, making it obvious that a pointer is used to call the method, allowing to use the dynamic object type.

However in your example since you created a B it will of course call B's version of the method.

Do note (as seen in a comment) that virtual dispatch doesn't happen inside constructors even using the implicit this->.

EDIT2 for your update:
That's not right at all. Calls within B::foo() cannot be generally bound statically (unless due to inlining the compiler knows the static type of the object). Just because it knows that it's being called on a B* says nothing about the real type of the object in question - it could be a D* and need virtual dispatch.

Body:
struct B
{
  virtual void bar () {}
  virtual void foo () { bar(); }
};

struct D : B
{
  virtual void bar () {}
  virtual void foo () {}
};

Now we call foo() using an object of B as,

B obj;
obj.foo();  // calls B::bar()

Question:
Should bar() will be resolved through virtual dispatch or it will be resolved using the static type of the object (i.e. B).


问:
extract text from pdf File from S3 bucket python
I have multiple format files in my AWS s3 bucket like pdf,doc,rtf,odt,png and I need to extract text from it.
I have managed to get the list of contents  with their path .now depending on the file type i will use different libraries to extract text from the file . since files can be in thousands i need to extract text directly from s3 instead of downloading.

```<code>filespath=['https://abc.s3.ap-south-1.amazonaws.com/DocumentOnPATest', 'https://abc.s3.ap-south-1.amazonaws.com/IndustryReport2019.pdf', 'https://abc.s3.ap-south-1.amazonaws.com/receipt.png', 'https://abc.s3.ap-south-1.amazonaws.com/sample.rtf', 'https://abc.s3.ap-south-1.amazonaws.com/sample1.odt']

bucketname =abc
</code>```

I tried something but its giving me error

```<code>for path in filespath:
    ext=pathlib.Path(path).suffix
    if ext=='.pdf':
       pdf_file=PyPDF2.PdfFileReader(path)
       print(pdf_file.extractText())
</code>```

but i am getting an error

```<code>  File "F:\Projects\FileExtractor\fileextracts3.py", line 28, in <module>
    pdf_file=PyPDF2.PdfFileReader(path)

  File "C:\ProgramData\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1081, in __init__
    fileobj = open(stream, 'rb')

OSError: [Errno 22] Invalid argument: 'https://abc.s3.ap-south-1.amazonaws.com/IndustryReport2019.pdf
</code>```

please help me with the lead. Thank you

答:
You could try the boto3 solution here, provided by Justin Leto.  You would still need a way of reading/converting the file stream for each file type but the PDF answer is there.</p>
```<code>import boto3
s3 = boto3.resource('s3')
obj = s3.Object(bucket_name, itemname)
fs = obj.get()['Body'].read()
</code>```

Body:
I have multiple format files in my AWS s3 bucket like pdf,doc,rtf,odt,png and I need to extract text from it.
I have managed to get the list of contents  with their path .now depending on the file type i will use different libraries to extract text from the file . since files can be in thousands i need to extract text directly from s3 instead of downloading.

filespath=['https://abc.s3.ap-south-1.amazonaws.com/DocumentOnPATest', 'https://abc.s3.ap-south-1.amazonaws.com/IndustryReport2019.pdf', 'https://abc.s3.ap-south-1.amazonaws.com/receipt.png', 'https://abc.s3.ap-south-1.amazonaws.com/sample.rtf', 'https://abc.s3.ap-south-1.amazonaws.com/sample1.odt']

bucketname =abc

I tried something but its giving me error

for path in filespath:
    ext=pathlib.Path(path).suffix
    if ext=='.pdf':
       pdf_file=PyPDF2.PdfFileReader(path)
       print(pdf_file.extractText())

but i am getting an error

  File "F:\Projects\FileExtractor\fileextracts3.py", line 28, in <module>
    pdf_file=PyPDF2.PdfFileReader(path)

  File "C:\ProgramData\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1081, in __init__
    fileobj = open(stream, 'rb')

OSError: [Errno 22] Invalid argument: 'https://abc.s3.ap-south-1.amazonaws.com/IndustryReport2019.pdf

please help me with the lead. Thank you

Body:
You could try the boto3 solution here, provided by Justin Leto.  You would still need a way of reading/converting the file stream for each file type but the PDF answer is there.

import boto3
s3 = boto3.resource('s3')
obj = s3.Object(bucket_name, itemname)
fs = obj.get()['Body'].read()


问:
Code undoes itself before returning value
```<code>from time import sleep
def refit(i, n, c=[]):
 sleep(1)
 print(c)
 if i[:n] != '': refit(i[n:],n,c+[i[:n]])
 sleep(1)
 print(c)
 return c
</code>```

Output when using arguments "Helloo" and 2:

```<code>[]
['He']
['He', 'll']
['He', 'll', 'oo']
['He', 'll', 'oo']
['He', 'll']
['He']
[]
[]
</code>```

The Array ['He', 'll', 'oo'] should be printed and returned, but the code is undoing itself.
What is happening? I am so confused.

答:
Did you mean to save the return value from recursive calls to refit()?

def refit(i, n, c=[]):
    if i[:n] != '':
        c = refit(i[n:], n, c+[i[:n]])
    return c

c = refit('Helloo',2)
print(c)
```

Output as requested

Body:
from time import sleep
def refit(i, n, c=[]):
 sleep(1)
 print(c)
 if i[:n] != '': refit(i[n:],n,c+[i[:n]])
 sleep(1)
 print(c)
 return c

Output when using arguments "Helloo" and 2:

[]
['He']
['He', 'll']
['He', 'll', 'oo']
['He', 'll', 'oo']
['He', 'll']
['He']
[]
[]

The Array ['He', 'll', 'oo'] should be printed and returned, but the code is undoing itself.
What is happening? I am so confused.

Body:
Did you mean to save the return value from recursive calls to refit()?

def refit(i, n, c=[]):
    if i[:n] != '':
        c = refit(i[n:], n, c+[i[:n]])
    return c

c = refit('Helloo',2)
print(c)

Output as requested


问:
Swift binding to a computed property
Have the following situation.  I have a view model that is an observable object with a computed property of type Bool.  I want to be able to enable/disable a navigation link based on the computed property, but I need a binding to do so.  Here a simplified example:

```<code>struct Project {
    var name: String
    var duration: Int
}

class MyViewModel: Observable Object {
    @Published var project: Project

    var isProjectValid: Bool {
        return project.name != "" && project.duration > 0
    }
}

struct MyView: View {
    @EnvironmentObject var myVM: MyViewModel

    var body: some View {
        ...
        NavigationLink("Click Link", isActive: ?????, destination: NextView())
        ...
    }
}
</code>```

Since isActive expects a binding I am not able to access computed property such as myVM.isProjectValid.  Tried also with the computed property in project class, still same problem.

Also considered creating custom binding related to the computed property, but not quite sure if/how to go about it.

First question I have posted, so if I am missing some details please be kind :)

答:
Make it a @Published property and update it when project is changed

```<code>class MyViewModel: ObservableObject {
    @Published var project: Project {
        didSet {
            isProjectValid = project.name != "" && project.duration > 0
        }
    }

    @Published var isProjectValid: Bool

     //...
}
</code>```

Title: Swift binding to a computed property

Body:
Have the following situation.  I have a view model that is an observable object with a computed property of type Bool.  I want to be able to enable/disable a navigation link based on the computed property, but I need a binding to do so.  Here a simplified example:

struct Project {
    var name: String
    var duration: Int
}

class MyViewModel: Observable Object {
    @Published var project: Project

    var isProjectValid: Bool {
        return project.name != "" && project.duration > 0
    }
}

struct MyView: View {
    @EnvironmentObject var myVM: MyViewModel

    var body: some View {
        ...
        NavigationLink("Click Link", isActive: ?????, destination: NextView())
        ...
    }
}

Since isActive expects a binding I am not able to access computed property such as myVM.isProjectValid.  Tried also with the computed property in project class, still same problem.

Also considered creating custom binding related to the computed property, but not quite sure if/how to go about it.

First question I have posted, so if I am missing some details please be kind :)

Body:
Make it a @Published property and update it when project is changed

class MyViewModel: ObservableObject {
    @Published var project: Project {
        didSet {
            isProjectValid = project.name != "" && project.duration > 0
        }
    }

    @Published var isProjectValid: Bool

     //...
}


问:
What DB to use for a windows application?
I am developing a small windows application in .net. What DB should I use?

DB Structure

Table 1 : Not more than 3 fields : 50+ records (Add, Delete)

Table 2 : Not more than 10 fields : 10-20 records (Add, Delete)

I thought of using XMLDatabase but some say its not advisable to use it. What are the reasons for this?
If it is OK to use XML files as the DB then can you suggest some tutorials or best practices? I have worked with XML files before. Is there anything different when it comes to using it as a DB?

I am also planning to distribute the application to my friends some time later and these guys are not programmers and they are less tech savvy.

So If I am using SQL server how can I deploy it in others machine? How can I add it to the setup file?

Update: Thanks for the answers. I am going for SQLite and here is a tutorial about SQLite and .net if someone is interested.

答:
John Saunders mentioned SQL Server Express.
Just to be fair there is also Oracle Express and DB2 Express.
Their respective feature lists are virtually identical.
All are free at least for personal use.</p>

OwnerDisplayName: Shoban

LastEditorDisplayName: Shoban


问:
How to create an instance method based on this object data?
I have some data inside this variable and I want to know how could I write an method to give me the sum of the items price.

Model names and their associations:

```<code>Order
- belongs_to :customer
- has_many :item_orders
- has_many :items, :through => :item_orders
- accepts_nested_attributes_for :item_orders, :allow_destroy => true, :reject_if => lambda { |a| a['item_id'].blank? }

Item
- has_many :item_orders, :dependent => :destroy
- has_many :orders, :through => :item_orders
- accepts_nested_attributes_for :item_orders, :allow_destroy => true

ItemOrder
- belongs_to :item
- belongs_to :order
</code>```

doing:

```<code><%= debug @order.items %>

# returns me

- !ruby/object:Item
  attributes:
  id: 31
  title: Golden Ring 2
  price: 13445.0
  labour_cost: 500.0
  item_type_id: 10
  created_at: 2011-08-13 10:53:24.000000000Z
  updated_at: 2011-08-18 06:10:36.000000000Z
  photo: golden_ring.jpg
  changed_attributes: {}
  previously_changed: {}
  attributes_cache: {}
  marked_for_destruction: false
  destroyed: false
  readonly: false
  new_record: false
- !ruby/object:Item
 attributes:
  id: 32
  title: Special Pendant
  price: 171.67
  labour_cost: 120.0
  item_type_id: 20
  created_at: 2011-08-13 11:09:43.000000000Z
  updated_at: 2011-08-14 06:03:02.000000000Z
  photo: prd_194_48cd9b21771dd.jpg
  changed_attributes: {}
  previously_changed: {}
  attributes_cache: {}
  marked_for_destruction: false
  destroyed: false
  readonly: false
  new_record: false
</code>```

So, I want to write a method in the Order model class to make possible writes something like this on the view.

```<code> <%= @order.items.total_price %>
</code>```

The total_price method will sum all the item prices and multiply by the quantity that contains in @order.items.

My doubt is: from inside the method, how could I have access to the items collection to perform the sum operation.

```<code>def total_price
  self.item_order.each do |i| {
     result += i.quantity * i.items.price
  }
end
</code>```

EDIT: I totally forgot to mention that I have to consider the quantity also to make this math.

答:
define a function in order.rb like this:

```<code>def total_price
  self.items.inject(0) {|sum, item| sum + item.price }
end
</code>```

In the view:

```<code><%= @order.total_price %>
</code>```

Body:
I have some data inside this variable and I want to know how could I write an method to give me the sum of the items price.

Model names and their associations:

Order
- belongs_to :customer
- has_many :item_orders
- has_many :items, :through => :item_orders
- accepts_nested_attributes_for :item_orders, :allow_destroy => true, :reject_if => lambda { |a| a['item_id'].blank? }

Item
- has_many :item_orders, :dependent => :destroy
- has_many :orders, :through => :item_orders
- accepts_nested_attributes_for :item_orders, :allow_destroy => true

ItemOrder
- belongs_to :item
- belongs_to :order

doing:

<%= debug @order.items %>

# returns me

- !ruby/object:Item
  attributes:
  id: 31
  title: Golden Ring 2
  price: 13445.0
  labour_cost: 500.0
  item_type_id: 10
  created_at: 2011-08-13 10:53:24.000000000Z
  updated_at: 2011-08-18 06:10:36.000000000Z
  photo: golden_ring.jpg
  changed_attributes: {}
  previously_changed: {}
  attributes_cache: {}
  marked_for_destruction: false
  destroyed: false
  readonly: false
  new_record: false
- !ruby/object:Item
 attributes:
  id: 32
  title: Special Pendant
  price: 171.67
  labour_cost: 120.0
  item_type_id: 20
  created_at: 2011-08-13 11:09:43.000000000Z
  updated_at: 2011-08-14 06:03:02.000000000Z
  photo: prd_194_48cd9b21771dd.jpg
  changed_attributes: {}
  previously_changed: {}
  attributes_cache: {}
  marked_for_destruction: false
  destroyed: false
  readonly: false
  new_record: false

So, I want to write a method in the Order model class to make possible writes something like this on the view.

 <%= @order.items.total_price %>

The total_price method will sum all the item prices and multiply by the quantity that contains in @order.items.

My doubt is: from inside the method, how could I have access to the items collection to perform the sum operation.

def total_price
  self.item_order.each do |i| {
     result += i.quantity * i.items.price
  }
end

EDIT: I totally forgot to mention that I have to consider the quantity also to make this math.

Body:
define a function in order.rb like this:

def total_price
  self.items.inject(0) {|sum, item| sum + item.price }
end

In the view:

<%= @order.total_price %>


问:
Compare Matrix Multiplication Execution Time in Different Sizes in C
I need to calculate and compare execution time of multiplication of 2 matrices in 3 different sizes (100 * 100 , 1000 * 1000 and 10000 * 10000) in C programming language. I wrote the following simple code to do that for 1000 * 1000 and I got the execution time

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int r1 = 1000, c1 = 1000, r2 = 1000, c2 = 1000, i, j, k;

    // Dynamic allocation.
    double(*a)[r1][c1] = malloc(sizeof *a);
    double(*b)[r2][c2] = malloc(sizeof *b);
    double(*result)[r1][c2] = malloc(sizeof *result);

    // Storing elements of first matrix.
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c1; ++j)
        {
            (*a)[i][j] = rand() / RAND_MAX;
        }
    }

    // Storing elements of second matrix.
    for (i = 0; i < r2; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*b)[i][j] = rand() / RAND_MAX;
        }
    }

    // Initializing all elements of result matrix to 0
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*result)[i][j] = 0;
        }
    }

    clock_t begin1 = clock();
    // Multiplying matrices a and b and
    // storing result in result matrix
    for (i = 0; i < r1; ++i)
        for (j = 0; j < c2; ++j)
            for (k = 0; k < c1; ++k)
            {
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
            }

    clock_t end1 = clock();
    double time_taken = (double)(end1 - begin1) / CLOCKS_PER_SEC;
    printf("\n function took %f seconds to execute \n", time_taken);
    return 0;
}
</code>```

And now I want to repeat this part for two other sizes and get the result like this at the end of my program with one run:

```<code>the execution time for 100 * 100 is 1 second
the execution time for 1000 * 1000 is 2 seconds
the execution time for 10000 * 10000 is 3 seconds
</code>```

What is the best solution for that? When I repeat this part for 10000 * 10000 after 1000 * 1000 I got the segmentation fault error.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int r1 = 1000, c1 = 1000, r2 = 1000, c2 = 1000, i, j, k;

    // Dynamic allocation.
    double(*a)[r1][c1] = malloc(sizeof *a);
    double(*b)[r2][c2] = malloc(sizeof *b);
    double(*result)[r1][c2] = malloc(sizeof *result);

    // Storing elements of first matrix.
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c1; ++j)
        {
            (*a)[i][j] = rand() / RAND_MAX;
        }
    }

    // Storing elements of second matrix.
    for (i = 0; i < r2; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*b)[i][j] = rand() / RAND_MAX;
        }
    }

    // Initializing all elements of result matrix to 0
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*result)[i][j] = 0;
        }
    }

    clock_t begin1 = clock();
    // Multiplying matrices a and b and
    // storing result in result matrix
    for (i = 0; i < r1; ++i)
        for (j = 0; j < c2; ++j)
            for (k = 0; k < c1; ++k)
            {
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
            }

    clock_t end1 = clock();
    double time_taken = (double)(end1 - begin1) / CLOCKS_PER_SEC;
    printf("\n \nfunction took %f seconds to execute \n",
           time_taken);
    free(a);
    free(b);
    free(result);

    r1 = 10000, c1 = 10000, r2 = 10000, c2 = 10000;
printf("\n run second one for %d \n",r1);
    // Storing elements of first matrix.
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c1; ++j)
        {
            (*a)[i][j] = rand() / RAND_MAX;
        }
    }

    // Storing elements of second matrix.
    for (i = 0; i < r2; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*b)[i][j] = rand() / RAND_MAX;
        }
    }

    // Initializing all elements of result matrix to 0
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*result)[i][j] = 0;
        }
    }

    begin1 = clock();
    // Multiplying matrices a and b and
    // storing result in result matrix
    for (i = 0; i < r1; ++i)
        for (j = 0; j < c2; ++j)
            for (k = 0; k < c1; ++k)
            {
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
            }

    end1 = clock();
    time_taken = (double)(end1 - begin1) / CLOCKS_PER_SEC;
    printf("\n second function took %f seconds to execute \n",
           time_taken);
    free(a);
    free(b);
    free(result);

    return 0;
}
</code>```

答:
There are multiple problems in your code:

you free the matrices and perform a new benchmark, storing data thru invalid pointers... this has undefined behavior, in your case a segmentation fault.

the allocation code is specific for the initial matrix size, you cannot reallocate the matrices for a different size in the main() function. You should move the code to a separate function taking the matrix sizes as arguments and call this function multiple times.

the initialization values rand() / RAND_MAX are almost always zero because integer arithmetics is used for this division. You should use (*a)[i][j] = rand() / (double)RAND_MAX;

Here is a modified version (similar to tstanisl's):

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void test(int r1, int c1, int r2, int c2) {
    int i, j, k;

    // Dynamic allocation.
    double(*a)[r1][c1] = malloc(sizeof *a);
    double(*b)[r2][c2] = malloc(sizeof *b);
    double(*result)[r1][c2] = malloc(sizeof *result);

    // Storing elements of first matrix.
    for (i = 0; i < r1; ++i) {
        for (j = 0; j < c1; ++j) {
            (*a)[i][j] = rand() / (double)RAND_MAX;
        }
    }
    // Storing elements of second matrix.
    for (i = 0; i < r2; ++i) {
        for (j = 0; j < c2; ++j) {
            (*b)[i][j] = rand() / (double)RAND_MAX;
        }
    }
    // Initializing all elements of result matrix to 0
    for (i = 0; i < r1; ++i) {
        for (j = 0; j < c2; ++j) {
            (*result)[i][j] = 0;
        }
    }
    clock_t begin1 = clock();
    // Multiplying matrices a and b and
    // storing result in result matrix
    // using cache friendly index order
    for (i = 0; i < r1; ++i) {
        for (k = 0; k < c1; ++k) {
            for (j = 0; j < c2; ++j) {
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
            }
        }
    }
    clock_t end1 = clock();
    double time_taken = (double)(end1 - begin1) / CLOCKS_PER_SEC;
    printf("M(%d,%d) x M(%d,%d) took %f seconds to execute\n",
           r1, c1, r2, c2, time_taken);
    free(a);
    free(b);
    free(result);
}

int main() {
    test(100, 100, 100, 100);
    test(1000, 1000, 1000, 1000);
    test(2000, 2000, 2000, 2000);
    test(3000, 3000, 3000, 3000);
    test(4000, 4000, 4000, 4000);
    return 0;
}
</code>```

Output:

M(100,100) x M(100,100) took 0.000347 seconds to execute
M(1000,1000) x M(1000,1000) took 0.616177 seconds to execute
M(2000,2000) x M(2000,2000) took 5.017987 seconds to execute
M(3000,3000) x M(3000,3000) took 17.703356 seconds to execute
M(4000,4000) x M(4000,4000) took 43.825951 seconds to execute
```

The time complexity of this simplistic implementation is O(N3), which is consistent with the above timings. Given enough RAM (2.4 GB), multiplying matrices with 10000 rows and columns would take a bit more than 10 minutes.

Achieving the multiplication of 2 10k by 10k double matrices in 3 seconds requires specialized hardware and tailor made software, well beyond the simple approach in this answer.

Body:
I need to calculate and compare execution time of multiplication of 2 matrices in 3 different sizes (100 * 100 , 1000 * 1000 and 10000 * 10000) in C programming language. I wrote the following simple code to do that for 1000 * 1000 and I got the execution time

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int r1 = 1000, c1 = 1000, r2 = 1000, c2 = 1000, i, j, k;

    // Dynamic allocation.
    double(*a)[r1][c1] = malloc(sizeof *a);
    double(*b)[r2][c2] = malloc(sizeof *b);
    double(*result)[r1][c2] = malloc(sizeof *result);

    // Storing elements of first matrix.
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c1; ++j)
        {
            (*a)[i][j] = rand() / RAND_MAX;
        }
    }

    // Storing elements of second matrix.
    for (i = 0; i < r2; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*b)[i][j] = rand() / RAND_MAX;
        }
    }

    // Initializing all elements of result matrix to 0
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*result)[i][j] = 0;
        }
    }

    clock_t begin1 = clock();
    // Multiplying matrices a and b and
    // storing result in result matrix
    for (i = 0; i < r1; ++i)
        for (j = 0; j < c2; ++j)
            for (k = 0; k < c1; ++k)
            {
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
            }

    clock_t end1 = clock();
    double time_taken = (double)(end1 - begin1) / CLOCKS_PER_SEC;
    printf("\n function took %f seconds to execute \n", time_taken);
    return 0;
}

And now I want to repeat this part for two other sizes and get the result like this at the end of my program with one run:

the execution time for 100 * 100 is 1 second
the execution time for 1000 * 1000 is 2 seconds
the execution time for 10000 * 10000 is 3 seconds

What is the best solution for that? When I repeat this part for 10000 * 10000 after 1000 * 1000 I got the segmentation fault error.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int r1 = 1000, c1 = 1000, r2 = 1000, c2 = 1000, i, j, k;

    // Dynamic allocation.
    double(*a)[r1][c1] = malloc(sizeof *a);
    double(*b)[r2][c2] = malloc(sizeof *b);
    double(*result)[r1][c2] = malloc(sizeof *result);

    // Storing elements of first matrix.
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c1; ++j)
        {
            (*a)[i][j] = rand() / RAND_MAX;
        }
    }

    // Storing elements of second matrix.
    for (i = 0; i < r2; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*b)[i][j] = rand() / RAND_MAX;
        }
    }

    // Initializing all elements of result matrix to 0
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*result)[i][j] = 0;
        }
    }

    clock_t begin1 = clock();
    // Multiplying matrices a and b and
    // storing result in result matrix
    for (i = 0; i < r1; ++i)
        for (j = 0; j < c2; ++j)
            for (k = 0; k < c1; ++k)
            {
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
            }

    clock_t end1 = clock();
    double time_taken = (double)(end1 - begin1) / CLOCKS_PER_SEC;
    printf("\n \nfunction took %f seconds to execute \n",
           time_taken);
    free(a);
    free(b);
    free(result);

    r1 = 10000, c1 = 10000, r2 = 10000, c2 = 10000;
printf("\n run second one for %d \n",r1);
    // Storing elements of first matrix.
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c1; ++j)
        {
            (*a)[i][j] = rand() / RAND_MAX;
        }
    }

    // Storing elements of second matrix.
    for (i = 0; i < r2; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*b)[i][j] = rand() / RAND_MAX;
        }
    }

    // Initializing all elements of result matrix to 0
    for (i = 0; i < r1; ++i)
    {
        for (j = 0; j < c2; ++j)
        {
            (*result)[i][j] = 0;
        }
    }

    begin1 = clock();
    // Multiplying matrices a and b and
    // storing result in result matrix
    for (i = 0; i < r1; ++i)
        for (j = 0; j < c2; ++j)
            for (k = 0; k < c1; ++k)
            {
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
            }

    end1 = clock();
    time_taken = (double)(end1 - begin1) / CLOCKS_PER_SEC;
    printf("\n second function took %f seconds to execute \n",
           time_taken);
    free(a);
    free(b);
    free(result);

    return 0;
}

Body:
There are multiple problems in your code:

you free the matrices and perform a new benchmark, storing data thru invalid pointers... this has undefined behavior, in your case a segmentation fault.

the allocation code is specific for the initial matrix size, you cannot reallocate the matrices for a different size in the main() function. You should move the code to a separate function taking the matrix sizes as arguments and call this function multiple times.

the initialization values rand() / RAND_MAX are almost always zero because integer arithmetics is used for this division. You should use (*a)[i][j] = rand() / (double)RAND_MAX;

Here is a modified version (similar to tstanisl's):

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void test(int r1, int c1, int r2, int c2) {
    int i, j, k;

    // Dynamic allocation.
    double(*a)[r1][c1] = malloc(sizeof *a);
    double(*b)[r2][c2] = malloc(sizeof *b);
    double(*result)[r1][c2] = malloc(sizeof *result);

    // Storing elements of first matrix.
    for (i = 0; i < r1; ++i) {
        for (j = 0; j < c1; ++j) {
            (*a)[i][j] = rand() / (double)RAND_MAX;
        }
    }
    // Storing elements of second matrix.
    for (i = 0; i < r2; ++i) {
        for (j = 0; j < c2; ++j) {
            (*b)[i][j] = rand() / (double)RAND_MAX;
        }
    }
    // Initializing all elements of result matrix to 0
    for (i = 0; i < r1; ++i) {
        for (j = 0; j < c2; ++j) {
            (*result)[i][j] = 0;
        }
    }
    clock_t begin1 = clock();
    // Multiplying matrices a and b and
    // storing result in result matrix
    // using cache friendly index order
    for (i = 0; i < r1; ++i) {
        for (k = 0; k < c1; ++k) {
            for (j = 0; j < c2; ++j) {
                (*result)[i][j] += (*a)[i][k] * (*b)[k][j];
            }
        }
    }
    clock_t end1 = clock();
    double time_taken = (double)(end1 - begin1) / CLOCKS_PER_SEC;
    printf("M(%d,%d) x M(%d,%d) took %f seconds to execute\n",
           r1, c1, r2, c2, time_taken);
    free(a);
    free(b);
    free(result);
}

int main() {
    test(100, 100, 100, 100);
    test(1000, 1000, 1000, 1000);
    test(2000, 2000, 2000, 2000);
    test(3000, 3000, 3000, 3000);
    test(4000, 4000, 4000, 4000);
    return 0;
}

Output:

M(100,100) x M(100,100) took 0.000347 seconds to execute
M(1000,1000) x M(1000,1000) took 0.616177 seconds to execute
M(2000,2000) x M(2000,2000) took 5.017987 seconds to execute
M(3000,3000) x M(3000,3000) took 17.703356 seconds to execute
M(4000,4000) x M(4000,4000) took 43.825951 seconds to execute

The time complexity of this simplistic implementation is O(N3), which is consistent with the above timings. Given enough RAM (2.4 GB), multiplying matrices with 10000 rows and columns would take a bit more than 10 minutes.

Achieving the multiplication of 2 10k by 10k double matrices in 3 seconds requires specialized hardware and tailor made software, well beyond the simple approach in this answer.


问:
How display percent values on a stacked bar plot using ggplot in R
I've produced this graph (on the attached photo) using ggplot2.

My code goes like this:

```<code>ggplot(data, aes(fill=condition, y=value, x=period)) +
geom_bar(position="fill", stat="identity")+
xlab("Période") +  ylab("Pourcentage") +
ggtitle("Répartition des français et étrangers")+
scale_y_continuous(labels = scales::percent)+
scale_fill_brewer(palette = "OrRd")
</code>```

Result looks like this

I just need to display the values on the bars. However, adding geom_text is not straightforward.
I would appreciate it if you could provide some ideas.

答:
Without knowing the data:

Try:   geom_text(aes(label = paste0(value*100,"%")), position = position_stack(vjust = 0.5), size = 2)

```<code>ggplot(data, aes(fill=condition, y=value, x=period)) +
  geom_bar(position="fill", stat="identity")+
  geom_text(aes(label = paste0(value*100,"%")),
            position = position_stack(vjust = 0.5), size = 2)
  xlab("Période") +  ylab("Pourcentage") +
  ggtitle("Répartition des français et étrangers")+
  scale_y_continuous(labels = scales::percent)+
  scale_fill_brewer(palette = "OrRd")
</code>```

Body:
I've produced this graph (on the attached photo) using ggplot2.

My code goes like this:

ggplot(data, aes(fill=condition, y=value, x=period)) +
geom_bar(position="fill", stat="identity")+
xlab("Période") +  ylab("Pourcentage") +
ggtitle("Répartition des français et étrangers")+
scale_y_continuous(labels = scales::percent)+
scale_fill_brewer(palette = "OrRd")

Result looks like this

I just need to display the values on the bars. However, adding geom_text is not straightforward.
I would appreciate it if you could provide some ideas.

Body:
Without knowing the data:

Try:   geom_text(aes(label = paste0(value*100,"%")), position = position_stack(vjust = 0.5), size = 2)

ggplot(data, aes(fill=condition, y=value, x=period)) +
  geom_bar(position="fill", stat="identity")+
  geom_text(aes(label = paste0(value*100,"%")),
            position = position_stack(vjust = 0.5), size = 2)
  xlab("Période") +  ylab("Pourcentage") +
  ggtitle("Répartition des français et étrangers")+
  scale_y_continuous(labels = scales::percent)+
  scale_fill_brewer(palette = "OrRd")


问:
Error from firestore when subscribing to user state: TypeError: Cannot add property 2, object is not extensible
I'm experimenting with firebase auth, and have encountered this error from @firebase/utils:

```<code>TypeError: Cannot add property 2, object is not extensible
</code>```

And I can't work out what I'm doing wrong.

The erroring line of code is

```<code>        this.observers.push(observer);
</code>```

at the end of ObserverProxy.subscribe.

Up the stack a bit, this is being invoked from the onIdTokenChanged call in

```<code>function user(auth) {
    return new Observable(function (subscriber) {
        var unsubscribe = onIdTokenChanged(auth, subscriber.next.bind(subscriber), subscriber.error.bind(subscriber), subscriber.complete.bind(subscriber));
        return { unsubscribe: unsubscribe };
    });
}
</code>```

I think this user call is from my angular HttpInterceptor that injects the user token onto requests, as that is the only user call I have so far, although with the asynchronous calls the stack trace doesn't include my code.

The interceptor does the following in intercept:

```<code>    return user(this.auth).pipe(
      switchMap(user => user?.getIdToken()),
      map(idToken =>
        !idToken
          ? req
          : req.clone({
              headers: req.headers.set('Authorization', `Bearer ${idToken}`),
            })
      ),
      switchMap(req => next.handle(req))
    );
</code>```

Versions:

node_modules/@firebase/auth/package.json: 0.19.0

node_modules/@firebase/util/package.json: 1.4.3

I suspect a similar question was submitted and then deleted as Google gives me a search result pointing to https://stackoverflow.com/questions/70637998/firebase-auth-observer-cause-problem-with-firestore-query-observer-cant-subscri which is a deleted question. The cache doesn't show any answers on that question though.

答:
I discovered it was ngrx freezing everything. I was passing a firebase User as an action prop, and that had some properties that gave the freezing a path into the rest of the firebase sdk and rxjs.

I found what was being frozen by replacing Object.freeze with one that would log, and eventually modified it to fail on unexpected objects being frozen, taken from

How can I find where my object is being frozen?

```<code>function DebugFreeze() {
  const oldFree = Object.freeze;
  Object.freeze = (...args) => {
    const error = new Error('Object Frozen');
    if (
      args[0] !== null &&
      typeof args[0] === 'object' &&
      Object.getPrototypeOf(args[0]) !== null &&
      args[0].constructor.name !== 'Object' &&
      args[0].constructor.name !== 'Set' &&
      args[0].constructor.name !== 'Array' &&
      args[0].constructor.name !== 'TCleanup'
    )
      throw error;
    console.log(error.stack, '\n', ...args);
    return oldFree.call(Object, ...args);
  };
}

DebugFreeze();
</code>```

I have added a shim to convert a firebase User into a new object with a useful subset of properties when creating the action.

Body:
I'm experimenting with firebase auth, and have encountered this error from @firebase/utils:

TypeError: Cannot add property 2, object is not extensible

And I can't work out what I'm doing wrong.

The erroring line of code is

        this.observers.push(observer);

at the end of ObserverProxy.subscribe.

Up the stack a bit, this is being invoked from the onIdTokenChanged call in

function user(auth) {
    return new Observable(function (subscriber) {
        var unsubscribe = onIdTokenChanged(auth, subscriber.next.bind(subscriber), subscriber.error.bind(subscriber), subscriber.complete.bind(subscriber));
        return { unsubscribe: unsubscribe };
    });
}

I think this user call is from my angular HttpInterceptor that injects the user token onto requests, as that is the only user call I have so far, although with the asynchronous calls the stack trace doesn't include my code.

The interceptor does the following in intercept:

    return user(this.auth).pipe(
      switchMap(user => user?.getIdToken()),
      map(idToken =>
        !idToken
          ? req
          : req.clone({
              headers: req.headers.set('Authorization', `Bearer ${idToken}`),
            })
      ),
      switchMap(req => next.handle(req))
    );

Versions:

node_modules/@firebase/auth/package.json: 0.19.0

node_modules/@firebase/util/package.json: 1.4.3

I suspect a similar question was submitted and then deleted as Google gives me a search result pointing to https://stackoverflow.com/questions/70637998/firebase-auth-observer-cause-problem-with-firestore-query-observer-cant-subscri which is a deleted question. The cache doesn't show any answers on that question though.

Body:
I discovered it was ngrx freezing everything. I was passing a firebase User as an action prop, and that had some properties that gave the freezing a path into the rest of the firebase sdk and rxjs.

I found what was being frozen by replacing Object.freeze with one that would log, and eventually modified it to fail on unexpected objects being frozen, taken from

How can I find where my object is being frozen?

function DebugFreeze() {
  const oldFree = Object.freeze;
  Object.freeze = (...args) => {
    const error = new Error('Object Frozen');
    if (
      args[0] !== null &&
      typeof args[0] === 'object' &&
      Object.getPrototypeOf(args[0]) !== null &&
      args[0].constructor.name !== 'Object' &&
      args[0].constructor.name !== 'Set' &&
      args[0].constructor.name !== 'Array' &&
      args[0].constructor.name !== 'TCleanup'
    )
      throw error;
    console.log(error.stack, '\n', ...args);
    return oldFree.call(Object, ...args);
  };
}

DebugFreeze();

I have added a shim to convert a firebase User into a new object with a useful subset of properties when creating the action.


问:
How to group nested list by first,last element differences in Python?
I need to group nested lists by first element and last element differences.

I have a nested list like :

```<code>[[1, 17, 4], [1, 17, 3],  [2, 17, 3]]
</code>```

This is my code :

This creates dict and checks first and last element not in dict. If first and last element not in dict, saves list to dict.

```<code>
b = [[1, 17, 4], [1, 17, 3],  [2, 17, 3]]
d = {}

for l in b:
    if l[2] not in d and l[0] not in d:
        d[l[2]] = [l[0],l[1],l[2]]

res = list(d.values())

print(res)

</code>```

This returns :

```<code>[[1, 17, 4], [1, 17, 3]]
</code>```

It should have returned different lists (first,last element be different). Returned lists last elements are different but first elements are same.

If the code worked properly it would have returned [1,17,4],[2,17,3]. (I marked the differences in bold.)

I need to first and last elements be different. But why this code not working properly ?

答:
In your code, [2, 17, 3] never gets picked up because 3 is already in d after [1, 17, 3] is added.

Here's one approach that may work. Keep a dictionary that keeps track of what elements were in first and last places in sublists and only append sublists that don't have already existing first or last elements:

```<code>taken = {'first':set(), 'last':set()}
d = {}
for l in b:
    if l[2] not in taken['last']:
        taken['last'].add(l[2])
        d[l[2]] = l
    else:
        if l[0] not in taken['first']:
            taken['first'].add(l[0])
            d[l[2]] = l
out = list(d.values())

</code>```

Output:

```<code>[[1, 17, 4], [2, 17, 3]]
</code>```

Body:
I need to group nested lists by first element and last element differences.

I have a nested list like :

[[1, 17, 4], [1, 17, 3],  [2, 17, 3]]

This is my code :

This creates dict and checks first and last element not in dict. If first and last element not in dict, saves list to dict.

b = [[1, 17, 4], [1, 17, 3],  [2, 17, 3]]
d = {}

for l in b:
    if l[2] not in d and l[0] not in d:
        d[l[2]] = [l[0],l[1],l[2]]

res = list(d.values())

print(res)

This returns :

[[1, 17, 4], [1, 17, 3]]

It should have returned different lists (first,last element be different). Returned lists last elements are different but first elements are same.

If the code worked properly it would have returned [1,17,4],[2,17,3]. (I marked the differences in bold.)

I need to first and last elements be different. But why this code not working properly ?

Body:
In your code, [2, 17, 3] never gets picked up because 3 is already in d after [1, 17, 3] is added.

Here's one approach that may work. Keep a dictionary that keeps track of what elements were in first and last places in sublists and only append sublists that don't have already existing first or last elements:

taken = {'first':set(), 'last':set()}
d = {}
for l in b:
    if l[2] not in taken['last']:
        taken['last'].add(l[2])
        d[l[2]] = l
    else:
        if l[0] not in taken['first']:
            taken['first'].add(l[0])
            d[l[2]] = l
out = list(d.values())

Output:

[[1, 17, 4], [2, 17, 3]]


问:
comparing values of settings.bundle toggle switch
How can I compare settings.bundle toggle switch value correctly? Toggle switch is named enableAnotherUser.

```<code>NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults synchronize];

if([defaults objectForKey:@"enableAnotherUser"]==1) // here i tried from 1, 0, nil, null, isEqual,... and none seem to work correctly?
    {}
else
{}
</code>```

po in console for [defaults objectForKey:@"enableAnotherUser"] returns 1.. but ==1 in if doesn't seem to matter, the program always goes to else part. Plus this warning on comparing 1, but not on 0: comparison between pointer and integer.

What should I do?

答:
@kikovi - try something like this...</p>

```<code>BOOL enableAnotherUser = [[NSUserDefaults standardUserDefaults] boolForKey:@"enableAnotherUser"];
if(enableAnotherUser) {
...
}
else {
...
}
</code>```

Body:
How can I compare settings.bundle toggle switch value correctly? Toggle switch is named enableAnotherUser.

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults synchronize];

if([defaults objectForKey:@"enableAnotherUser"]==1) // here i tried from 1, 0, nil, null, isEqual,... and none seem to work correctly?
    {}
else
{}

po in console for [defaults objectForKey:@"enableAnotherUser"] returns 1.. but ==1 in if doesn't seem to matter, the program always goes to else part. Plus this warning on comparing 1, but not on 0: comparison between pointer and integer.

What should I do?

Body:
@kikovi - try something like this...

BOOL enableAnotherUser = [[NSUserDefaults standardUserDefaults] boolForKey:@"enableAnotherUser"];
if(enableAnotherUser) {
...
}
else {
...
}


问:
How to hide collapsible Bootstrap navbar on click
I've created this collapsable navbar using Bootstrap 4 that works nicely, but I would like it to close when the user clicks on a link. Any way to do this?  Thanks

html navbar:

```<code><nav class="navbar navbar-toggleable-md fixed-top">

<button id="nav-btn"class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarDiv"  aria-expanded="false" aria-label="Toggle navigation">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
 </button>

            <div class="container">

                <a class="navbar-brand" href="#"><img src="Images/logo.png" width="60px"></a>

                    <div class="collapse navbar-collapse" id="navbarDiv">

                        <ul class="navbar-nav mr-auto">

                            <li class="nav-item active">

                                <a class="nav-link" href="#home">Home <span class="sr-only">(current)</span></a>

                            </li>

                            <li class="nav-item">

                                <a class="nav-link" href="#about-us">About</a>

                            </li>

                            <li class="nav-item">

                                <a class="nav-link" href="#pricing">Pricing</a>

                            </li>

                        </ul>

                    </div>

            </div>

        </nav>
</code>```

css for .icon-bar, since Bootstrap 4 doesn't use the icon-bar class.

```<code>.navbar-toggler .icon-bar {
  margin: 7px;
  display: block;
  width: 22px;
  height: 1px;
  background-color: #cccccc;
  border-radius: 1px;
}
</code>```

答:
I have modified the answer of Zim.
Now the code closes the navbar only in case it is open.</p>
```<code>const navLinks = document.querySelectorAll('.nav-item')
const menuToggle = document.getElementById('navbarSupportedContent')
const bsCollapse = new bootstrap.Collapse(menuToggle, {
  toggle: false
})
navLinks.forEach((l) => {
    l.addEventListener('click', () => {
        if(bsCollapse._isShown()){
            bsCollapse.hide()
        }
    })
})
</code>```

Body:
I've created this collapsable navbar using Bootstrap 4 that works nicely, but I would like it to close when the user clicks on a link. Any way to do this?  Thanks

html navbar:

<button id="nav-btn"class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarDiv"  aria-expanded="false" aria-label="Toggle navigation">

 </button>

                                Home (current)

                                About

                                Pricing

css for .icon-bar, since Bootstrap 4 doesn't use the icon-bar class.

.navbar-toggler .icon-bar {
  margin: 7px;
  display: block;
  width: 22px;
  height: 1px;
  background-color: #cccccc;
  border-radius: 1px;
}

Body:
I have modified the answer of Zim.
Now the code closes the navbar only in case it is open.

const navLinks = document.querySelectorAll('.nav-item')
const menuToggle = document.getElementById('navbarSupportedContent')
const bsCollapse = new bootstrap.Collapse(menuToggle, {
  toggle: false
})
navLinks.forEach((l) => {
    l.addEventListener('click', () => {
        if(bsCollapse._isShown()){
            bsCollapse.hide()
        }
    })
})


问:
How to make the specified nodes horizontally aligned in Mermaid?
This is my flowchart:

```<code>graph TB
    aaa ---> bbb ---> ddd & ccc
    ddd -.-> fff
    ccc --->|eee| fff
    fff ---> hhh & ggg & kkk
    hhh --->|iii| mmm
    ggg & kkk -.-> mmm
</code>```

But actually I want the node ccc and node ddd to be aligned horizontally. And the hhh , node ggg and kkk to be aligned horizontally. Is it possible?

Of course, the purpose of this post is to think about how to align these nodes horizontally, but if possible I would also like to make these edges as short as possible to save space while aligning them. For example, I want the node ddd to go up, not the node ccc to come down

答:
You can achieve this by using longer or shorter arrows, which changes the minimum link length between nodes:

```<code>graph TB
    aaa ---> bbb ---> ddd & ccc
    ddd -..-> fff
    %%   ^^ extra .
    ccc --->|eee| fff
    fff ---> hhh & ggg & kkk
    hhh --->|iii| mmm
    ggg & kkk -..-> mmm
    %%         ^^ extra .
</code>```

Body:
This is my flowchart:

graph TB
    aaa ---> bbb ---> ddd & ccc
    ddd -.-> fff
    ccc --->|eee| fff
    fff ---> hhh & ggg & kkk
    hhh --->|iii| mmm
    ggg & kkk -.-> mmm

But actually I want the node ccc and node ddd to be aligned horizontally. And the hhh , node ggg and kkk to be aligned horizontally. Is it possible?

Of course, the purpose of this post is to think about how to align these nodes horizontally, but if possible I would also like to make these edges as short as possible to save space while aligning them. For example, I want the node ddd to go up, not the node ccc to come down

Body:
You can achieve this by using longer or shorter arrows, which changes the minimum link length between nodes:

graph TB
    aaa ---> bbb ---> ddd & ccc
    ddd -..-> fff
    %%   ^^ extra .
    ccc --->|eee| fff
    fff ---> hhh & ggg & kkk
    hhh --->|iii| mmm
    ggg & kkk -..-> mmm
    %%         ^^ extra .


问:
CSS - Background image
I am not sure how to change the background of an image tag in css. For example, I have a darker background in my webpage. Let's say I include an image of a purple X with a white background. How would I change the background of that purple X image to be the same color as my body.</p>

答:
You could add mix-blend-mode: multiply; to your 's css. It will render the white 'transparent' but it'll also alter the other colors in the image.
Best solution would probably be to use transparent PNGs.

Title: CSS - Background image

Body:
You could add mix-blend-mode: multiply; to your <img>'s css. It will render the white 'transparent' but it'll also alter the other colors in the image.
Best solution would probably be to use transparent PNGs.


问:
C++ Same include line in 2 files in the same folder: one works, another can't find the file
Windows 10
Eclipse IDE for C/C++ Developers
Version: Kepler Service Release 2
Build id: 20140224-0627

I'm trying to use imgui. Unfortunately, documentation is pretty shady about how to get it working.

So, in order to get it working, I think I need something called "glad". Whatever it is, the only source of it seems to be some shady-looking one-pager that generates the files for you (found a link to it here).

Anyway, I checked all the boxes I needed (copied from the screenshot from the provided link). I don't understand much about what it is (very roughly), I simply want to get imgui running (ha-ha on me, imgui also needs some other stuff scattered around internet, but it's my next problem, not current).

Anyway, in my new C++ project in eclipse I created a folder "include" and added its path into "C/C++ General -> Paths and Symbols". So when I write "#include "glad/glad.h" in my "test3.cpp" (file with main function, project called test3), I'm ok. But I can't build it because glad.c, which is located in the SAME folder as test3.cpp, has the identical include line, but it gives an error that it can't find it. Sounds like some nonsense to me.

```<code>#include "glad/glad.h"
#include <iostream>
using namespace std;
//for those who wanted to copy default hello world program
int main() {
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    return 0;
}
</code>```

How is this even possible? Looks like a total nonsense to me. They're in the same folder. Test3 sees the file, glad.c doesn't. I tried replacing "<>" in include in glad.c with quotes like in test3.c, same thing. One file works, another doesn't.

What can I do about it?

答:
Eclipse separates the include paths for C and C++ files. If you have a program combining both C and C++ files, the correct include paths need to be set for both languages.

Navigate to the C/C++ General -> Paths and Symbols -> Includes tab. You will see both languages (and probably Assembly) listed under Languages. Pick the correct language or when adding the path, check the Add to all languages box.

Body:
Windows 10
Eclipse IDE for C/C++ Developers
Version: Kepler Service Release 2
Build id: 20140224-0627

I'm trying to use imgui. Unfortunately, documentation is pretty shady about how to get it working.

So, in order to get it working, I think I need something called "glad". Whatever it is, the only source of it seems to be some shady-looking one-pager that generates the files for you (found a link to it here).

Anyway, I checked all the boxes I needed (copied from the screenshot from the provided link). I don't understand much about what it is (very roughly), I simply want to get imgui running (ha-ha on me, imgui also needs some other stuff scattered around internet, but it's my next problem, not current).

Anyway, in my new C++ project in eclipse I created a folder "include" and added its path into "C/C++ General -> Paths and Symbols". So when I write "#include "glad/glad.h" in my "test3.cpp" (file with main function, project called test3), I'm ok. But I can't build it because glad.c, which is located in the SAME folder as test3.cpp, has the identical include line, but it gives an error that it can't find it. Sounds like some nonsense to me.

#include "glad/glad.h"
#include <iostream>
using namespace std;
//for those who wanted to copy default hello world program
int main() {
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    return 0;
}

How is this even possible? Looks like a total nonsense to me. They're in the same folder. Test3 sees the file, glad.c doesn't. I tried replacing "<>" in include in glad.c with quotes like in test3.c, same thing. One file works, another doesn't.

What can I do about it?


答:
IIUC you want to filter sublists to ensure the first and last element is unique relative to the previous sublists.

You could use sets to keep track of the seen values:

```<code>b = [[1, 17, 4], [1, 17, 3],  [2, 17, 3]]

first = set()
last  = set()

out = []
for x in b:
    if x[0] not in first and x[-1] not in last:
        out.append(x)
        first.add(x[0])
        last.add(x[-1])
</code>```

Output: [[1, 17, 4], [2, 17, 3]]

Title: How to group nested list by first,last element differences in Python?

Body:
IIUC you want to filter sublists to ensure the first and last element is unique relative to the previous sublists.

You could use sets to keep track of the seen values:

b = [[1, 17, 4], [1, 17, 3],  [2, 17, 3]]

first = set()
last  = set()

out = []
for x in b:
    if x[0] not in first and x[-1] not in last:
        out.append(x)
        first.add(x[0])
        last.add(x[-1])

Output: [[1, 17, 4], [2, 17, 3]]


问:
how can I avoid buffer overflow in this case?
I have this exercise: "create a function in order to subtract two strings".

my attempt works just fine (with the help of an old answer here on stack overflow). The problem is that when I debug, the debugger doesn't warn me on anything, but I have a grey squiggle below the argument of malloc. visual studio says that "a sub-expression may overflow before being assigned to a wider type". This is my thought: "I need to write an if-check before malloc to make sure the sub-expression won't overflow. To do it, I've thought to do this way:
int sum = length + 1; if (condition), then do this (allocation)."
the problem is that I don't know the condition to be checked.
based on an old discussion here on stack overflow, I know that if I have a subtraction I have to do this way

```<code>int c = a - b;
if (c >= a) {
// do allocation;
} else {
return NULL;
}
</code>```

but it works only for subtraction, but if I have an addition this method fails.
therefore, this method doesn't work.

how can I do it?

```<code>#include <stdlib.h>
#include <stdio.h>
#
char* subtract(const char* a, const char* b) {
    int a_1 = atoi(a); int b_1 = atoi(b); int result = 0;
    result = a_1 - b_1;
    int length = snprintf(NULL, 0, "%d", result);
    char* str = malloc(length + 1);
    if (str == NULL) {
        return NULL;
    }
    snprintf(str, length + 1, "%d", result);
    return str;
}

int main(void) {
    char a[] = "4567";
    char b[] = "568";
    char* c;
    c = subtract(a, b);

    return 0;
}
</code>```

答:
but I have a little warning. it's located in the argument of malloc,
as I said.

malloc(length + 1);

length is signed integer and it can overflow if you add 1 to it.

Solution:
cast it to size_t

```<code>malloc((size_t)length + 1);
</code>```

BTW
What is the difference between "little" and "big" warnings?

PS How to substract "4564536456645645645" and "545643563456436565436" using your solution?

Body:
I have this exercise: "create a function in order to subtract two strings".

my attempt works just fine (with the help of an old answer here on stack overflow). The problem is that when I debug, the debugger doesn't warn me on anything, but I have a grey squiggle below the argument of malloc. visual studio says that "a sub-expression may overflow before being assigned to a wider type". This is my thought: "I need to write an if-check before malloc to make sure the sub-expression won't overflow. To do it, I've thought to do this way:
int sum = length + 1; if (condition), then do this (allocation)."
the problem is that I don't know the condition to be checked.
based on an old discussion here on stack overflow, I know that if I have a subtraction I have to do this way

int c = a - b;
if (c >= a) {
// do allocation;
} else {
return NULL;
}

but it works only for subtraction, but if I have an addition this method fails.
therefore, this method doesn't work.

how can I do it?

#include <stdlib.h>
#include <stdio.h>
#
char* subtract(const char* a, const char* b) {
    int a_1 = atoi(a); int b_1 = atoi(b); int result = 0;
    result = a_1 - b_1;
    int length = snprintf(NULL, 0, "%d", result);
    char* str = malloc(length + 1);
    if (str == NULL) {
        return NULL;
    }
    snprintf(str, length + 1, "%d", result);
    return str;
}

int main(void) {
    char a[] = "4567";
    char b[] = "568";
    char* c;
    c = subtract(a, b);

    return 0;
}

Body:
but I have a little warning. it's located in the argument of malloc,
as I said.

malloc(length + 1);

length is signed integer and it can overflow if you add 1 to it.

Solution:
cast it to size_t

malloc((size_t)length + 1);

BTW
What is the difference between "little" and "big" warnings?

PS How to substract "4564536456645645645" and "545643563456436565436" using your solution?


问:
How solve problem with installing web3 for python in windows?
I'm trying install web3 for python3.7.5 on windows 10. But I get this error every time . I don't know what should I do, because I have already installed "Microsoft Visual C++ 14.0" and Build Tools. I tried also installing in vitrual enviroment, but it  ended with same error. Thanks for your advice.</p>
```<code>  Building wheel for lru-dict (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: 'c:\python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Žaneta\\AppData\\Local\\Temp\\pip-install-p2lk_xob\\lru-dict\\setup.py'"'"'; __file__='"'"'C:\\Users\\Žaneta\\AppData\\Local\\Temp\\pip-install-p2lk_xob\\lru-dict\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Žaneta\AppData\Local\Temp\pip-wheel-89ed3hox'
       cwd: C:\Users\Žaneta\AppData\Local\Temp\pip-install-p2lk_xob\lru-dict\
  Complete output (5 lines):
  running bdist_wheel
  running build
  running build_ext
  building 'lru' extension
  error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
  ----------------------------------------
</code>```

答:
I know this is old but for anyone who runs into this issue, I got it solved by following a solution posted on github

This is the solution:

Install Visual Studio Build Tools here

Select the "Desktop development with C++" Workload for installation (it is about 6GB)

Finish installation and reboot PC

Open the terminal and retry pip install web3

Screenshot of the workload needed

Body:
I'm trying install web3 for python3.7.5 on windows 10. But I get this error every time . I don't know what should I do, because I have already installed "Microsoft Visual C++ 14.0" and Build Tools. I tried also installing in vitrual enviroment, but it  ended with same error. Thanks for your advice.

  Building wheel for lru-dict (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: 'c:\python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Žaneta\\AppData\\Local\\Temp\\pip-install-p2lk_xob\\lru-dict\\setup.py'"'"'; __file__='"'"'C:\\Users\\Žaneta\\AppData\\Local\\Temp\\pip-install-p2lk_xob\\lru-dict\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Žaneta\AppData\Local\Temp\pip-wheel-89ed3hox'
       cwd: C:\Users\Žaneta\AppData\Local\Temp\pip-install-p2lk_xob\lru-dict\
  Complete output (5 lines):
  running bdist_wheel
  running build
  running build_ext
  building 'lru' extension
  error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
  ----------------------------------------


问:
Vite Server is running but not working on localhost
Vite + Reactjs server is running but I am getting
"This localhost page can’t be found
No webpage was found for the web address: https://localhost:4200/"
on the browser</p>

答:
A common mistake when moving from create react app/react-scripts to Vite is having the index.html in the public folder.
Make sure your index.html file is in the root directory for your Vite project.