问:
How to filter object entries to keep only those whose keys start with a string, using ramda?
Having the following array:

const vegsAndFruits = [
    {
        "fruit_banana": 10,
        "fruit_apple": 1,
        "veg_tomato": 3,
        "fruit_watermelon": 11
    },
    {
        "veg_carrot": 3,
        "veg_garlic": 11,
        "veg_potato": 0,
        "fruit_apricot": 22
    },
    {
        "veg_eggplant": 2,
        "veg_cabbage": 1,
        "fruit_strawberry": 100,
        "fruit_orange": 30
    }
]
```
<p>I want to filter it to return the same array <strong>but</strong> to keep only the properties that start with <code>"fruit"</code>.</p>
<p><em>Expected output</em></p>
<pre class="lang-js prettyprint-override"><code>const expectedOutput = [
    {
        "fruit_banana": 10,
        "fruit_apple": 1,
        "fruit_watermelon": 11
    },
    {
        "fruit_apricot": 22
    },
    {
        "fruit_strawberry": 100,
        "fruit_orange": 30
    }
]
</code>```

My attempt

I thought the solution should come from mixing ramda's R.startsWith() and R.pickBy(). But the following doesn't work as I expected:

const R = require("ramda")

R.map(R.pickBy(R.startsWith(["fruit"])),vegsAndFruits)
```
<p>which returns</p>
<pre class="lang-js prettyprint-override"><code>// [ {}, {}, {} ]
</code>```

What am I missing here?

答:
The pickby function takes two parameters, value and key.

You can run R.map(R.pickBy((_, key) => key.startsWith('fruit')),vegsAndFruits) to get the result you want.

Body:
Having the following array:

const vegsAndFruits = [
    {
        "fruit_banana": 10,
        "fruit_apple": 1,
        "veg_tomato": 3,
        "fruit_watermelon": 11
    },
    {
        "veg_carrot": 3,
        "veg_garlic": 11,
        "veg_potato": 0,
        "fruit_apricot": 22
    },
    {
        "veg_eggplant": 2,
        "veg_cabbage": 1,
        "fruit_strawberry": 100,
        "fruit_orange": 30
    }
]

I want to filter it to return the same array but to keep only the properties that start with "fruit".

Expected output

const expectedOutput = [
    {
        "fruit_banana": 10,
        "fruit_apple": 1,
        "fruit_watermelon": 11
    },
    {
        "fruit_apricot": 22
    },
    {
        "fruit_strawberry": 100,
        "fruit_orange": 30
    }
]

My attempt

I thought the solution should come from mixing ramda's R.startsWith() and R.pickBy(). But the following doesn't work as I expected:

const R = require("ramda")

R.map(R.pickBy(R.startsWith(["fruit"])),vegsAndFruits)

which returns

// [ {}, {}, {} ]

What am I missing here?


来源: stackexchange

问:
How to let the user select multiple choices while filtering data using django-filter?
I have a model:

```<code>class Radiations(models.Model):
    patient=models.ForeignKey(Patient, on_delete=CASCADE)
    patient_type=models.ForeignKey(PatientType, on_delete=CASCADE, default=None)
    date=models.DateField(default=datetime.date.today)
    done_fractions=models.IntegerField(default=0)
    base_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=None)
    expected_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=None)
    remarks=models.TextField(max_length=500, blank=True, default=None)
    radiations_date=models.DateTimeField(auto_now_add=True)
    modified_on=models.DateTimeField(auto_now=True)
</code>```

Its filter looks like this:

```<code>class RadiationsFilters(django_filters.FilterSet):
    patient__name=django_filters.CharFilter(lookup_expr='icontains', label='Name')
    from_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'type': 'date'}), field_name='date', label='From - Date ', lookup_expr='gte')
    to_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'type': 'date'}), field_name='date', label='To - Date ', lookup_expr='lte')
</code>```

Now, I want the user to be able to select multiple patients which are saved in the database, how can I bring them into my filter code? Someone please help. Thanks in advance.

答:
Just add a new filter field like:</p>
```<code>patients = django_filters.ModelMultipleChoiceFilter(
    queryset=Patient.objects.all()
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a model:

class Radiations(models.Model):
    patient=models.ForeignKey(Patient, on_delete=CASCADE)
    patient_type=models.ForeignKey(PatientType, on_delete=CASCADE, default=None)
    date=models.DateField(default=datetime.date.today)
    done_fractions=models.IntegerField(default=0)
    base_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=None)
    expected_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=None)
    remarks=models.TextField(max_length=500, blank=True, default=None)
    radiations_date=models.DateTimeField(auto_now_add=True)
    modified_on=models.DateTimeField(auto_now=True)

Its filter looks like this:

class RadiationsFilters(django_filters.FilterSet):
    patient__name=django_filters.CharFilter(lookup_expr='icontains', label='Name')
    from_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'type': 'date'}), field_name='date', label='From - Date ', lookup_expr='gte')
    to_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'type': 'date'}), field_name='date', label='To - Date ', lookup_expr='lte')

Now, I want the user to be able to select multiple patients which are saved in the database, how can I bring them into my filter code? Someone please help. Thanks in advance.

Body:
Just add a new filter field like:

patients = django_filters.ModelMultipleChoiceFilter(
    queryset=Patient.objects.all()
)


问:
How to avoid "-internal-autofill-selected" style to be applied?
I have a login form with 2 fields, username and password. Username field is autocompleted by chrome. When I submit the form (when it is valid), this style is applied mysteriously:

```<code>input:-internal-autofill-selected {s ñ
    background-color: rgb(232, 240, 254) !important;
    background-image: none !important;
    color: -internal-light-dark-color(black, white) !important;
}
</code>```

Is there a way to avoid that? The form is submitted using Ajax, so it is a little ugly if for Username field that style is applied, but for Password field it is not.

I noticed that this happen only if field is filled with an element in the chrome sugggestions list. If field is filled with a value that is not in the list, the style is not applied.

Regards
Jaime

答:
If you're ok with the default -internal-autofill-selected styling on a light theme and just want it to look nicer in a dark theme then you might just need:

```<code>input {
  color-scheme: dark;
}
</code>```

Body:
I have a login form with 2 fields, username and password. Username field is autocompleted by chrome. When I submit the form (when it is valid), this style is applied mysteriously:

input:-internal-autofill-selected {s ñ
    background-color: rgb(232, 240, 254) !important;
    background-image: none !important;
    color: -internal-light-dark-color(black, white) !important;
}

Is there a way to avoid that? The form is submitted using Ajax, so it is a little ugly if for Username field that style is applied, but for Password field it is not.

I noticed that this happen only if field is filled with an element in the chrome sugggestions list. If field is filled with a value that is not in the list, the style is not applied.

Regards
Jaime

Body:
If you're ok with the default -internal-autofill-selected styling on a light theme and just want it to look nicer in a dark theme then you might just need:

input {
  color-scheme: dark;
}


问:
Retrieve only a particular number of child records
If I write

```<code>db.Topics.Include("ChildTopics")
</code>```

then it gives all the child comments for that. But what I want is only the top two child topics ordered by "childtopic created date".

答:
Include does an early load of all dependencies, but I am not aware of a way to apply restrictions on this implementation.

An alternate way would be to shape the results like:

```<code>var comments = db.Topics.Select(_x=>
                    new{
                        Topic = _x,
                        TopTwoChildTopics = _x.ChildTopics.Top(2)
                       });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If I write

db.Topics.Include("ChildTopics")

then it gives all the child comments for that. But what I want is only the top two child topics ordered by "childtopic created date".

Body:
Include does an early load of all dependencies, but I am not aware of a way to apply restrictions on this implementation.

An alternate way would be to shape the results like:

var comments = db.Topics.Select(_x=>
                    new{
                        Topic = _x,
                        TopTwoChildTopics = _x.ChildTopics.Top(2)
                       });


问:
TreeView width unexpectedly changes
I have a Frame that contains Treeview and a Frame-embedded-in-a-Canvas.
Treeview displays documents from MongoDB in one '#0' column and every time a user selects any document I generate from document's fields a list of Checkbuttons in the Frame-embedded-in-a-Canvas.

The issue I got is that Treeview width is not constant, but I just can't understand why it changes and when exactly it happens.
Every time after generating new Checkbuttons list my Treeview width grows by 30 pixels without any regard to the fact that both the Treeview and the Frame-embedded-in-a-Canvas are expected to be in parent's grid columns 0 and 1 respectively with zero weight.

Here's a link to the GIF showing how it looks. And below you can find my code concerning these widgets.

Show me please where to look for this issue reason.

def treeview_reload():
    dt_tv.delete(*dt_tv.get_children())
    dt_tv.insert('', 'end', '_b_', text='biomes')
    dt_tv.insert('', 'end', '_z_', text='zones')
    dt_tv.insert('', 'end', '_p_', text='points')
    dt_tv.insert('', 'end', '_m_', text='biomaterials')
    dt_tv.insert('', 'end', '_c_', text='characters')

def tv_sel_handler(event):
    try:
        sel_iid = event.widget.selection()[0]
    except IndexError:
        sel_iid = ''
    try:
        generate_model(MAP[sel_iid])
    except KeyError:
        pass

def generate_model(document, new_list=True, row=0, indent=0):
    if new_list:
        for c in list(dt_model.children.values()):
            c.destroy()
    i = row
    for field in document.keys():
        if type(document[field]) is list:
            cb = ttk.Label(dt_model, text=indent*2*' '+field)
            cb.grid(row=i, column=0, sticky='w', padx=30, pady=4)
            cb['font'] = ("Noto Mono", 13)
        else:
            cb = ttk.Checkbutton(dt_model, text=indent*2*' '+field)
            cb.grid(row=i, column=0, sticky='w')
            ttk.Style().configure('Mono.TCheckbutton', font=("Noto Mono", 13))
            cb['style'] = 'Mono.TCheckbutton'
            if type(document[field]) is dict:
                i = generate_model(document[field], False, i+1, indent+1)
    if i > 17:
        vsb = ttk.Scrollbar(pdb_data, orient=VERTICAL, command=dt_canv.yview)
        dt_canv['yscrollcommand'] = vsb.set
        vsb.grid(row=0, column=2, sticky='nsw')
        dt_model.bind('<Configure>',
                      lambda event, canvas=dt_canv:
                            canvas.configure(scrollregion=canvas.bbox("all")))
        dt_model.bind('<Enter>',
                      lambda event:
                            dt_canv.bind_all("<MouseWheel>",
                                             lambda event:
                                                    dt_canv.yview_scroll(int(-1*(event.delta/120)), "units")))
        dt_model.bind('<Leave>',
                      lambda event: dt_canv.unbind_all("<MouseWheel>"))
    return i

# ...
# ___ frame for the data
pdb_data = ttk.Frame(page_db, width=1250, height=450)
pdb_data.grid(row=6, column=0, columnspan=2, sticky='nsew', pady=24)
# ____ categorized documents list
dt_tv = ttk.Treeview(pdb_data, selectmode='browse', show=('tree',))
dt_tv.column('#0', width=250)
dt_tv.grid(row=0, column=0, sticky='nsw')
dt_tv.bind('<<TreeviewSelect>>', tv_sel_handler)
treeview_reload()
# ____ auxiliary canvas
dt_canv = Canvas(pdb_data, borderwidth=0, width=200)
dt_canv.grid(row=0, column=1, sticky='nsw', padx=5)
# _____ frame-embedded-in-a-canvas for checkbuttons list
dt_model = ttk.Frame(pdb_data, takefocus=0)
dt_canv.create_window((0,0), window=dt_model, anchor='nw')

pdb_data.rowconfigure(0, weight=1)
```

答:
I have found a way how to prevent unexpected Treeview column width change. My solution is to remove Treeview from grid, then explicitly set column width and once again grid Treeview. The code is below.

But couldn't understand a reason of such behaviour. Any explanation is appreciated.

def treeview_reload():
    dt_tv.delete(*dt_tv.get_children())
    dt_tv.insert('', 'end', '_b_', text='biomes')
    dt_tv.insert('', 'end', '_z_', text='zones')
    dt_tv.insert('', 'end', '_p_', text='points')
    dt_tv.insert('', 'end', '_m_', text='biomaterials')
    dt_tv.insert('', 'end', '_c_', text='characters')

def tv_sel_handler(event):
    try:
        sel_iid = event.widget.selection()[0]
    except IndexError:
        sel_iid = ''
    try:
        generate_model(MAP[sel_iid])
    except KeyError:
        pass

def generate_model(document, new_list=True, row=0, indent=0):
    # do not destroy Checkbuttons if recursive call
    if new_list:
        for c in list(dt_model.children.values()):
            c.destroy()
    i = row
    for field in document.keys():
        if type(document[field]) is list:
            cb = ttk.Label(dt_model, text=indent*2*' '+field, font=("Noto Mono", 13))
            cb.grid(row=i, column=0, sticky='w', padx=30, pady=4)
        else:
            ttk.Style().configure('Mono.TCheckbutton', font=("Noto Mono", 13))
            cb = ttk.Checkbutton(dt_model,
                                 text=indent*2*' '+field,
                                 style='Mono.TCheckbutton')
            cb.grid(row=i, column=0, sticky='w')
            if type(document[field]) is dict:
                i = generate_model(document[field], False, i+1, indent+1)
    # only for recursive call
    if not new_list:
        return i
    # this is here because Treeview width changes if grid only once
    dt_tv.grid_remove()
    dt_tv.column('#0', width=220)
    dt_tv.grid(row=0, column=0, sticky='nsw')
    # place vertical Scrollbar if needed and connect MouseWheel
    if i > dt_canv.winfo_height() // 28:
        vsb.grid(row=0, column=2, sticky='nsw')
        dt_model.bind('<Configure>',
                      lambda event, canvas=dt_canv:
                            canvas.configure(scrollregion=canvas.bbox("all")))
        dt_model.bind('<Enter>',
                      lambda event:
                            dt_canv.bind_all("<MouseWheel>",
                                             lambda event:
                                                    dt_canv.yview_scroll(int(-1*(event.delta/120)), "units")))
        dt_model.bind('<Leave>',
                      lambda event: dt_canv.unbind_all("<MouseWheel>"))
    else:
        dt_canv.unbind_all('<MouseWheel>')
        dt_model.unbind_all('<Configure>')
        vsb.grid_remove()

# ...
# ___ frame for the data
pdb_data = ttk.Frame(page_db, width=1250, height=450)
pdb_data.grid(row=6, column=0, columnspan=2, sticky='nsew', pady=24)
# ____ categorized documents list
dt_tv = ttk.Treeview(pdb_data, selectmode='browse', show=('tree',))
dt_tv.column('#0', width=250)
dt_tv.grid(row=0, column=0, sticky='nsw')
dt_tv.bind('<<TreeviewSelect>>', tv_sel_handler)
treeview_reload()
# ____ auxiliary canvas
dt_canv = Canvas(pdb_data, borderwidth=0, width=200)
dt_canv.grid(row=0, column=1, sticky='nsw', padx=5)
# _____ frame-embedded-in-a-canvas for checkbuttons list
dt_model = ttk.Frame(pdb_data, takefocus=0)
dt_canv.create_window((0,0), window=dt_model, anchor='nw')
# ____ vertical scrollbar for frame
vsb = ttk.Scrollbar(pdb_data, orient=VERTICAL, command=dt_canv.yview)
dt_canv['yscrollcommand'] = vsb.set

pdb_data.rowconfigure(0, weight=1)
```

Title: TreeView width unexpectedly changes


问:
why does my hangman code keep coming back with an error saying " IndexError: list index out of range"
here is my code
my assignment is to create a hangman game that picks word from an outside text file, pick a word, close the file, then start the game. I think the problem is with opening the text file. I'm not sure if I'm saving it in the right spot or whatever. pls help.</p>
```<code>    import random
#extract a random word from a text file

def word_selected(fname):
    word_file = open('hangman list.txt','r+')
    secret_word = random.choice(word_file.read().split())
    word_file.close()
    return secret_word
secret_word = word_selected('hangman list.txt')
print(secret_word)
#Display randomly chosen word in dash:
def word_selected_dashed():
    word_selected_dashed = []
    for i in range(len(secret_word)):
        word_selected_dashed.append('_')
    return ''.join(word_selected_dashed)

word_selected_dashed = word_selected_dashed()
print(word_selected_dashed)

trials = 5

gussed_word = list(word_selected_dashed)

while trials > 0:
    if ''.join(gussed_word) == secret_word:
        print("Congraluation, you have gussed the correct word")
        break

    print('you have got '+ str(trials)+ ' wrong tries ')
    user_guseed_letter = input('Guess a letter >>>>> \n')

    if user_guseed_letter in secret_word:
        print('Correct!')
        for i in range(len(secret_word)):
            if list(secret_word)[i] == user_guseed_letter:
                gussed_word[i] = user_guseed_letter
        print(''.join(gussed_word))

    elif user_guseed_letter not in secret_word:
        print('wrong!')
        trials -= 1
        hang = display_hangman(tries=(5-trials))
        print(hang)
if trials == 0 :
    print('you have ran out of trials')
</code>```

答:
One issue I notice is in the word_selected function, you have an input of fname, then use a specific file name within the function. Instead of writing out the actual file name, use the variable you used in the function name (ie fname).

Also, make sure the file is in the same directory (folder) of your Python file. If its in a different directory, you can also specify the whole file path as the file name.

Body:
here is my code
my assignment is to create a hangman game that picks word from an outside text file, pick a word, close the file, then start the game. I think the problem is with opening the text file. I'm not sure if I'm saving it in the right spot or whatever. pls help.

    import random
#extract a random word from a text file

def word_selected(fname):
    word_file = open('hangman list.txt','r+')
    secret_word = random.choice(word_file.read().split())
    word_file.close()
    return secret_word
secret_word = word_selected('hangman list.txt')
print(secret_word)
#Display randomly chosen word in dash:
def word_selected_dashed():
    word_selected_dashed = []
    for i in range(len(secret_word)):
        word_selected_dashed.append('_')
    return ''.join(word_selected_dashed)

word_selected_dashed = word_selected_dashed()
print(word_selected_dashed)

trials = 5

gussed_word = list(word_selected_dashed)

while trials > 0:
    if ''.join(gussed_word) == secret_word:
        print("Congraluation, you have gussed the correct word")
        break

    print('you have got '+ str(trials)+ ' wrong tries ')
    user_guseed_letter = input('Guess a letter >>>>> \n')

    if user_guseed_letter in secret_word:
        print('Correct!')
        for i in range(len(secret_word)):
            if list(secret_word)[i] == user_guseed_letter:
                gussed_word[i] = user_guseed_letter
        print(''.join(gussed_word))

    elif user_guseed_letter not in secret_word:
        print('wrong!')
        trials -= 1
        hang = display_hangman(tries=(5-trials))
        print(hang)
if trials == 0 :
    print('you have ran out of trials')


问:
File not found when file does exist and can be opened
I have a macro-enabled workbook, that has a macro that should save a copy of the file to a new location. I store the name of the original file as a string before saving to the new location, so that I can still reference the original file in the original location. The file still exists there, and the filename string works when I open the file using it, but it doesn't work when I try to do anything else with the string.

The original location is a folder called Source, and the file is copied to the folder called Destination.

The important problem here, is that the folders are located on SharePoint. If the folders are on a local machine it's not an issue.

```<code>https://[company].sharepoint.com/sites/[team]/Shared Documents/General/Source/oldVersion.xlsm

https://[company].sharepoint.com/sites/[team]/Shared Documents/General/Destination/newVersion.xlsm
</code>```

Sub testMove()

    FullName = Application.ActiveWorkbook.FullName

    ActiveWorkbook.SaveAs "https://[company].sharepoint.com/sites/" _
& "[team]/Shared Documents/General/Destination/newVersion.xlsm", xlOpenXMLWorkbookMacroEnabled

    'SetAttr FullName, vbNormal
    Workbooks.Open FullName

End Sub
```

The above code runs just fine, but when you uncomment the setAttr it gets a file not found error.

The goal is to be able to close and/or delete the file in the original location, so SaveCopyAs doesn't quite work for this purpose.

答:
SaveAs and Delete

This works for me. Your feedback is most welcome.

Option Explicit

Sub TestMove()

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim sFilePath As String: sFilePath = wb.FullName

    Dim dFilePath As String: dFilePath = "C:\Users\[username]\OneDrive\" _
        & "Documents\Destination\newVersion.xlsm"

    Application.DisplayAlerts = False ' overwrite without confirmation
    wb.SaveAs dFilePath, xlOpenXMLWorkbookMacroEnabled
    Application.DisplayAlerts = True
    'Debug.Print wb.Name ' to prove that it has a new name now

    If Len(Dir(sFilePath)) > 0 Then
        SetAttr sFilePath, vbNormal
        Workbooks.Open sFilePath
        'Or:
        'Kill sFilePath
    Else
        MsgBox "File not found.", vbCritical
    End If

End Sub
```

Body:
I have a macro-enabled workbook, that has a macro that should save a copy of the file to a new location. I store the name of the original file as a string before saving to the new location, so that I can still reference the original file in the original location. The file still exists there, and the filename string works when I open the file using it, but it doesn't work when I try to do anything else with the string.

The original location is a folder called Source, and the file is copied to the folder called Destination.

The important problem here, is that the folders are located on SharePoint. If the folders are on a local machine it's not an issue.

https://[company].sharepoint.com/sites/[team]/Shared Documents/General/Source/oldVersion.xlsm

https://[company].sharepoint.com/sites/[team]/Shared Documents/General/Destination/newVersion.xlsm

Sub testMove()

    FullName = Application.ActiveWorkbook.FullName

    ActiveWorkbook.SaveAs "https://[company].sharepoint.com/sites/" _
& "[team]/Shared Documents/General/Destination/newVersion.xlsm", xlOpenXMLWorkbookMacroEnabled

    'SetAttr FullName, vbNormal
    Workbooks.Open FullName

End Sub

The above code runs just fine, but when you uncomment the setAttr it gets a file not found error.

The goal is to be able to close and/or delete the file in the original location, so SaveCopyAs doesn't quite work for this purpose.


问:
How to use the PrepareForSegue method to transfer an object which has an unknown type in the receiving controller?
I'm working on Xcode projects in Swift and I'm trying to transfer data from a "FirstViewController" to a "SecondViewController".

First of all, I receive some data by my user in the FirstViewController. I made a structure to put all these data in one single object that i try to transfer.

Here's my code :

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToSecondViewController" {
            let sentData:typeOfMyStrcuture = myObject()
            let secondVC = segue.destination as! SecondViewController
            secondVC.sentData = sentData
        }
    }
</code>```

In my SecondViewController I have :

```<code>var sentData: typeOfMyStructure!
</code>```

The problem is : since the type of the object i'm sending is unknown in my SecondViewController, i got the following error : "Cannot find type 'typeOfMyStructure' in scope".
I tried to write the same structure in my SecondViewController for it to recognize the type but I get this error : "Cannot assign value of type 'FirstViewController.typeOfMyStructure' to type 'SecondViewController.typeOfMyStructure'

Thanks by advance for your precious help !

答:
Two options:

if typeOfMyStructure is created inside the first view controller declare in the second view controller

```<code>var sentData: FirstViewController.typeOfMyStructure!
</code>```

Declare typeOfMyStructure outside of any view controller

Side note: Please name structs and classes with a starting capital letter

Body:
I'm working on Xcode projects in Swift and I'm trying to transfer data from a "FirstViewController" to a "SecondViewController".

First of all, I receive some data by my user in the FirstViewController. I made a structure to put all these data in one single object that i try to transfer.

Here's my code :

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToSecondViewController" {
            let sentData:typeOfMyStrcuture = myObject()
            let secondVC = segue.destination as! SecondViewController
            secondVC.sentData = sentData
        }
    }

In my SecondViewController I have :

var sentData: typeOfMyStructure!

The problem is : since the type of the object i'm sending is unknown in my SecondViewController, i got the following error : "Cannot find type 'typeOfMyStructure' in scope".
I tried to write the same structure in my SecondViewController for it to recognize the type but I get this error : "Cannot assign value of type 'FirstViewController.typeOfMyStructure' to type 'SecondViewController.typeOfMyStructure'

Thanks by advance for your precious help !

Body:
Two options:

if typeOfMyStructure is created inside the first view controller declare in the second view controller

var sentData: FirstViewController.typeOfMyStructure!

Declare typeOfMyStructure outside of any view controller

Side note: Please name structs and classes with a starting capital letter


问:
How to update record using Entity Framework 6?
I am trying to update a record using EF6. First finding the record, if it exists, update.
Here is my code:

```<code>var book = new Model.Book
{
    BookNumber =  _book.BookNumber,
    BookName = _book.BookName,
    BookTitle = _book.BookTitle,
};
using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        try
        {
            db.Books.Attach(book);
            db.Entry(book).State = EntityState.Modified;
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}
</code>```

Every time I try to update the record using the above code, I am getting this error:

{System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Store
update, insert, or delete statement affected an unexpected number of
rows (0). Entities may have been modified or deleted since entities
were loaded. Refresh ObjectStateManager entries

答:
The easiest way to do it is like so.</p>
```<code>var book = new Model.Book
{
    BookNumber =  _book.BookNumber,
    BookName = _book.BookName,
    BookTitle = _book.BookTitle,
};
using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        try
        {
            // you can't attach book since it doesn't exist in the database yet
            // attach result instead
            db.Books.Attach(result);
            result = book; // this will update all the fields at once
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}
</code>```

Body:
I am trying to update a record using EF6. First finding the record, if it exists, update.
Here is my code:

var book = new Model.Book
{
    BookNumber =  _book.BookNumber,
    BookName = _book.BookName,
    BookTitle = _book.BookTitle,
};
using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        try
        {
            db.Books.Attach(book);
            db.Entry(book).State = EntityState.Modified;
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

Every time I try to update the record using the above code, I am getting this error:

{System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Store
update, insert, or delete statement affected an unexpected number of
rows (0). Entities may have been modified or deleted since entities
were loaded. Refresh ObjectStateManager entries

Body:
The easiest way to do it is like so.

var book = new Model.Book
{
    BookNumber =  _book.BookNumber,
    BookName = _book.BookName,
    BookTitle = _book.BookTitle,
};
using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        try
        {
            // you can't attach book since it doesn't exist in the database yet
            // attach result instead
            db.Books.Attach(result);
            result = book; // this will update all the fields at once
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}


问:
Why immutability of super class is not forced in child class?
You can break immutabiliy of super class, even if you declare the immutable fields with val in interface or abstract class.

interface Foo {
    val bar: String // immutable
}

class FooImpl : Foo {
    override var bar: String = "bar" // mutable

    init {
        bar = "changed"
    }
}

println(FooImpl().bar) // changed
```

I expected above code will occurs compile error, but it works.
Why is this possible in kotlin?

答:
From the language spec:

A property declaration D which overrides property declaration B should satisfy the following conditions.

Mutability of D is not stronger than mutability of B (where read-only val is stronger than mutable var);

Type of D is a subtype of type of B ; except for the case when both D and B are mutable (var), then types of D and B must be equivalent.

So your overriding property can add mutability, and also use a more specific subtype (e.g. Int instead of Number) so long as the declaration isn't a var (so you can't write a Double to it via the interface).

One way you could look at it, is your original val is sort of declaring a getBar(): String function which you're overriding. By making it a var, you're also defining a setString(string) function in your own class.

If you try to access your object as Foo then that setter doesn't exist, because it's not (implicitly) defined in the interface. It's a separate function on your class, just conveniently expressed by tweaking the property definition (in a defined, restricted way)

Body:
You can break immutabiliy of super class, even if you declare the immutable fields with val in interface or abstract class.

interface Foo {
    val bar: String // immutable
}

class FooImpl : Foo {
    override var bar: String = "bar" // mutable

    init {
        bar = "changed"
    }
}

println(FooImpl().bar) // changed

I expected above code will occurs compile error, but it works.
Why is this possible in kotlin?


问:
How to copy dtype when doing numpy array assignment or when appending to a numpy array
I'm pretty illiterate in using Python/numpy.

I have the following piece of code:

```<code>data = np.array([])

for i in range(10):
    data = np.append(data, GetData())

return data
</code>```

GetData() returns a numpy array with a custom dtype. However when executing the above piece of code, the numbers convert to float64 which I suspect is the culprit for other issues I'm having. How can I copy/append the output of the functions while preserving the dtype as well?

答:
Your use of [] and append indicates that your are naively copying that common list idiom:

```<code>alist = []
for x in another_list:
   alist.append(x)
</code>```

Your data is not a clone of the [] list:

```<code>In [220]: np.array([])
Out[220]: array([], dtype=float64)
</code>```

It's an array with shape (0,) and dtype float.

np.append is not an list append clone.  I stress that, because too many new users make that mistake, and the result is many different errors.  It is really just a cover for np.concatenate, one that takes 2 arguments instead of a list of arguments.  As the docs stress it returns a new array, and when used iteratively, that means a lot of copying.

It is best to collect your arrays in a list, and give it to concatenate.  List append is in-place, and better when done iteratively.  If you give concatenate a list of arrays, the resulting dtype will be the common one (or whatever promoting requires).  (new versions do let you specify dtype when calling concatenate.)

Keep the numpy documentation at hand (python too if necessary), and look up functions.  Pay attention to how they are called, including the keyword parameters).  And practice with small examples.  I keep an interactive python session at hand, even when writing answers.

When working with arrays, pay close attention to shape and dtype.  Don't make assumptions.

concatenating 2 int arrays:

```<code>In [238]: np.concatenate((np.array([1,2]),np.array([4,3])))
Out[238]: array([1, 2, 4, 3])
</code>```

making one  a float array (just by adding a decimal point to one number):

```<code>In [239]: np.concatenate((np.array([1,2]),np.array([4,3.])))
Out[239]: array([1., 2., 4., 3.])
</code>```

It won't let me change the result to int:

```<code>In [240]: np.concatenate((np.array([1,2]),np.array([4,3.])), dtype=int)
Traceback (most recent call last):
  File "<ipython-input-240-91b4e3fec07a>", line 1, in <module>
    np.concatenate((np.array([1,2]),np.array([4,3.])), dtype=int)
  File "<__array_function__ internals>", line 180, in concatenate
TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'same_kind'
</code>```

If an element is a string, the result is also a string dtype:

```<code>In [241]: np.concatenate((np.array([1,2]),np.array(['4',3.])))
Out[241]: array(['1', '2', '4', '3.0'], dtype='<U32')
</code>```

Sometimes it is necessary to adjust dtypes after a calculation:

```<code>In [243]: np.concatenate((np.array([1,2]),np.array(['4',3.]))).astype(float)
Out[243]: array([1., 2., 4., 3.])
In [244]: np.concatenate((np.array([1,2]),np.array(['4',3.]))).astype(float).as
     ...: type(int)
Out[244]: array([1, 2, 4, 3])
</code>```

Body:
I'm pretty illiterate in using Python/numpy.

I have the following piece of code:

data = np.array([])

for i in range(10):
    data = np.append(data, GetData())

return data

GetData() returns a numpy array with a custom dtype. However when executing the above piece of code, the numbers convert to float64 which I suspect is the culprit for other issues I'm having. How can I copy/append the output of the functions while preserving the dtype as well?

Body:
Your use of [] and append indicates that your are naively copying that common list idiom:

alist = []
for x in another_list:
   alist.append(x)

Your data is not a clone of the [] list:

In [220]: np.array([])
Out[220]: array([], dtype=float64)

It's an array with shape (0,) and dtype float.

np.append is not an list append clone.  I stress that, because too many new users make that mistake, and the result is many different errors.  It is really just a cover for np.concatenate, one that takes 2 arguments instead of a list of arguments.  As the docs stress it returns a new array, and when used iteratively, that means a lot of copying.

It is best to collect your arrays in a list, and give it to concatenate.  List append is in-place, and better when done iteratively.  If you give concatenate a list of arrays, the resulting dtype will be the common one (or whatever promoting requires).  (new versions do let you specify dtype when calling concatenate.)

Keep the numpy documentation at hand (python too if necessary), and look up functions.  Pay attention to how they are called, including the keyword parameters).  And practice with small examples.  I keep an interactive python session at hand, even when writing answers.

When working with arrays, pay close attention to shape and dtype.  Don't make assumptions.

concatenating 2 int arrays:

In [238]: np.concatenate((np.array([1,2]),np.array([4,3])))
Out[238]: array([1, 2, 4, 3])

making one  a float array (just by adding a decimal point to one number):

In [239]: np.concatenate((np.array([1,2]),np.array([4,3.])))
Out[239]: array([1., 2., 4., 3.])

It won't let me change the result to int:

In [240]: np.concatenate((np.array([1,2]),np.array([4,3.])), dtype=int)
Traceback (most recent call last):
  File "<ipython-input-240-91b4e3fec07a>", line 1, in <module>
    np.concatenate((np.array([1,2]),np.array([4,3.])), dtype=int)
  File "<__array_function__ internals>", line 180, in concatenate
TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'same_kind'

If an element is a string, the result is also a string dtype:

In [241]: np.concatenate((np.array([1,2]),np.array(['4',3.])))
Out[241]: array(['1', '2', '4', '3.0'], dtype='<U32')

Sometimes it is necessary to adjust dtypes after a calculation:

In [243]: np.concatenate((np.array([1,2]),np.array(['4',3.]))).astype(float)
Out[243]: array([1., 2., 4., 3.])
In [244]: np.concatenate((np.array([1,2]),np.array(['4',3.]))).astype(float).as
     ...: type(int)
Out[244]: array([1, 2, 4, 3])


问:
PHP downloading instead of opening in browser - MacOS Sierra
I'm having issues related to loading php using Apache. I use a iMac running Sierra 10.12.6. Server version: Apache/2.4.25 (Unix). PHP 5.6.30 (cli) (built: Feb 7 2017 (16:18:37). Loaded module: php7_module (shared). I have been making all changes using Terminal. So far I can access my localhost, getting the "It Works!" page. I can access my user directory, for html documents only.

When I load the php5 module localhost will not connect at all. Server localhost not found. When I comment the php5 load module out again and restart apache I can gain access html documents in both localhost and localhost/~. When php5 is not loaded it downloads the document instead of opening it. It will go to the downloads folder or open in a text editor like Dreamweaver automatically. I downloaded MAMP and can access the phpinfo page and localhost on port 8888 so I think that is Ok, although I'm having issues connecting MySQL. That's a separate issue. Right now I just want to access php in my localhost/~.

My user directory info is (using actual username)

```<code><Directory "Users/username/Sites/">
    Options Indexes MultiViews
    AllowOverride All
    Require all granted
</Directory>
</code>```

I followed tutorials making the recommended changes to the httpd.conf and other files and creating the index.html and php info documents in ~/Sites.

```<code>LoadModule userdir_mod
AddHandler php5-script php
display_errors = On
Include /private/etc/apache2/extra/httpd-userdir.conf
Include /private/etc/apache2/other/*.conf
</code>```

I also changed the ServerName to localhost:80.
I also changed permissions on my WebServer/Documents folder to read & write for system, wheel and everyone.
I also made the following changes after reading through message boards on this site making changes to the Directory index.

I made other changes to the bash file (following the tutorial) and eventually reloaded the original httpd but I still can't access php. How do i access php5 in my user directory? Thanks.

答: I had the same issue and it turned out to be a permissions error.  Try creating a new folder and copy across all the files.</p>

Body:
I'm having issues related to loading php using Apache. I use a iMac running Sierra 10.12.6. Server version: Apache/2.4.25 (Unix). PHP 5.6.30 (cli) (built: Feb 7 2017 (16:18:37). Loaded module: php7_module (shared). I have been making all changes using Terminal. So far I can access my localhost, getting the "It Works!" page. I can access my user directory, for html documents only.

When I load the php5 module localhost will not connect at all. Server localhost not found. When I comment the php5 load module out again and restart apache I can gain access html documents in both localhost and localhost/~. When php5 is not loaded it downloads the document instead of opening it. It will go to the downloads folder or open in a text editor like Dreamweaver automatically. I downloaded MAMP and can access the phpinfo page and localhost on port 8888 so I think that is Ok, although I'm having issues connecting MySQL. That's a separate issue. Right now I just want to access php in my localhost/~.

My user directory info is (using actual username)

<Directory "Users/username/Sites/">
    Options Indexes MultiViews
    AllowOverride All
    Require all granted
</Directory>

I followed tutorials making the recommended changes to the httpd.conf and other files and creating the index.html and php info documents in ~/Sites.

LoadModule userdir_mod
AddHandler php5-script php
display_errors = On
Include /private/etc/apache2/extra/httpd-userdir.conf
Include /private/etc/apache2/other/*.conf

I also changed the ServerName to localhost:80.
I also changed permissions on my WebServer/Documents folder to read & write for system, wheel and everyone.
I also made the following changes after reading through message boards on this site making changes to the Directory index.

I made other changes to the bash file (following the tutorial) and eventually reloaded the original httpd but I still can't access php. How do i access php5 in my user directory? Thanks.


问:
Will adding an id to a html style tag cause issues?
I have a javascript application where for some obscure reasons I need to:

Inject styles into my html head

Remove these styles from my html head at a later stage

My simplified setup I have right now is something like this...

Injecting the

答:
You don't have to get it by id again. You have it in styleEl variable, so just remove it from a DOM like this:

```<code>styleEl.remove(); // remove it from the DOM
</code>```

You can do this repeatedly. Append and remove.

Body:
You don't have to get it by id again. You have it in styleEl variable, so just remove it from a DOM like this:

styleEl.remove(); // remove it from the DOM

You can do this repeatedly. Append and remove.


问:
Function to determine if it is possible to make the one string to be equal with the other
function to determine if it is possible to make the first input equal to the second input by either capitalizing or removing letters. Cannot interchange the positions of the letters.</p>

答:
Idea is to take one letter at a time from right string, and try to “cross out” some letters from left string by certain rules. For each letter from right string, it must be able to cross out at least one letter from left string, otherwise the check fails.

function check(left, right) {
  const chars = right.split('');
  for (const c of chars) {
    let i = left.indexOf(c);
    if (i == -1) i = left.indexOf(c.toLowerCase());
    if (i == -1) return false;
    left = left.slice(i + 1);
  }
  return true;
}
```


问:
Does "return await" makes any difference?
Is there any difference between

```<code>const foo = async () => {
  // some other code that uses await
  return await bar()
}
</code>```

and

```<code>const foo = async () => {
  // some other code that uses await
  return bar()
}
</code>```

Where bar is a function that returns a promise.

Is the await redundant or does it make any difference?

答:
It is redundant.

It extracts the value from the promise returned by bar, and then resolves the promise returned by foo with it.

If you return bar's promise directly, then the promise returned by foo adopts it to the same effect.

Body:
Is there any difference between

const foo = async () => {
  // some other code that uses await
  return await bar()
}

and

const foo = async () => {
  // some other code that uses await
  return bar()
}

Where bar is a function that returns a promise.

Is the await redundant or does it make any difference?


问:
On public XMPP servers, how do you find which port supports websockets?
Opening a websocket without a port specified seems to fail on all xmpp servers. I assume this means there is no default websocket port.

I have been able to only open one xmpp server's websocket. It does not appear other xmpp servers use the same 5291 websocket port as tigase.im

How do you determine the websocket port for a public XMPP server? The lists of open xmpp servers seem to only give a url.

I at first tried DNS SRV lookup using DNSchecker.org which showed no SRV record.

As I learned more about DNS SRV lookup formats by reading RFC 6120, I found I can get the tcp port using mxtoolbox.com with the string: _xmpp-client._tcp.tigase.im

On a hunch, I tried _xmpp-client._websocket.tigase.im, but no port was returned. On further reading, the IETF specified to try the string _ws._tcp.tigase.im which also returned nothing using mxtoolbox.com  Is there a different string I should be using with mxtoolbox.com?

Is there another way to get the websocket port number of a public XMPP server?

答:
XEP-0156 also had another method I didn't originally understand, called HTTP lookup and it is a lot more practical for calling from javascript, then parsing the response.

If the xmpp server supports it, you append /.well-known/host-meta to the server's URL like this tigase.im/.well-known/host-meta

It can be even easier to parse with /.well-known/host-meta.json


问:
Installing Docker on Slackware 15
I previously followed the instructions here: https://docs.slackware.com/howtos:cloud:docker to install docker on my Slackware 14.2 box. I've got a new setup with Slackware 15 and it doesn't work - because there's no Slackbuilds support for 15 apparently. Is there a way to use the 14.2 builds? or an alternative way to get this working?</p>

答: Found out a simpler way - Just installed the statically linked versions and everything worked. https://download.docker.com/linux/static/stable/x86_64/</p>

Title: Installing Docker on Slackware 15


问:
How to trigger dependabot scan on developer pull requests
I'm not sure if my use case is one dependabot is suited for, so hoping someone can tell me if it is or is not, and if it is, point me to some documentation on how to do what I'm describing:

I want to create workflow that:

runs dependabot scan on each developer pull request

dependabot only reports on newly introduced or updated
dependencies

pull request is blocked by any new dependencies with
vulnerabilities of medium or higher

dependabot does not create PR as a result of a PR scan

Is this possible?

答:
Seems the answer is no, dependabot cannot do this.

A colleague found this information:

"Dependabot alerts will find vulnerabilities that are already in your dependencies, but it's much better to avoid introducing potential problems than to fix problems at a later date."

At this location:

https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review

And github has, on their roadmap, the ability to block pull requests that introduce vulnerable dependencies:

https://github.com/github/roadmap/issues/149


问:
send email from node.js app using nodemailer
From my ubuntu (10.04) box, I have no problem send email with:

```<code>echo "hello" | mail -s 'test email' my_gmail_nickname@gmail.com
</code>```

When I try to send an email from a node.js app running on the same machine, it does not work.

```<code>var nodemailer = require('nodemailer');
nodemailer.SMTP = {
  host: 'localhost'
}
nodemailer.send_mail(
{
    sender: 'me@example.com',
    to:'my_gmail_nickname@gmail.com',
    subject:'Hello!',
    html: 'test',
    body:'test'
},
function(error, success){
    console.log(error);
    console.log(success);
    console.log('Message ' + success ? 'sent' : 'failed');
});
</code>```

I have the error message:

```<code>me@luc:~/gridteams/services/gpshop$ cat nohup.out
{ stack: [Getter/Setter],
  arguments: undefined,
  type: undefined,
  message: 'ECONNREFUSED, Connection refused',
  errno: 111,
  code: 'ECONNREFUSED',
  syscall: 'connect' }
null
sent
</code>```

I see the connection refused but do not understand why I get this error. What do you think is the missing piece ?

答:
I think your problem is like this:

The commandline program mail uses a binary called /usr/sbin/sendmail for sending mail. sendmail is a commandline programm which will try to deliver the mail. It uses a local connection to the mail infrastructure.

The node nodemailer will try to connect to a SMTP server on the host localhost on TCP port 25 which doesn't exist. Just try to get a connection using the telnet program for verification.

Here is a server running:

```<code>$ telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 xxxx.de ESMTP Postfix
QUIT
221 2.0.0 Bye
Connection closed by foreign host.
</code>```

here is no server running:

```<code>$ telnet localhost 25
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused
</code>```

If you get the second, you have a problem with your SMTP which is not started/enabled listening on port 25 - which is the default (for security reasons). You need to configure it first.

Or - according to the nodemail documentation you can use the sendmail binary as well:

```<code>'sendmail' alternative

Alternatively if you don't want to use SMTP but the sendmail
</code>```

command then set property sendmail to true (or as the path to sendmail
  if the command is not in default path).

```<code>nodemailer.sendmail = true;

or

nodemailer.sendmail = '/path/to/sendmail';

If sendmail is set, then SMTP options are discarded.
</code>```

Body:
From my ubuntu (10.04) box, I have no problem send email with:

echo "hello" | mail -s 'test email' my_gmail_nickname@gmail.com

When I try to send an email from a node.js app running on the same machine, it does not work.

var nodemailer = require('nodemailer');
nodemailer.SMTP = {
  host: 'localhost'
}
nodemailer.send_mail(
{
    sender: 'me@example.com',
    to:'my_gmail_nickname@gmail.com',
    subject:'Hello!',
    html: 'test',
    body:'test'
},
function(error, success){
    console.log(error);
    console.log(success);
    console.log('Message ' + success ? 'sent' : 'failed');
});

I have the error message:

me@luc:~/gridteams/services/gpshop$ cat nohup.out
{ stack: [Getter/Setter],
  arguments: undefined,
  type: undefined,
  message: 'ECONNREFUSED, Connection refused',
  errno: 111,
  code: 'ECONNREFUSED',
  syscall: 'connect' }
null
sent

I see the connection refused but do not understand why I get this error. What do you think is the missing piece ?

Body:
I think your problem is like this:

The commandline program mail uses a binary called /usr/sbin/sendmail for sending mail. sendmail is a commandline programm which will try to deliver the mail. It uses a local connection to the mail infrastructure.

The node nodemailer will try to connect to a SMTP server on the host localhost on TCP port 25 which doesn't exist. Just try to get a connection using the telnet program for verification.

Here is a server running:

$ telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 xxxx.de ESMTP Postfix
QUIT
221 2.0.0 Bye
Connection closed by foreign host.

here is no server running:

$ telnet localhost 25
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused

If you get the second, you have a problem with your SMTP which is not started/enabled listening on port 25 - which is the default (for security reasons). You need to configure it first.

Or - according to the nodemail documentation you can use the sendmail binary as well:

'sendmail' alternative

Alternatively if you don't want to use SMTP but the sendmail

command then set property sendmail to true (or as the path to sendmail
  if the command is not in default path).

nodemailer.sendmail = true;

or

nodemailer.sendmail = '/path/to/sendmail';

If sendmail is set, then SMTP options are discarded.


问:
AttributeError: 'Worksheet' object has no attribute 'set_default_row'
I am getting an error that seems weird. Worksheet object does have set_default_row() function, in the docs. Not sure what I am missing here.

I got this code project from someone who made this and has been running for a long time. We are using different python versions. He's on 3.10 and I am on 3.9 and I don't see that to be any reason.

Error:

```<code>Traceback (most recent call last):
  File "C:\Users\ajoshi\my_folder\misc\quick tools\CI-TestRun-Report-Generator\FileProvider.py", line 31, in create
    worksheet.set_default_row(20)
AttributeError: 'Worksheet' object has no attribute 'set_default_row'
</code>```

Code:

```<code>s = data.style.applymap(FileProvider.color_negative_red)
s.to_excel(writer, sheet_name=plan["name"], header=True, index=False)

workbook = writer.book
worksheet = writer.sheets[plan["name"]]
worksheet.set_default_row(20)
worksheet.set_row(0, 40)
</code>```

答:
The issue is that you are calling a xlsxwriter method but that, most probably, the module isn't installed so Pandas is defaulting to creating a openpyxl worksheet object which has different APIs and doesn't have that method. Try set up your Pandas xlsx writer like this:

writer = pd.ExcelWriter('filename.xlsx', engine='xlsxwriter')
```

If that fails then you need to install xlsxwriter.

If you are already using engine='xlsxwriter' then the issue could be that you have a very old version installed that doesn't support the set_default_row() method. In which case you should upgrade xlsxwriter.

Body:
I am getting an error that seems weird. Worksheet object does have set_default_row() function, in the docs. Not sure what I am missing here.

I got this code project from someone who made this and has been running for a long time. We are using different python versions. He's on 3.10 and I am on 3.9 and I don't see that to be any reason.

Error:

Traceback (most recent call last):
  File "C:\Users\ajoshi\my_folder\misc\quick tools\CI-TestRun-Report-Generator\FileProvider.py", line 31, in create
    worksheet.set_default_row(20)
AttributeError: 'Worksheet' object has no attribute 'set_default_row'

Code:

s = data.style.applymap(FileProvider.color_negative_red)
s.to_excel(writer, sheet_name=plan["name"], header=True, index=False)

workbook = writer.book
worksheet = writer.sheets[plan["name"]]
worksheet.set_default_row(20)
worksheet.set_row(0, 40)

Body:
The issue is that you are calling a xlsxwriter method but that, most probably, the module isn't installed so Pandas is defaulting to creating a openpyxl worksheet object which has different APIs and doesn't have that method. Try set up your Pandas xlsx writer like this:

writer = pd.ExcelWriter('filename.xlsx', engine='xlsxwriter')

If that fails then you need to install xlsxwriter.

If you are already using engine='xlsxwriter' then the issue could be that you have a very old version installed that doesn't support the set_default_row() method. In which case you should upgrade xlsxwriter.


问:
SQL query for Weekly Sales Report

Retrieve three columns labeled day, qty_sold and total_profit in that order.
day should be displayed in the 3-character format Sun, Mon, Tue, Wed, Thu, Fri, Sat and sorted ascending in that order.

Only retrieve sales from the past week.

If there are no sales on a particular day of the week (as might be the case on a holiday), the row should still be included in the report with qty_sold and total_profit columns as 0.

Net profit per item is calculated as qty_sold * (price - cost). Total profit for a day is the sum of the net profit of every item sold on that day.
Do not format any numbers as currency.

Here's what i got so far any help would be greatly appreciated

```<code>SELECT DATE_FORMAT(s.order_time,"%a") AS day
FROM sales_order s
INNER JOIN order_item o on o.sales_order_id=s.id
INNER JOIN menu_item m on m.id =o.menu_item_id
GROUP BY day;
</code>```

This is supposed to be the output

答:
You can try something like this

SELECT day,COUNT(menu_item_id) AS qty_sold,SUM(price - cost) AS total_profit
FROM
(SELECT 1 AS id,"Sun" AS day
UNION ALL
SELECT 2,"Mon"
UNION ALL
SELECT 3,"Tue"
UNION ALL
SELECT 4,"Wed"
UNION ALL
SELECT 5,"Thu"
UNION ALL
SELECT 6,"Fri"
UNION ALL
SELECT 7,"Sat") AS dow
LEFT OUTER JOIN sales_order AS s ON dow.id = DAYOFWEEK(s.order_time)
INNER JOIN order_item AS o ON o.sales_order_id=s.id
INNER JOIN menu_item AS m ON m.id=o.menu_item_id
WHERE s.order_time >= DATE_SUB(NOW(),INTERVAL 7 + WEEKDAY(current_date) DAY) AND s.order_time < CONCAT(current_date," 00:00:00")
GROUP BY day
ORDER BY dow.id
```

Title: SQL query for Weekly Sales Report

Body:
Retrieve three columns labeled day, qty_sold and total_profit in that order.
day should be displayed in the 3-character format Sun, Mon, Tue, Wed, Thu, Fri, Sat and sorted ascending in that order.

Only retrieve sales from the past week.

If there are no sales on a particular day of the week (as might be the case on a holiday), the row should still be included in the report with qty_sold and total_profit columns as 0.

Net profit per item is calculated as qty_sold * (price - cost). Total profit for a day is the sum of the net profit of every item sold on that day.
Do not format any numbers as currency.

Here's what i got so far any help would be greatly appreciated

SELECT DATE_FORMAT(s.order_time,"%a") AS day
FROM sales_order s
INNER JOIN order_item o on o.sales_order_id=s.id
INNER JOIN menu_item m on m.id =o.menu_item_id
GROUP BY day;

This is supposed to be the output


问:
SQL : How to get multiple XML parent node values inside new node dynamically?
How do i get the desired output dynamically ?

In the source XML i have multiple child nodes for SHIPMENTS. I need to take partial information from them and map them to a new output inside SQL ( i use SSMS ).
I only need to output the shipmentno, tripsequence, unloaddate and unloadtime - but for multiple shipments.

Source XML :

```<code><SHIPMENTS>
    <Laden>JAMAICA</Laden>
    <CLIENT>FAKE CLIENT</CLIENT>
    <Activiteit>SD</Activiteit>
    <TRIPSEQUENCE>10</TRIPSEQUENCE>
    <Tpttype>FRE</Tpttype>
    <SHIPMENTNO>42069</SHIPMENTNO>
</SHIPMENTS>
<SHIPMENTS>
    <Lossen>NEW ZEALANG</Lossen>
    <CLIENT>FAKE CLIENT</CLIENT>
    <Activiteit>DS</Activiteit>
    <TRIPSEQUENCE>70</TRIPSEQUENCE>
    <Tpttype>DEZ</Tpttype>
    <SHIPMENTNO>42169</SHIPMENTNO>
    <UNLOADDATE>15/12</UNLOADDATE>
    <UNLOADTIME>09:00:00</UNLOADTIME>
</SHIPMENTS>
<SHIPMENTS>
    <Lossen>LONDON</Lossen>
    <CLIENT>FAKE CLIENT</CLIENT>
    <Activiteit>LO</Activiteit>
    <TRIPSEQUENCE>80</TRIPSEQUENCE>
    <Tpttype>DSZ</Tpttype>
    <SHIPMENTNO>42269</SHIPMENTNO>
    <UNLOADDATE>15/12</UNLOADDATE>
    <UNLOADTIME>09:00:00</UNLOADTIME>
</SHIPMENTS>
<SHIPMENTS>
    <Lossen>LOUISIANA</Lossen>
    <CLIENT>FAKE CLIENT</CLIENT>
    <Activiteit>DS</Activiteit>
    <TRIPSEQUENCE>90</TRIPSEQUENCE>
    <Tpttype>GRO</Tpttype>
    <SHIPMENTNO>42369</SHIPMENTNO>
    <UNLOADDATE>15/12</UNLOADDATE>
    <UNLOADTIME>09:00:00</UNLOADTIME>
</SHIPMENTS>
<SHIPMENTS>
    <Lossen>KOS</Lossen>
    <CLIENT>FAKE CLIENT</CLIENT>
    <Activiteit>LO</Activiteit>
    <TRIPSEQUENCE>100</TRIPSEQUENCE>
    <Tpttype>GFS</Tpttype>
    <SHIPMENTNO>42369</SHIPMENTNO>
    <UNLOADDATE>15/12</UNLOADDATE>
    <UNLOADTIME>08:00:00</UNLOADTIME>
</SHIPMENTS>
<SHIPMENTS>
    <Lossen>ROTTERDAM</Lossen>
    <CLIENT>FAKE CLIENT</CLIENT>
    <Activiteit>LOL</Activiteit>
    <TRIPSEQUENCE>110</TRIPSEQUENCE>
    <Tpttype>GRO</Tpttype>
    <SHIPMENTNO>42469</SHIPMENTNO>
    <UNLOADDATE>15/12</UNLOADDATE>
    <UNLOADTIME>09:00:00</UNLOADTIME>
</SHIPMENTS>
<SHIPMENTS>
    <Lossen>TENERIFE</Lossen>
    <CLIENT>FAKE CLIENT</CLIENT>
    <Activiteit>LO</Activiteit>
    <TRIPSEQUENCE>120</TRIPSEQUENCE>
    <Tpttype>GRO</Tpttype>
    <SHIPMENTNO>42570</SHIPMENTNO>
    <UNLOADDATE>15/12</UNLOADDATE>
    <UNLOADTIME>09:00:00</UNLOADTIME>
</SHIPMENTS>
</code>```

MISSION : In my Output XML, i need <SHIPMENTS/> To be the parent node, with multiple <SHIPMENT/> children containing the values from the source XML. This is how the output should look

DESIRED OUTPUT :

```<code><SHIPMENTS>
    <SHIPMENT>
        <SHIPMENTNO>UI0010912</SHIPMENTNO>
        <TRIPSEQUENCE>1</TRIPSEQUENCE>
        <UNLOADDATE>20211012</UNLOADDATE>
        <UNLOADTIME>10:00</UNLOADTIME>
    </SHIPMENT>
    <SHIPMENT>
        <SHIPMENTNO>UI0010911</SHIPMENTNO>
        <TRIPSEQUENCE>2</TRIPSEQUENCE>
        <UNLOADDATE>20211012</UNLOADDATE>
        <UNLOADTIME>11:00</UNLOADTIME>
    </SHIPMENT>
    <SHIPMENT>
        <SHIPMENTNO>UI0010913</SHIPMENTNO>
        <TRIPSEQUENCE>3</TRIPSEQUENCE>
        <UNLOADDATE>20211012</UNLOADDATE>
        <UNLOADTIME>15:00</UNLOADTIME>
    </SHIPMENT>
</SHIPMENTS>
</code>```

THE QUERY :
This is the structure and the values that i need per child node  :

```<code>SET @xml = (
    (SELECT
N'' AS [TRIP/SHIPMENTS],
        N'' AS [TRIP/SHIPMENTS/SHIPMENT],
        N'UI45048839' AS [TRIP/SHIPMENTS/SHIPMENT/SHIPMENTNO],
        N'1' AS [TRIP/SHIPMENTS/SHIPMENT/TRIPSEQUENCE],
        @XML.query(N'(/SHIPMENTS/UNLOADDATE)[5]').value('.', N'nvarchar(MAX)') AS [TRIP/SHIPMENTS/SHIPMENT/UNLOADDATE],
        @XML.query(N'(/SHIPMENTS/UNLOADTIME)[5]').value('.', N'nvarchar(MAX)') AS [TRIP/SHIPMENTS/SHIPMENT/UNLOADTIME],
        N'' AS [TRIP/SHIPMENTS/SHIPMENT],
        N'UI45048841' AS [TRIP/SHIPMENTS/SHIPMENT/SHIPMENTNO],
        N'2' AS [TRIP/SHIPMENTS/SHIPMENT/TRIPSEQUENCE],
        @XML.query(N'(/SHIPMENTS/UNLOADDATE)[3]').value('.', N'nvarchar(MAX)') AS [TRIP/SHIPMENTS/SHIPMENT/UNLOADDATE],
        @XML.query(N'(/SHIPMENTS/UNLOADTIME)[3]').value('.', N'nvarchar(MAX)') AS [TRIP/SHIPMENTS/SHIPMENT/UNLOADTIME],
        N'UI45048840' AS [TRIP/SHIPMENTS/SHIPMENT/SHIPMENTNO],
        N'3' AS [TRIP/SHIPMENTS/SHIPMENT/TRIPSEQUENCE],
        @XML.query(N'(/SHIPMENTS/UNLOADDATE)[2]').value('.', N'nvarchar(MAX)') AS [TRIP/SHIPMENTS/SHIPMENT/UNLOADDATE],
        @XML.query(N'(/SHIPMENTS/UNLOADTIME)[2]').value('.', N'nvarchar(MAX)') AS [TRIP/SHIPMENTS/SHIPMENT/UNLOADTIME]
        FOR XML PATH (N'SHIPMENTS'), TYPE
    ) AS [SHIPMENTS/SHIPMENT]
FOR XML PATH(N''), ROOT(N'TRIPS'), TYPE
);
SELECT @xml AS [FileContent];
</code>```

and obviously RETURNS :

```<code><SHIPMENTS>
    <SHIPMENT>
      <SHIPMENTNO>UI45048839</SHIPMENTNO>
      <TRIPSEQUENCE>1</TRIPSEQUENCE>
      <UNLOADDATE>15/12</UNLOADDATE>
      <UNLOADTIME>09:00:00</UNLOADTIME>
      <SHIPMENTNO>UI45048841</SHIPMENTNO>
      <TRIPSEQUENCE>2</TRIPSEQUENCE>
      <UNLOADDATE>15/12</UNLOADDATE>
      <UNLOADTIME>09:00:00</UNLOADTIME>
      <SHIPMENTNO>UI45048840</SHIPMENTNO>
      <TRIPSEQUENCE>3</TRIPSEQUENCE>
      <UNLOADDATE>15/12</UNLOADDATE>
      <UNLOADTIME>09:00:00</UNLOADTIME>
    </SHIPMENT>
</SHIPMENTS>
</code>```

I don't like my approach as it is mainly hardcoding and repeating the result.

How do i get the desired output dynamically ?

Thank you for your time !

答:
It seems you are massively over-complicating this. You can use .query() to generate constructed XML containing the correct nodes

SELECT @xml.query('
    <SHIPMENTS>
    {
        for $s in /SHIPMENTS
        return
          <SHIPMENT>
              {
                $s/*[
                  local-name() = ("SHIPMENTNO", "TRIPSEQUENCE", "UNLOADDATE", "UNLOADTIME")
                  ]
              }
          </SHIPMENT>
    }
    </SHIPMENTS>
');
```

db<>fiddle

This creates a new root SHIPMENTS node.

Within that, it takes all original SHIPMENTS nodes and creates SHIPMENT nodes from them.

Each of those only contains the four relevant child nodes. It takes all nodes by using a wildcard, then checks them using local-name().

Body:
How do i get the desired output dynamically ?

In the source XML i have multiple child nodes for SHIPMENTS. I need to take partial information from them and map them to a new output inside SQL ( i use SSMS ).
I only need to output the shipmentno, tripsequence, unloaddate and unloadtime - but for multiple shipments.

Source XML :

<SHIPMENTS>
    <Laden>JAMAICA</Laden>
    <CLIENT>FAKE CLIENT</CLIENT>
    <Activiteit>SD</Activiteit>
    <TRIPSEQUENCE>10</TRIPSEQUENCE>
    <Tpttype>FRE</Tpttype>
    <SHIPMENTNO>42069</SHIPMENTNO>
</SHIPMENTS>
<SHIPMENTS>
    <Lossen>NEW ZEALANG</Lossen>
    <CLIENT>FAKE CLIENT</CLIENT>
    <Activiteit>DS</Activiteit>
    <TRIPSEQUENCE>70</TRIPSEQUENCE>
    <Tpttype>DEZ</Tpttype>
    <SHIPMENTNO>42169</SHIPMENTNO>
    <UNLOADDATE>15/12</UNLOADDATE>
    <UNLOADTIME>09:00:00</UNLOADTIME>
</SHIPMENTS>
<SHIPMENTS>
    <Lossen>LONDON</Lossen>
    <CLIENT>FAKE CLIENT</CLIENT>
    <Activiteit>LO</Activiteit>
    <TRIPSEQUENCE>80</TRIPSEQUENCE>
    <Tpttype>DSZ</Tpttype>
    <SHIPMENTNO>42269</SHIPMENTNO>
    <UNLOADDATE>15/12</UNLOADDATE>
    <UNLOADTIME>09:00:00</UNLOADTIME>
</SHIPMENTS>
<SHIPMENTS>
    <Lossen>LOUISIANA</Lossen>
    <CLIENT>FAKE CLIENT</CLIENT>
    <Activiteit>DS</Activiteit>
    <TRIPSEQUENCE>90</TRIPSEQUENCE>
    <Tpttype>GRO</Tpttype>
    <SHIPMENTNO>42369</SHIPMENTNO>
    <UNLOADDATE>15/12</UNLOADDATE>
    <UNLOADTIME>09:00:00</UNLOADTIME>
</SHIPMENTS>
<SHIPMENTS>
    <Lossen>KOS</Lossen>
    <CLIENT>FAKE CLIENT</CLIENT>
    <Activiteit>LO</Activiteit>
    <TRIPSEQUENCE>100</TRIPSEQUENCE>
    <Tpttype>GFS</Tpttype>
    <SHIPMENTNO>42369</SHIPMENTNO>
    <UNLOADDATE>15/12</UNLOADDATE>
    <UNLOADTIME>08:00:00</UNLOADTIME>
</SHIPMENTS>
<SHIPMENTS>
    <Lossen>ROTTERDAM</Lossen>
    <CLIENT>FAKE CLIENT</CLIENT>
    <Activiteit>LOL</Activiteit>
    <TRIPSEQUENCE>110</TRIPSEQUENCE>
    <Tpttype>GRO</Tpttype>
    <SHIPMENTNO>42469</SHIPMENTNO>
    <UNLOADDATE>15/12</UNLOADDATE>
    <UNLOADTIME>09:00:00</UNLOADTIME>
</SHIPMENTS>
<SHIPMENTS>
    <Lossen>TENERIFE</Lossen>
    <CLIENT>FAKE CLIENT</CLIENT>
    <Activiteit>LO</Activiteit>
    <TRIPSEQUENCE>120</TRIPSEQUENCE>
    <Tpttype>GRO</Tpttype>
    <SHIPMENTNO>42570</SHIPMENTNO>
    <UNLOADDATE>15/12</UNLOADDATE>
    <UNLOADTIME>09:00:00</UNLOADTIME>
</SHIPMENTS>

MISSION : In my Output XML, i need <SHIPMENTS/> To be the parent node, with multiple <SHIPMENT/> children containing the values from the source XML. This is how the output should look

DESIRED OUTPUT :

<SHIPMENTS>
    <SHIPMENT>
        <SHIPMENTNO>UI0010912</SHIPMENTNO>
        <TRIPSEQUENCE>1</TRIPSEQUENCE>
        <UNLOADDATE>20211012</UNLOADDATE>
        <UNLOADTIME>10:00</UNLOADTIME>
    </SHIPMENT>
    <SHIPMENT>
        <SHIPMENTNO>UI0010911</SHIPMENTNO>
        <TRIPSEQUENCE>2</TRIPSEQUENCE>
        <UNLOADDATE>20211012</UNLOADDATE>
        <UNLOADTIME>11:00</UNLOADTIME>
    </SHIPMENT>
    <SHIPMENT>
        <SHIPMENTNO>UI0010913</SHIPMENTNO>
        <TRIPSEQUENCE>3</TRIPSEQUENCE>
        <UNLOADDATE>20211012</UNLOADDATE>
        <UNLOADTIME>15:00</UNLOADTIME>
    </SHIPMENT>
</SHIPMENTS>

THE QUERY :
This is the structure and the values that i need per child node  :

SET @xml = (
    (SELECT
N'' AS [TRIP/SHIPMENTS],
        N'' AS [TRIP/SHIPMENTS/SHIPMENT],
        N'UI45048839' AS [TRIP/SHIPMENTS/SHIPMENT/SHIPMENTNO],
        N'1' AS [TRIP/SHIPMENTS/SHIPMENT/TRIPSEQUENCE],
        @XML.query(N'(/SHIPMENTS/UNLOADDATE)[5]').value('.', N'nvarchar(MAX)') AS [TRIP/SHIPMENTS/SHIPMENT/UNLOADDATE],
        @XML.query(N'(/SHIPMENTS/UNLOADTIME)[5]').value('.', N'nvarchar(MAX)') AS [TRIP/SHIPMENTS/SHIPMENT/UNLOADTIME],
        N'' AS [TRIP/SHIPMENTS/SHIPMENT],
        N'UI45048841' AS [TRIP/SHIPMENTS/SHIPMENT/SHIPMENTNO],
        N'2' AS [TRIP/SHIPMENTS/SHIPMENT/TRIPSEQUENCE],
        @XML.query(N'(/SHIPMENTS/UNLOADDATE)[3]').value('.', N'nvarchar(MAX)') AS [TRIP/SHIPMENTS/SHIPMENT/UNLOADDATE],
        @XML.query(N'(/SHIPMENTS/UNLOADTIME)[3]').value('.', N'nvarchar(MAX)') AS [TRIP/SHIPMENTS/SHIPMENT/UNLOADTIME],
        N'UI45048840' AS [TRIP/SHIPMENTS/SHIPMENT/SHIPMENTNO],
        N'3' AS [TRIP/SHIPMENTS/SHIPMENT/TRIPSEQUENCE],
        @XML.query(N'(/SHIPMENTS/UNLOADDATE)[2]').value('.', N'nvarchar(MAX)') AS [TRIP/SHIPMENTS/SHIPMENT/UNLOADDATE],
        @XML.query(N'(/SHIPMENTS/UNLOADTIME)[2]').value('.', N'nvarchar(MAX)') AS [TRIP/SHIPMENTS/SHIPMENT/UNLOADTIME]
        FOR XML PATH (N'SHIPMENTS'), TYPE
    ) AS [SHIPMENTS/SHIPMENT]
FOR XML PATH(N''), ROOT(N'TRIPS'), TYPE
);
SELECT @xml AS [FileContent];

and obviously RETURNS :

<SHIPMENTS>
    <SHIPMENT>
      <SHIPMENTNO>UI45048839</SHIPMENTNO>
      <TRIPSEQUENCE>1</TRIPSEQUENCE>
      <UNLOADDATE>15/12</UNLOADDATE>
      <UNLOADTIME>09:00:00</UNLOADTIME>
      <SHIPMENTNO>UI45048841</SHIPMENTNO>
      <TRIPSEQUENCE>2</TRIPSEQUENCE>
      <UNLOADDATE>15/12</UNLOADDATE>
      <UNLOADTIME>09:00:00</UNLOADTIME>
      <SHIPMENTNO>UI45048840</SHIPMENTNO>
      <TRIPSEQUENCE>3</TRIPSEQUENCE>
      <UNLOADDATE>15/12</UNLOADDATE>
      <UNLOADTIME>09:00:00</UNLOADTIME>
    </SHIPMENT>
</SHIPMENTS>

I don't like my approach as it is mainly hardcoding and repeating the result.

How do i get the desired output dynamically ?

Thank you for your time !

Body:
It seems you are massively over-complicating this. You can use .query() to generate constructed XML containing the correct nodes

SELECT @xml.query('
    <SHIPMENTS>
    {
        for $s in /SHIPMENTS
        return
          <SHIPMENT>
              {
                $s/*[
                  local-name() = ("SHIPMENTNO", "TRIPSEQUENCE", "UNLOADDATE", "UNLOADTIME")
                  ]
              }
          </SHIPMENT>
    }
    </SHIPMENTS>
');

db<>fiddle

This creates a new root SHIPMENTS node.

Within that, it takes all original SHIPMENTS nodes and creates SHIPMENT nodes from them.

Each of those only contains the four relevant child nodes. It takes all nodes by using a wildcard, then checks them using local-name().


答:
If the Promise is rejected, the error would be thrown in different places, in the two example you wrote.

In the first, a rejected error would happen inside foo.

In the second, a rejected error would happen to the function that called foo

Title: Does "return await" makes any difference?


问:
Using ffmpeg to copy file with all streams intact (to fix any issues)
I am trying to use ffmpeg to copy files with all streams intact to fix various issues with files. ffmpeg is pretty good at reconstructing files and can remove various strangeness various encoders insert. The issue is that it fails on files with covers.

I am currently using:

```<code>ffmpeg -i input.ogg -map 0 -c copy output.ogg
</code>```

But for example on this file it fails with:

```<code>Input #0, ogg, from 'KR369.ogg':
  Duration: 01:32:53.80, start: 0.000000, bitrate: 164 kb/s
    Stream #0:0: Audio: vorbis, 44100 Hz, stereo, fltp, 152 kb/s
    Metadata:
      ALBUM           : Küchenradio.org
      ENCODED-BY      : auphonic.com
      ARTIST          : Philip Banse
      TITLE           : KR369 Hotel Berlin
      PUBLISHER       : Küchenstud.io
      URL             : http://kuechenstud.io/
      DATE            : 2014
      GENRE           : Podcast
      RIGHTS-DATE     : 2014
      RIGHTS          : 2014 CC BY SA
      LICENSE         : http://creativecommons.org/licenses/by-sa/3.0/de/
      RIGHTS-URI      : http://creativecommons.org/licenses/by-sa/3.0/de/
      ENCODED_BY      : auphonic.com
      comment         : DocPhil, Cindy, Frau Katja und Onkel Andi zu Besuch bei Susanne DeOcampo-Herrmann, der Chefköchin im Hotel Berlin. Wir waren lange nicht mehr zusammen und hatten wie gewohnt alle auf einmal viele Fragen zur: Küchenplanung, Hotelgeschichte, Filetier-Tech
    Stream #0:1: Video: mjpeg (Baseline), yuvj420p(pc, bt470bg/unknown/unknown), 500x500 [SAR 1:1 DAR 1:1], 90k tbr, 90k tbn, 90k tbc (attached pic)
    Metadata:
      comment         : Cover (front)
[ogg @ 0x55db241c2e80] Unsupported codec id in stream 1
Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
  Stream #0:1 -> #0:1 (copy)
    Last message repeated 1 times
</code>```

There seems to be a known issue about it but I am trying to see if there is any workaround. Maybe to do something with multiple passes, first manually extracting everything and then reconstructing? Or if there is another tool to use?

答:
You need to "unmap" the video stream, I believe using -map 0 -map -0:v will un-map the "video stream" (cover) so that you're left with only the audio.

See https://trac.ffmpeg.org/wiki/Map for more information.

Body:
I am trying to use ffmpeg to copy files with all streams intact to fix various issues with files. ffmpeg is pretty good at reconstructing files and can remove various strangeness various encoders insert. The issue is that it fails on files with covers.

I am currently using:

ffmpeg -i input.ogg -map 0 -c copy output.ogg

But for example on this file it fails with:

Input #0, ogg, from 'KR369.ogg':
  Duration: 01:32:53.80, start: 0.000000, bitrate: 164 kb/s
    Stream #0:0: Audio: vorbis, 44100 Hz, stereo, fltp, 152 kb/s
    Metadata:
      ALBUM           : Küchenradio.org
      ENCODED-BY      : auphonic.com
      ARTIST          : Philip Banse
      TITLE           : KR369 Hotel Berlin
      PUBLISHER       : Küchenstud.io
      URL             : http://kuechenstud.io/
      DATE            : 2014
      GENRE           : Podcast
      RIGHTS-DATE     : 2014
      RIGHTS          : 2014 CC BY SA
      LICENSE         : http://creativecommons.org/licenses/by-sa/3.0/de/
      RIGHTS-URI      : http://creativecommons.org/licenses/by-sa/3.0/de/
      ENCODED_BY      : auphonic.com
      comment         : DocPhil, Cindy, Frau Katja und Onkel Andi zu Besuch bei Susanne DeOcampo-Herrmann, der Chefköchin im Hotel Berlin. Wir waren lange nicht mehr zusammen und hatten wie gewohnt alle auf einmal viele Fragen zur: Küchenplanung, Hotelgeschichte, Filetier-Tech
    Stream #0:1: Video: mjpeg (Baseline), yuvj420p(pc, bt470bg/unknown/unknown), 500x500 [SAR 1:1 DAR 1:1], 90k tbr, 90k tbn, 90k tbc (attached pic)
    Metadata:
      comment         : Cover (front)
[ogg @ 0x55db241c2e80] Unsupported codec id in stream 1
Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
  Stream #0:1 -> #0:1 (copy)
    Last message repeated 1 times

There seems to be a known issue about it but I am trying to see if there is any workaround. Maybe to do something with multiple passes, first manually extracting everything and then reconstructing? Or if there is another tool to use?


问:
Django AttributeError object has no attribute 'upper'
I am implementing an API for an image labelling app.
I have customised a create() method for Tagging. A Tagging contains a tag, which is an object containing a name and a language. To make tags easier to compare to each other, I have to save all tags either in upper or lower case.

serializers.py

```<code>  def create(self, validated_data):
    """Create and return a new tagging"""

    user = None
    request = self.context.get("request")
    if request and hasattr(request, "user"):
      user = request.user

    score = 0

    tag_data = validated_data.pop('tag', None)
    if tag_data:
      tag = Tag.objects.get_or_create(**tag_data)[0]
      validated_data['tag'] = tag

    tagging = Tagging(
      user=user,
      gameround=validated_data.get("gameround"),
      resource=validated_data.get("resource"),
      tag=validated_data.get("tag"),
      created=datetime.now(),
      score=score,
      origin=""
    )
    tagging.save()
    return tagging
</code>```

I have tried both this

```<code>tag=validated_data.get("tag").upper()
</code>```

and this:

```<code>tag=validated_data.get("tag").lower()
</code>```

and I get an AttributeError 'Tag' object has no attribute 'upper' or 'Tag' object has no attribute 'lower'.

I want for this tag in the tagging object:

```<code>{
        "gameround_id": 65,
        "resource_id": 11601,
        "tag": {
            "name": "TagToTestNow",
            "language": "de"
        }
}
</code>```

to be saved something like "TAGTOTESTNOW" or "tagtotestnow" to make Tag comparison easier.

How can I achieve this?

答:
It's because you already created the tag, so it's not a dict anymore. You can do tag=tag directly in you Tagging object creation.

If you want all your tags to have the same case, you have to slightly modify the way you create your Tag in the first place, as follow:

tag = Tag.objects.get_or_create(
    language=tag_data['language'],
    name=tag_data['name'].upper()
)[0]
```

Body:
I am implementing an API for an image labelling app.
I have customised a create() method for Tagging. A Tagging contains a tag, which is an object containing a name and a language. To make tags easier to compare to each other, I have to save all tags either in upper or lower case.

serializers.py

  def create(self, validated_data):
    """Create and return a new tagging"""

    user = None
    request = self.context.get("request")
    if request and hasattr(request, "user"):
      user = request.user

    score = 0

    tag_data = validated_data.pop('tag', None)
    if tag_data:
      tag = Tag.objects.get_or_create(**tag_data)[0]
      validated_data['tag'] = tag

    tagging = Tagging(
      user=user,
      gameround=validated_data.get("gameround"),
      resource=validated_data.get("resource"),
      tag=validated_data.get("tag"),
      created=datetime.now(),
      score=score,
      origin=""
    )
    tagging.save()
    return tagging

I have tried both this

tag=validated_data.get("tag").upper()

and this:

tag=validated_data.get("tag").lower()

and I get an AttributeError 'Tag' object has no attribute 'upper' or 'Tag' object has no attribute 'lower'.

I want for this tag in the tagging object:

{
        "gameround_id": 65,
        "resource_id": 11601,
        "tag": {
            "name": "TagToTestNow",
            "language": "de"
        }
}

to be saved something like "TAGTOTESTNOW" or "tagtotestnow" to make Tag comparison easier.

How can I achieve this?


问:
Installed turtle package not recognized by vscode
I have an issue with working with the turtle package in python. I have Anaconda installed on my computer. Within Anaconda I have installed the turtle package with pip command (there is no conda install option for turtle as to my knowledge).

When I start a jupyter notebook and import turtle everything works just fine.

When I start vscode from conda and use the same python environment, I get an import error from vscode saying: importerror: cannot import name Turtle.

Why is this happening and how could I start turtle in vscode?

Thank you!

答:
Solved! Shayan solved the problem in the comments... I was so stupid to name my file turtle.py... no comment
I renamed the file and works really great!
Thank you Shayan!</p>


问:
Split C# collection into equal parts, maintaining sort
I am trying to split a collection into multiple collections while maintaining a sort I have on the collection.  I have tried using the following extension method, but it breaks them incorrectly.  Basically, if I was to look at the items in the collection, the order should be the same when compared to the broken up collections joined.  Here is the code I am using that doesn't work:

```<code>public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
        {
            int i = 0;
            var splits = from name in list
                         group name by i++ % parts into part
                         select part.AsEnumerable();
            return splits;
        }
</code>```

int parts = number of sub enumerables

答:
The code provided in the first answer splits a group of 21 elements to 10 with the following number of elements in the partitions:
3, 3, 3, 3, 3, 3, 3, 0, 0, 0

The wanted element number is:
3, 2, 2, 2, 2, 2, 2, 2, 2, 2

I made a small change in the provided code to give the wanted partition sizes

```<code>    public static List<T>[] Partition<T>(List<T> list, int totalPartitions)
    {
        if (list == null)
            throw new ArgumentNullException("list");

        if (totalPartitions < 1)
            throw new ArgumentOutOfRangeException("totalPartitions");

        List<T>[] partitions = new List<T>[totalPartitions];
        int k = 0;

        for (int i = 0; i < partitions.Length; i++)
        {
            int maxSize = (int)Math.Ceiling( (list.Count - i) / (double)totalPartitions);
            partitions[i] = new List<T>();
            for (int j = k; j < k + maxSize; j++)
            {
                if (j >= list.Count)
                    break;
                partitions[i].Add(list[j]);
            }
            k += maxSize;
        }
        return partitions;
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to split a collection into multiple collections while maintaining a sort I have on the collection.  I have tried using the following extension method, but it breaks them incorrectly.  Basically, if I was to look at the items in the collection, the order should be the same when compared to the broken up collections joined.  Here is the code I am using that doesn't work:

public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
        {
            int i = 0;
            var splits = from name in list
                         group name by i++ % parts into part
                         select part.AsEnumerable();
            return splits;
        }

int parts = number of sub enumerables

Body:
The code provided in the first answer splits a group of 21 elements to 10 with the following number of elements in the partitions:
3, 3, 3, 3, 3, 3, 3, 0, 0, 0

The wanted element number is:
3, 2, 2, 2, 2, 2, 2, 2, 2, 2

I made a small change in the provided code to give the wanted partition sizes

    public static List<T>[] Partition<T>(List<T> list, int totalPartitions)
    {
        if (list == null)
            throw new ArgumentNullException("list");

        if (totalPartitions < 1)
            throw new ArgumentOutOfRangeException("totalPartitions");

        List<T>[] partitions = new List<T>[totalPartitions];
        int k = 0;

        for (int i = 0; i < partitions.Length; i++)
        {
            int maxSize = (int)Math.Ceiling( (list.Count - i) / (double)totalPartitions);
            partitions[i] = new List<T>();
            for (int j = k; j < k + maxSize; j++)
            {
                if (j >= list.Count)
                    break;
                partitions[i].Add(list[j]);
            }
            k += maxSize;
        }
        return partitions;
    }


问:
How to hide a DIV element using RegEx and Jquery
I would like to hide all other element except class="imagebrowser" in following,

```<code><div class="entry">
    <p>Heading 1</p>
    <p>Heading 2</p>
        ...
    <p>Heading n</p>
    <b>This is abold text</b>
    <div>This is a div element</div>

    <div class="imagebrowser">
        Hello world
    </div>
</div>
</code>```

Expected result,

```<code><div class="entry">

    <div class="imagebrowser">
        Hello world
    </div>
</div>
</code>```

Any help please

答:
Have you tried:

```<code>$('.entry').children().hide();
$('.imagebrowser').show();
</code>```

This should hide all the contents of the entry div, including the p tags, and then show the imagebrowser div afterwards.

Body:
I would like to hide all other element except class="imagebrowser" in following,

Heading 1

Heading 2

        ...

Heading n

    This is abold text

This is a div element

        Hello world

Expected result,

        Hello world

Any help please

Body:
Have you tried:

$('.entry').children().hide();
$('.imagebrowser').show();

This should hide all the contents of the entry div, including the p tags, and then show the imagebrowser div afterwards.


问:
How to remove special characters from the `TextField` in SwiftUI
I need to apply some validations in my form like remove special character, accept only number, alphabets, alphanumeric, and only specific length of a string.

I have many text fields, in many places in my app. So that I'm creating extensions to Binding, and trying to apply conditions when editing.

These filters/conditions using for @State, @Published, and @Binding variables.

Here is my code:

struct ContentView: View {
    @State var name = ""
    var body: some View {
        InputField(text: $name)
    }
}

struct InputField: View {
    @Binding var text: String
    var body: some View {
        VStack {
            TextField("Name here...", text: $text.limit(6).alphaNumeric)
                .frame(maxWidth: .infinity, minHeight: 48,  alignment: .leading)
        }.padding()
    }
}

extension Binding where Value == String {

    var alphaNumeric: Binding<String> {
        Binding<String>(get: { self.wrappedValue },
                        set: {
            self.wrappedValue = $0.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)})
    }

    func limit(_ length: Int) -> Binding<String> {
        Binding<String>(get: { self.wrappedValue },
                        set: {
            print($0.prefix(length))
            self.wrappedValue = String($0.prefix(length))
        })
    }
}
```

Here in the above code $text.limit(6).alphaNumeric, I'm trying to limit the length to 6 characters and only allow the alphaNumeric string.

答:
How about a custom TextField with checks, instead of messing with Binding Wrapper itself:
(with OPs full code to proof that binding works)</p>
```<code>struct ContentView: View {
    @State var name = ""
    @State var number = ""
    var body: some View {
        InputField(text: $name, number: $number)
    }
}

struct InputField: View {
    @Binding var text: String
    @Binding var number: String
    var body: some View {
        VStack {
            TextFieldWithCheck("Name here...", text: $text, limit: 15, allowed: .alphanumerics)
                .frame(maxWidth: .infinity, minHeight: 48,  alignment: .leading)

            TextFieldWithCheck("Phone no here...", text: $number, limit: 9, allowed: .decimalDigits)
                .frame(maxWidth: .infinity, minHeight: 48,  alignment: .leading)

        }.padding()
    }
}

// here is the custom TextField itself
struct TextFieldWithCheck: View {

    let label: LocalizedStringKey
    @Binding var text: String
    let limit: Int
    let allowed: CharacterSet

    init(_ label: LocalizedStringKey, text: Binding<String>, limit: Int = Int.max, allowed: CharacterSet = .alphanumerics) {
        self.label = label
        self._text = Binding(projectedValue: text)
        self.limit = limit
        self.allowed = allowed
    }

    var body: some View {
        TextField(label, text: $text)
            .onChange(of: text) { _ in
                // all credits to Leo Dabus:
                text = String(text.prefix(limit).unicodeScalars.filter(allowed.contains))
            }
    }
}
</code>```

Body:
I need to apply some validations in my form like remove special character, accept only number, alphabets, alphanumeric, and only specific length of a string.

I have many text fields, in many places in my app. So that I'm creating extensions to Binding, and trying to apply conditions when editing.

These filters/conditions using for @State, @Published, and @Binding variables.

Here is my code:

struct ContentView: View {
    @State var name = ""
    var body: some View {
        InputField(text: $name)
    }
}

struct InputField: View {
    @Binding var text: String
    var body: some View {
        VStack {
            TextField("Name here...", text: $text.limit(6).alphaNumeric)
                .frame(maxWidth: .infinity, minHeight: 48,  alignment: .leading)
        }.padding()
    }
}

extension Binding where Value == String {

    var alphaNumeric: Binding<String> {
        Binding<String>(get: { self.wrappedValue },
                        set: {
            self.wrappedValue = $0.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)})
    }

    func limit(_ length: Int) -> Binding<String> {
        Binding<String>(get: { self.wrappedValue },
                        set: {
            print($0.prefix(length))
            self.wrappedValue = String($0.prefix(length))
        })
    }
}

Here in the above code $text.limit(6).alphaNumeric, I'm trying to limit the length to 6 characters and only allow the alphaNumeric string.

Body:
How about a custom TextField with checks, instead of messing with Binding Wrapper itself:
(with OPs full code to proof that binding works)

struct ContentView: View {
    @State var name = ""
    @State var number = ""
    var body: some View {
        InputField(text: $name, number: $number)
    }
}

struct InputField: View {
    @Binding var text: String
    @Binding var number: String
    var body: some View {
        VStack {
            TextFieldWithCheck("Name here...", text: $text, limit: 15, allowed: .alphanumerics)
                .frame(maxWidth: .infinity, minHeight: 48,  alignment: .leading)

            TextFieldWithCheck("Phone no here...", text: $number, limit: 9, allowed: .decimalDigits)
                .frame(maxWidth: .infinity, minHeight: 48,  alignment: .leading)

        }.padding()
    }
}

// here is the custom TextField itself
struct TextFieldWithCheck: View {

    let label: LocalizedStringKey
    @Binding var text: String
    let limit: Int
    let allowed: CharacterSet

    init(_ label: LocalizedStringKey, text: Binding<String>, limit: Int = Int.max, allowed: CharacterSet = .alphanumerics) {
        self.label = label
        self._text = Binding(projectedValue: text)
        self.limit = limit
        self.allowed = allowed
    }

    var body: some View {
        TextField(label, text: $text)
            .onChange(of: text) { _ in
                // all credits to Leo Dabus:
                text = String(text.prefix(limit).unicodeScalars.filter(allowed.contains))
            }
    }
}


问:
How to clean up ActiveStorage record and storage folder of development environment?
According to Rails (edge6.0) guides, we can do maintenance work for ActiveStorage used in System Test and Integration Test by calling the following statement respectively

  # System Test
  FileUtils.rm_rf("#{Rails.root}/storage_test")

  # Integration Test
  FileUtils.rm_rf(Rails.root.join('tmp', 'storage'))
```
<p>I want to know -</p>
<p>Are there any Rails built-in functions or rake commands or gems to do the following?</p>
<ol>
<li>remove the orphan blobs (<code>ActiveStorage::Blob</code> records those are no longer associated with any <code>ActiveStorage::Attachment</code> record)</li>
<li>remove the orphan files (files those are no longer associated with any <code>ActiveStorage::Blob</code> record)</li>
</ol>
<p>I do not see any relevant rake tasks with <code>rails --tasks</code>.</p>
<p>Currently, I am using</p>
<pre class="lang-rb prettyprint-override"><code># remove blob not associated with any attachment
ActiveStorage::Blob.where.not(id: ActiveStorage::Attachment.select(:blob_id)).find_each do |blob|
  blob.purge # or purge_later
end
</code>```

and this script to clean orphan files (via rails console)

```<code># run these ruby statement in project rails console
# to remove the orphan file
include ActionView::Helpers::NumberHelper

dry_run = true
files = Dir['storage/??/??/*']

orphan = files.select do |f|
  !ActiveStorage::Blob.exists?(key: File.basename(f))
end

sum = 0
orphan.each do |f|
  sum += File.size(f)
  FileUtils.remove(f) unless dry_run
end

puts "Size: #{number_to_human_size(sum)}"
</code>```

答:
```<code>ActiveStorage::Blob.unattached.each(&:purge_later)
</code>```

or just purge if you don't want it to happen in the background.

Body:
According to Rails (edge6.0) guides, we can do maintenance work for ActiveStorage used in System Test and Integration Test by calling the following statement respectively

  # System Test
  FileUtils.rm_rf("#{Rails.root}/storage_test")

  # Integration Test
  FileUtils.rm_rf(Rails.root.join('tmp', 'storage'))

I want to know -

Are there any Rails built-in functions or rake commands or gems to do the following?

remove the orphan blobs (ActiveStorage::Blob records those are no longer associated with any ActiveStorage::Attachment record)

remove the orphan files (files those are no longer associated with any ActiveStorage::Blob record)

I do not see any relevant rake tasks with rails --tasks.

Currently, I am using

# remove blob not associated with any attachment
ActiveStorage::Blob.where.not(id: ActiveStorage::Attachment.select(:blob_id)).find_each do |blob|
  blob.purge # or purge_later
end

and this script to clean orphan files (via rails console)

# run these ruby statement in project rails console
# to remove the orphan file
include ActionView::Helpers::NumberHelper

dry_run = true
files = Dir['storage/??/??/*']

orphan = files.select do |f|
  !ActiveStorage::Blob.exists?(key: File.basename(f))
end

sum = 0
orphan.each do |f|
  sum += File.size(f)
  FileUtils.remove(f) unless dry_run
end

puts "Size: #{number_to_human_size(sum)}"

Body:
ActiveStorage::Blob.unattached.each(&:purge_later)

or just purge if you don't want it to happen in the background.


问:
Using Material icons inside a library component with Angular Nx Storybook
i am having hard time in using Angular material icons in Nx storybook.

Here is how these are configured in angular.json, i think i am not configuring it correctly, please let me know what is the correct way to do it. Please note I cannot use link as following since, i am building a library, its not an application.

```<code><link
      href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet"
    />
</code>```

This is how icon is showing up.

答:
I did this way. you can try this

```<code>npm install material-design-icons

 // angular.json

   "styles": [
     "node_modules/material-design-icons/iconfont/material-icons.css"
   ]

// style.css
   @import '~material-design-icons/iconfont/material-icons.css';

// html
<i class="material-icons">cloud_upload</i>
</code>```

Body:
i am having hard time in using Angular material icons in Nx storybook.

Here is how these are configured in angular.json, i think i am not configuring it correctly, please let me know what is the correct way to do it. Please note I cannot use link as following since, i am building a library, its not an application.

<link
      href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet"
    />

This is how icon is showing up.

Body:
I did this way. you can try this

npm install material-design-icons

 // angular.json

   "styles": [
     "node_modules/material-design-icons/iconfont/material-icons.css"
   ]

// style.css
   @import '~material-design-icons/iconfont/material-icons.css';

// html
<i class="material-icons">cloud_upload</i>