问:
How can I speed up a python loop with a timestamp interval condition
I have this code that is rather done in a hurry but it works in general. The only thing it runs forever. The idea is to update 2 columns on a table that is holding 1495748 rows, so the number of the list of timestamp being queried in first place. For each update value there has to be done a comparison in which the timestamp has to be in an hourly interval that is formed by two timestamps coming from the api in two different dicts. Is there a way to speed up things a little or maybe multiprocess it?

Hint: db_mac = db_connection to a Postgres database.

the response looks like this:
{'meta': {'source': 'National Oceanic and Atmospheric Administration, Deutscher Wetterdienst'}, 'data': [{'time': '2019-11-26 23:00:00', 'time_local': '2019-11-27 00:00', 'temperature': 8.3, 'dewpoint': 5.9, 'humidity': 85, 'precipitation': 0, 'precipitation_3': None, 'precipitation_6': None, 'snowdepth': None, 'windspeed': 11, 'peakgust': 21, 'winddirection': 160, 'pressure': 1004.2, 'condition': 4}, {'time': '2019-11-27 00:00:00', ....

```<code>import requests
import db_mac
from collections import defaultdict
import datetime
import time
t = time.time()

station = [10382,"DE","Berlin / Tegel",52.5667,13.3167,37,"EDDT",10382,"TXL","Europe/Berlin"]

dates = [("2019-11-20","2019-11-22"), ("2019-11-27","2019-12-02") ]
insert_dict = defaultdict(tuple)

hist_weather_list = []

for d in dates:
    end = d[1]
    start = d[0]
    print(start, end)
    url = "https://api.meteostat.net/v1/history/hourly?station={station}&start={start}&end={end}&time_zone={timezone}&&time_format=Y-m-d%20H:i&key=<APIKEY>".format(station=station[0], start=start, end=end, timezone=station[-1])

    response = requests.get(url)
    weather = response.json()
    print(weather)
    for i in weather["data"]:
        hist_weather_list.append(i)

sql = "select timestamp from dump order by timestamp asc"
result = db_mac.execute(sql)

hours, rem = divmod(time.time() - t, 3600)
minutes, seconds = divmod(rem, 60)
print("step1 {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))

for row in result:
    try:
        ts_dump = datetime.datetime.timestamp(row[0])
        for i, hour in enumerate(hist_weather_list):
            ts1 = datetime.datetime.timestamp(datetime.datetime.strptime(hour["time"], '%Y-%m-%d %H:%M:%S'))

            ts2 = datetime.datetime.timestamp(datetime.datetime.strptime(hist_weather_list[i + 1]["time"], '%Y-%m-%d %H:%M:%S'))

            if ts1 <= ts_dump and ts_dump < ts2:

                insert_dict[row[0]] = (hour["temperature"], hour["pressure"])

    except Exception as e:
        pass

hours, rem = divmod(time.time() - t, 3600)
minutes, seconds = divmod(rem, 60)
print("step2 {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))

for key, value in insert_dict.items():
    sql2 = """UPDATE dump SET temperature = """ + str(value[0]) + """, pressure = """+ str(value[1]) + """ WHERE timestamp = '"""+ str(key) + """';"""
    db_mac.execute(sql2)

hours, rem = divmod(time.time() - t, 3600)
minutes, seconds = divmod(rem, 60)
print("step3 {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))
</code>```

UPDATE the code for multiprocessing. I'll let it run the night and give an update of the running time.

```<code>import requests
import db_mac
from collections import defaultdict
import datetime
import time
import multiprocessing as mp
t = time.time()

station = [10382,"DE","Berlin / Tegel",52.5667,13.3167,37,"EDDT",10382,"TXL","Europe/Berlin"]

dates = [("2019-11-20","2019-11-22"), ("2019-11-27","2019-12-02") ]
insert_dict = defaultdict(tuple)

hist_weather_list = []

for d in dates:
    end = d[1]
    start = d[0]
    print(start, end)
    url = "https://api.meteostat.net/v1/history/hourly?station={station}&start={start}&end={end}&time_zone={timezone}&&time_format=Y-m-d%20H:i&key=wzwi2YR5".format(station=station[0], start=start, end=end, timezone=station[-1])

    response = requests.get(url)
    weather = response.json()
    print(weather)
    for i in weather["data"]:
        hist_weather_list.append(i)

sql = "select timestamp from dump order by timestamp asc"
result = db_mac.execute(sql)

hours, rem = divmod(time.time() - t, 3600)
minutes, seconds = divmod(rem, 60)
print("step1 {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))

def find_parameters(x):

    for row in result[x[0]:x[1]]:
        try:
            ts_dump = datetime.datetime.timestamp(row[0])
            for i, hour in enumerate(hist_weather_list):
                ts1 = datetime.datetime.timestamp(datetime.datetime.strptime(hour["time"], '%Y-%m-%d %H:%M:%S'))

                ts2 = datetime.datetime.timestamp(datetime.datetime.strptime(hist_weather_list[i + 1]["time"], '%Y-%m-%d %H:%M:%S'))

                if ts1 <= ts_dump and ts_dump < ts2:

                    insert_dict[row[0]] = (hour["temperature"], hour["pressure"])

        except Exception as e:
            pass

step1 = int(len(result) /4)
step2 = 2 * step1
step3 = 3 * step1
step4 = len(result)
steps = [[0,step1],[step1,step2],[step2,step3], [step3,step4]]

pool = mp.Pool(mp.cpu_count())
pool.map(find_parameters, steps)

hours, rem = divmod(time.time() - t, 3600)
minutes, seconds = divmod(rem, 60)
print("step2 {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))

for key, value in insert_dict.items():
    sql2 = """UPDATE dump SET temperature = """ + str(value[0]) + """, pressure = """+ str(value[1]) + """ WHERE timestamp = '"""+ str(key) + """';"""
    db_mac.execute(sql2)

hours, rem = divmod(time.time() - t, 3600)
minutes, seconds = divmod(rem, 60)
print("step3 {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))
</code>```

UPDATE 2
It finished and ran for 2:45 hours in 4 cores on a raspberry pi. Though is there a more efficient way to do such things?

答:
So theres a few minor things I can think of to speed this up a little. I figure anything little bit helps especially if you have a lot of rows to process. For starters, print statements can slow down your code a lot. I'd get rid of those if they are unneeded.

Most importantly, you are calling the api in every iteration of the loop. Waiting for a response from the API is probably taking up the bulk of your time.  I looked a bit at the api you are using, but don't know the exact case you're using it for or what your dates "start" and "end" look like, but if you could do it in less calls that would surely speed up this loop by a lot. Another way you can do this is, it looks like the api has a .csv version of the data you can download and use. Running this on local data would be way faster. If you choose to go this route i'd suggest using pandas. (Sorry if you already know pandas and i'm over explaining) You can use: df = pd.read_csv("filename.csv") and edit the table from there easily. You can also do df.to_sql(params) to write to your data base. Let me know if you want help forming a pandas version of this code.

Also, not sure from your code if this would cause an error, but I would try, instead of your for loop (for i in weather["data"]).
  hist_weather_list += weather["data"]
   or possibly
  hist_weather_list += [weather["data"]

Let me know how it goes!

Body:
I have this code that is rather done in a hurry but it works in general. The only thing it runs forever. The idea is to update 2 columns on a table that is holding 1495748 rows, so the number of the list of timestamp being queried in first place. For each update value there has to be done a comparison in which the timestamp has to be in an hourly interval that is formed by two timestamps coming from the api in two different dicts. Is there a way to speed up things a little or maybe multiprocess it?

Hint: db_mac = db_connection to a Postgres database.

the response looks like this:
{'meta': {'source': 'National Oceanic and Atmospheric Administration, Deutscher Wetterdienst'}, 'data': [{'time': '2019-11-26 23:00:00', 'time_local': '2019-11-27 00:00', 'temperature': 8.3, 'dewpoint': 5.9, 'humidity': 85, 'precipitation': 0, 'precipitation_3': None, 'precipitation_6': None, 'snowdepth': None, 'windspeed': 11, 'peakgust': 21, 'winddirection': 160, 'pressure': 1004.2, 'condition': 4}, {'time': '2019-11-27 00:00:00', ....

import requests
import db_mac
from collections import defaultdict
import datetime
import time
t = time.time()

station = [10382,"DE","Berlin / Tegel",52.5667,13.3167,37,"EDDT",10382,"TXL","Europe/Berlin"]

dates = [("2019-11-20","2019-11-22"), ("2019-11-27","2019-12-02") ]
insert_dict = defaultdict(tuple)

hist_weather_list = []

for d in dates:
    end = d[1]
    start = d[0]
    print(start, end)
    url = "https://api.meteostat.net/v1/history/hourly?station={station}&start={start}&end={end}&time_zone={timezone}&&time_format=Y-m-d%20H:i&key=<APIKEY>".format(station=station[0], start=start, end=end, timezone=station[-1])

    response = requests.get(url)
    weather = response.json()
    print(weather)
    for i in weather["data"]:
        hist_weather_list.append(i)

sql = "select timestamp from dump order by timestamp asc"
result = db_mac.execute(sql)

hours, rem = divmod(time.time() - t, 3600)
minutes, seconds = divmod(rem, 60)
print("step1 {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))

for row in result:
    try:
        ts_dump = datetime.datetime.timestamp(row[0])
        for i, hour in enumerate(hist_weather_list):
            ts1 = datetime.datetime.timestamp(datetime.datetime.strptime(hour["time"], '%Y-%m-%d %H:%M:%S'))

            ts2 = datetime.datetime.timestamp(datetime.datetime.strptime(hist_weather_list[i + 1]["time"], '%Y-%m-%d %H:%M:%S'))

            if ts1 <= ts_dump and ts_dump < ts2:

                insert_dict[row[0]] = (hour["temperature"], hour["pressure"])

    except Exception as e:
        pass

hours, rem = divmod(time.time() - t, 3600)
minutes, seconds = divmod(rem, 60)
print("step2 {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))

for key, value in insert_dict.items():
    sql2 = """UPDATE dump SET temperature = """ + str(value[0]) + """, pressure = """+ str(value[1]) + """ WHERE timestamp = '"""+ str(key) + """';"""
    db_mac.execute(sql2)

hours, rem = divmod(time.time() - t, 3600)
minutes, seconds = divmod(rem, 60)
print("step3 {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))

UPDATE the code for multiprocessing. I'll let it run the night and give an update of the running time.

import requests
import db_mac
from collections import defaultdict
import datetime
import time
import multiprocessing as mp
t = time.time()

station = [10382,"DE","Berlin / Tegel",52.5667,13.3167,37,"EDDT",10382,"TXL","Europe/Berlin"]

dates = [("2019-11-20","2019-11-22"), ("2019-11-27","2019-12-02") ]
insert_dict = defaultdict(tuple)

hist_weather_list = []

for d in dates:
    end = d[1]
    start = d[0]
    print(start, end)
    url = "https://api.meteostat.net/v1/history/hourly?station={station}&start={start}&end={end}&time_zone={timezone}&&time_format=Y-m-d%20H:i&key=wzwi2YR5".format(station=station[0], start=start, end=end, timezone=station[-1])

    response = requests.get(url)
    weather = response.json()
    print(weather)
    for i in weather["data"]:
        hist_weather_list.append(i)

sql = "select timestamp from dump order by timestamp asc"
result = db_mac.execute(sql)

hours, rem = divmod(time.time() - t, 3600)
minutes, seconds = divmod(rem, 60)
print("step1 {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))

def find_parameters(x):

    for row in result[x[0]:x[1]]:
        try:
            ts_dump = datetime.datetime.timestamp(row[0])
            for i, hour in enumerate(hist_weather_list):
                ts1 = datetime.datetime.timestamp(datetime.datetime.strptime(hour["time"], '%Y-%m-%d %H:%M:%S'))

                ts2 = datetime.datetime.timestamp(datetime.datetime.strptime(hist_weather_list[i + 1]["time"], '%Y-%m-%d %H:%M:%S'))

                if ts1 <= ts_dump and ts_dump < ts2:

                    insert_dict[row[0]] = (hour["temperature"], hour["pressure"])

        except Exception as e:
            pass

step1 = int(len(result) /4)
step2 = 2 * step1
step3 = 3 * step1
step4 = len(result)
steps = [[0,step1],[step1,step2],[step2,step3], [step3,step4]]

pool = mp.Pool(mp.cpu_count())
pool.map(find_parameters, steps)

hours, rem = divmod(time.time() - t, 3600)
minutes, seconds = divmod(rem, 60)
print("step2 {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))

for key, value in insert_dict.items():
    sql2 = """UPDATE dump SET temperature = """ + str(value[0]) + """, pressure = """+ str(value[1]) + """ WHERE timestamp = '"""+ str(key) + """';"""
    db_mac.execute(sql2)

hours, rem = divmod(time.time() - t, 3600)
minutes, seconds = divmod(rem, 60)
print("step3 {:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))

UPDATE 2
It finished and ran for 2:45 hours in 4 cores on a raspberry pi. Though is there a more efficient way to do such things?


来源: stackexchange

问:
SQL Server 2008 - MERGE statement - Perform multiple actions in WHEN MATCHED block
I am trying to use MERGE statement to accomplish the following. I have a SP and i am passing TableValue Parameter to it. This is how my SP looks like:

```<code>CREATE PROC sp_AddInformation
@IntoTbl dbo.Information  READONLY ,
@baseEventType dbo.EventType READONLY

AS

BEGIN

MERGE Information
USING (SELECT InfoID, NewsID, NewsType FROM @IntoTbl ) AS baseInfo (InfoID, NewsID, NewsType)
ON (info.infoID = baseInfo.InfoID)
WHEN MATCHED
        THEN
        --EXEC dbo.sp_insertEventInfo(@baseEventType) (This is not working)

        UPDATE set Info.Reporter = baseInfo.Reporter
WHEN NOT MATCHED BY SOURCE
        THEN

        DELETE
WHEN NOT MATCHED BY TARGET
    THEN INSERT VALUES (InfoID, NewsID,NewsType);
END
</code>```

Does anyone know how can i call another SP or perform another MERGE on other tables in WHEN MATCHED block?

答:
It is not possible to call a stored procedure or merge from the when matched block. You are only allowed to do update or delete (or both). From the documentation on merge.

```<code> <merge_matched>::=
     { UPDATE SET <set_clause> | DELETE }
</code>```

You can use the output clause to capture the rows that was updated in when matched. The output can be captured in a table variable that you then can use in another merge statement or in a stored procedure. Use inserted.* and $action in the output. The rows from when matched is where $action = 'UPDATE'

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use MERGE statement to accomplish the following. I have a SP and i am passing TableValue Parameter to it. This is how my SP looks like:

CREATE PROC sp_AddInformation
@IntoTbl dbo.Information  READONLY ,
@baseEventType dbo.EventType READONLY

AS

BEGIN

MERGE Information
USING (SELECT InfoID, NewsID, NewsType FROM @IntoTbl ) AS baseInfo (InfoID, NewsID, NewsType)
ON (info.infoID = baseInfo.InfoID)
WHEN MATCHED
        THEN
        --EXEC dbo.sp_insertEventInfo(@baseEventType) (This is not working)

        UPDATE set Info.Reporter = baseInfo.Reporter
WHEN NOT MATCHED BY SOURCE
        THEN

        DELETE
WHEN NOT MATCHED BY TARGET
    THEN INSERT VALUES (InfoID, NewsID,NewsType);
END

Does anyone know how can i call another SP or perform another MERGE on other tables in WHEN MATCHED block?

Body:
It is not possible to call a stored procedure or merge from the when matched block. You are only allowed to do update or delete (or both). From the documentation on merge.

 <merge_matched>::=
     { UPDATE SET <set_clause> | DELETE }

You can use the output clause to capture the rows that was updated in when matched. The output can be captured in a table variable that you then can use in another merge statement or in a stored procedure. Use inserted.* and $action in the output. The rows from when matched is where $action = 'UPDATE'


问:
What is the proper way to set my Java Swing application's title in the Gnome top bar?
I'm using the following code to set my Java Swing application's title in Gnome 3's top bar.  However, when I run it, I get the warnings shown below the code.  Is there a better way to set the application title in code?  Please note that this not a question about setting the title of the window itself.

```<code>try
{
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Field awtAppClassNameField = toolkit.getClass().getDeclaredField("awtAppClassName");
    awtAppClassNameField.setAccessible(true);
    awtAppClassNameField.set(toolkit, "FNDice");
}
catch (NoSuchFieldException | IllegalAccessException e)
{
    e.printStackTrace();
}
</code>```

Here are the warnings I see when I run my application.

```<code>WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.gmail.fishnet37222.fndice.App (file:/home/dave/IdeaProjects/fndice/target/classes/) to field sun.awt.X11.XToolkit.awtAppClassName
WARNING: Please consider reporting this to the maintainers of com.gmail.fishnet37222.fndice.App
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
</code>```

答:
This is a side-effect of two different things, using a non-API interface via reflection, and using a new JVM which is using the module loading system (introduced in Java 9)

With Java Modules, JAR files now contain more metadata about what parts of the contained code should be accessed by other JAR files.  This permits a lot of things that were only previously possible with OSGI or custom class loaders.

Odds are the code you are working with and the libraries you are working with have not been updated to correctly work / interface with the module system, which is enforcing by default.  To get legacy reflective code to access non-API entry points in a backwards compatible way, you need to add the command line flag --illegal-access=permit to your java launch command.

Note that this might be needed for both the run-time launch and the compiler launch, if you are doing both.

Out of curiosity, on this platform, does jframe.setTitle("title") not work, or is the code base before setTitle was available?

Body:
I'm using the following code to set my Java Swing application's title in Gnome 3's top bar.  However, when I run it, I get the warnings shown below the code.  Is there a better way to set the application title in code?  Please note that this not a question about setting the title of the window itself.

try
{
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Field awtAppClassNameField = toolkit.getClass().getDeclaredField("awtAppClassName");
    awtAppClassNameField.setAccessible(true);
    awtAppClassNameField.set(toolkit, "FNDice");
}
catch (NoSuchFieldException | IllegalAccessException e)
{
    e.printStackTrace();
}

Here are the warnings I see when I run my application.

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.gmail.fishnet37222.fndice.App (file:/home/dave/IdeaProjects/fndice/target/classes/) to field sun.awt.X11.XToolkit.awtAppClassName
WARNING: Please consider reporting this to the maintainers of com.gmail.fishnet37222.fndice.App
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

ContentLicense: CC BY-SA 4.0


问:
Change Azure virtual machine name in Azure portal
Can we change the name of an Azure Virtual Machine in the Azure portal? I am sure we cannot change it via portal, do we have any PowerShell cmdlet to change the virtual machine name??

Note: I am not referring to VM name inside the VM, but the name that is displayed in the Azure Portal.

答:
Credit to Oliver Miossec for this non-destructive azure powershell script that creates a new VM, with some changes for parameters. You can find his post here. It's extra awesome because it'll also fix badly-named discs and NICs associated with the machine.</p>

```<code>#Deletes and recreates a VM
param (
    [Parameter(Mandatory=$true)]
    [string]$vmOldName,
    [Parameter(Mandatory=$true)]
    [string]$vmNewName,
    [Parameter(Mandatory=$true)]
    [string]$rgName,
    [string]$newLocation #Optional, moves the VM to a new Geographic Location
)

$ErrorActionPreference = "Stop"

Write-Host "Get and Shutdown old VM, Create new config"
$SourceVmObject = get-azvm -Name $vmOldName -ResourceGroupName $rgName

if ([string]::IsNullOrEmpty($newLocation)) {
    $newLocation = $SourceVmObject.Location
    Write-Host "No new location specified, using the current VM's existing location: $newLocation"
}

$SourceVmPowerStatus = (get-azvm -Name $SourceVmObject.Name -ResourceGroupName $SourceVmObject.ResourceGroupName -Status).Statuses | where-object code -like "PowerState*"

if ($SourceVmPowerStatus -ne "VM deallocated") {
    stop-azVm -Name $SourceVmObject.Name -ResourceGroupName $SourceVmObject.ResourceGroupName -Force
    Start-Sleep -Seconds 30 #Wait to ensure VM is shutdown.
}

$NewVmObject = New-AzVMConfig -VMName $vmNewName -VMSize $SourceVmObject.HardwareProfile.VmSize

Write-Host "Create new Network Objects"
$subnetID = (Get-AzNetworkInterface -ResourceId $SourceVmObject.NetworkProfile.NetworkInterfaces[0].id).IpConfigurations.Subnet.id

$nic = New-AzNetworkInterface -Name "$($vmNewName.ToLower())-0-nic" -ResourceGroupName $SourceVmObject.ResourceGroupName  -Location $SourceVmObject.Location -SubnetId $SubnetId

Add-AzVMNetworkInterface -VM $NewVmObject -Id $nic.Id

Write-Host "Move OS Disk"
$SourceOsDiskSku = (get-azdisk -ResourceGroupName $SourceVmObject.ResourceGroupName -DiskName $SourceVmObject.StorageProfile.OsDisk.name).Sku.Name

$SourceOsDiskSnapConfig =  New-AzSnapshotConfig  -SourceUri $SourceVmObject.StorageProfile.OsDisk.ManagedDisk.Id -Location $SourceVmObject.Location -CreateOption copy

$SourceOsDiskSnap = New-AzSnapshot -Snapshot $SourceOsDiskSnapConfig  -SnapshotName "$($SourceVmObject.Name)-os-snap"  -ResourceGroupName $SourceVmObject.ResourceGroupName

$TargetOsDiskConfig = New-AzDiskConfig -AccountType $SourceOsDiskSku -Location $SourceVmObject.Location -CreateOption Copy -SourceResourceId $SourceOsDiskSnap.Id

$TargetOsDisk = New-AzDisk -Disk $TargetOsDiskConfig -ResourceGroupName $SourceVmObject.ResourceGroupName -DiskName "$($vmNewName.ToLower())-os-vhd"

Set-AzVMOSDisk -VM $NewVmObject -ManagedDiskId $TargetOsDisk.Id -CreateOption Attach -Windows

Write-Host "Create new Data Disks"
Foreach ($SourceDataDisk in $SourceVmObject.StorageProfile.DataDisks) {

    $SourceDataDiskSku = (get-azdisk -ResourceGroupName $SourceVmObject.ResourceGroupName -DiskName $SourceDataDisk.name).Sku.Name

    $SourceDataDiskSnapConfig =  New-AzSnapshotConfig  -SourceUri $SourceDataDisk.ManagedDisk.Id -Location $SourceVmObject.Location -CreateOption copy

    $SourceDataDiskSnap = New-AzSnapshot -Snapshot $SourceDataDiskSnapConfig  -SnapshotName "$($SourceVmObject.Name)-$($SourceDataDisk.name)-snap"  -ResourceGroupName $SourceVmObject.ResourceGroupName

    $TargetDataDiskConfig = New-AzDiskConfig -AccountType $SourceDataDiskSku -Location $SourceVmObject.Location -CreateOption Copy -SourceResourceId $SourceDataDiskSnap.Id

    $TargetDataDisk = New-AzDisk -Disk $TargetDataDiskConfig -ResourceGroupName $SourceVmObject.ResourceGroupName -DiskName "$($vmNewName.ToLower())-$($SourceDataDisk.lun)-vhd"

    Add-AzVMDataDisk -VM $NewVmObject -Name "$($vmNewName.ToLower())-$($SourceDataDisk.lun)-vhd" -ManagedDiskId $TargetDataDisk.Id -Lun $SourceDataDisk.lun -CreateOption "Attach"
}

Write-Host "Creating..."
New-AzVM -VM $NewVmObject -ResourceGroupName $SourceVmObject.ResourceGroupName -Location $SourceVmObject.Location
Write-Host "VM Created..."
</code>```

Body:
Credit to Oliver Miossec for this non-destructive azure powershell script that creates a new VM, with some changes for parameters. You can find his post here. It's extra awesome because it'll also fix badly-named discs and NICs associated with the machine.

#Deletes and recreates a VM
param (
    [Parameter(Mandatory=$true)]
    [string]$vmOldName,
    [Parameter(Mandatory=$true)]
    [string]$vmNewName,
    [Parameter(Mandatory=$true)]
    [string]$rgName,
    [string]$newLocation #Optional, moves the VM to a new Geographic Location
)

$ErrorActionPreference = "Stop"

Write-Host "Get and Shutdown old VM, Create new config"
$SourceVmObject = get-azvm -Name $vmOldName -ResourceGroupName $rgName

if ([string]::IsNullOrEmpty($newLocation)) {
    $newLocation = $SourceVmObject.Location
    Write-Host "No new location specified, using the current VM's existing location: $newLocation"
}

$SourceVmPowerStatus = (get-azvm -Name $SourceVmObject.Name -ResourceGroupName $SourceVmObject.ResourceGroupName -Status).Statuses | where-object code -like "PowerState*"

if ($SourceVmPowerStatus -ne "VM deallocated") {
    stop-azVm -Name $SourceVmObject.Name -ResourceGroupName $SourceVmObject.ResourceGroupName -Force
    Start-Sleep -Seconds 30 #Wait to ensure VM is shutdown.
}

$NewVmObject = New-AzVMConfig -VMName $vmNewName -VMSize $SourceVmObject.HardwareProfile.VmSize

Write-Host "Create new Network Objects"
$subnetID = (Get-AzNetworkInterface -ResourceId $SourceVmObject.NetworkProfile.NetworkInterfaces[0].id).IpConfigurations.Subnet.id

$nic = New-AzNetworkInterface -Name "$($vmNewName.ToLower())-0-nic" -ResourceGroupName $SourceVmObject.ResourceGroupName  -Location $SourceVmObject.Location -SubnetId $SubnetId

Add-AzVMNetworkInterface -VM $NewVmObject -Id $nic.Id

Write-Host "Move OS Disk"
$SourceOsDiskSku = (get-azdisk -ResourceGroupName $SourceVmObject.ResourceGroupName -DiskName $SourceVmObject.StorageProfile.OsDisk.name).Sku.Name

$SourceOsDiskSnapConfig =  New-AzSnapshotConfig  -SourceUri $SourceVmObject.StorageProfile.OsDisk.ManagedDisk.Id -Location $SourceVmObject.Location -CreateOption copy

$SourceOsDiskSnap = New-AzSnapshot -Snapshot $SourceOsDiskSnapConfig  -SnapshotName "$($SourceVmObject.Name)-os-snap"  -ResourceGroupName $SourceVmObject.ResourceGroupName

$TargetOsDiskConfig = New-AzDiskConfig -AccountType $SourceOsDiskSku -Location $SourceVmObject.Location -CreateOption Copy -SourceResourceId $SourceOsDiskSnap.Id

$TargetOsDisk = New-AzDisk -Disk $TargetOsDiskConfig -ResourceGroupName $SourceVmObject.ResourceGroupName -DiskName "$($vmNewName.ToLower())-os-vhd"

Set-AzVMOSDisk -VM $NewVmObject -ManagedDiskId $TargetOsDisk.Id -CreateOption Attach -Windows

Write-Host "Create new Data Disks"
Foreach ($SourceDataDisk in $SourceVmObject.StorageProfile.DataDisks) {

    $SourceDataDiskSku = (get-azdisk -ResourceGroupName $SourceVmObject.ResourceGroupName -DiskName $SourceDataDisk.name).Sku.Name

    $SourceDataDiskSnapConfig =  New-AzSnapshotConfig  -SourceUri $SourceDataDisk.ManagedDisk.Id -Location $SourceVmObject.Location -CreateOption copy

    $SourceDataDiskSnap = New-AzSnapshot -Snapshot $SourceDataDiskSnapConfig  -SnapshotName "$($SourceVmObject.Name)-$($SourceDataDisk.name)-snap"  -ResourceGroupName $SourceVmObject.ResourceGroupName

    $TargetDataDiskConfig = New-AzDiskConfig -AccountType $SourceDataDiskSku -Location $SourceVmObject.Location -CreateOption Copy -SourceResourceId $SourceDataDiskSnap.Id

    $TargetDataDisk = New-AzDisk -Disk $TargetDataDiskConfig -ResourceGroupName $SourceVmObject.ResourceGroupName -DiskName "$($vmNewName.ToLower())-$($SourceDataDisk.lun)-vhd"

    Add-AzVMDataDisk -VM $NewVmObject -Name "$($vmNewName.ToLower())-$($SourceDataDisk.lun)-vhd" -ManagedDiskId $TargetDataDisk.Id -Lun $SourceDataDisk.lun -CreateOption "Attach"
}

Write-Host "Creating..."
New-AzVM -VM $NewVmObject -ResourceGroupName $SourceVmObject.ResourceGroupName -Location $SourceVmObject.Location
Write-Host "VM Created..."


问:
How should I use try-with-resources with JDBC?
I have a method for getting users from a database with JDBC:

```<code>public List<User> getUser(int userId) {
    String sql = "SELECT id, name FROM users WHERE id = ?";
    List<User> users = new ArrayList<User>();
    try {
        Connection con = DriverManager.getConnection(myConnectionURL);
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setInt(1, userId);
        ResultSet rs = ps.executeQuery();
        while(rs.next()) {
            users.add(new User(rs.getInt("id"), rs.getString("name")));
        }
        rs.close();
        ps.close();
        con.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return users;
}
</code>```

How should I use Java 7 try-with-resources to improve this code?

I have tried with the code below, but it uses many try blocks, and doesn't improve the readability much. Should I use try-with-resources in another way?

```<code>public List<User> getUser(int userId) {
    String sql = "SELECT id, name FROM users WHERE id = ?";
    List<User> users = new ArrayList<>();
    try {
        try (Connection con = DriverManager.getConnection(myConnectionURL);
             PreparedStatement ps = con.prepareStatement(sql);) {
            ps.setInt(1, userId);
            try (ResultSet rs = ps.executeQuery();) {
                while(rs.next()) {
                    users.add(new User(rs.getInt("id"), rs.getString("name")));
                }
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return users;
}
</code>```

答:
As others have stated, your code is basically correct though the outer try is unneeded. Here are a few more thoughts.

DataSource

Other answers here are correct and good, such the accepted Answer by bpgergo. But none of them show the use of DataSource, commonly recommended over use of DriverManager in modern Java.

So for the sake of completeness, here is a complete example that fetches the current date from the database server. The database used here is Postgres. Any other database would work similarly. You would replace the use of org.postgresql.ds.PGSimpleDataSource with an implementation of DataSource appropriate to your database. An implementation is likely provided by your particular driver, or connection pool if you go that route.

A DataSource implementation need not be closed, because it is never “opened”. A DataSource is not a resource, is not connected to the database, so it is not holding networking connections nor resources on the database server. A DataSource is simply information needed when making a connection to the database, with the database server's network name or address, the user name, user password, and various options you want specified when a connection is eventually made. So your DataSource implementation object does not go inside your try-with-resources parentheses.

The purpose of DataSource is to externalize your database connection information. If you hard-code username, password, and such within your your source code, then a change to your database server configuration means having to recompile and redeploy your code — not fun. Instead, such database configuration details should be stored outside your source code, then retrieved at runtime. You can retrieve the configuration details via JNDI from a naming and directory server such as LDAP. Or you might retrieve from the Servlet container or Jakarta EE server running your app.

Nested try-with-resources

Your code makes proper use of nested try-with-resources statements.

Notice in the example code below that we also use the try-with-resources syntax twice, one nested inside the other. The outer try defines two resources: Connection and PreparedStatement. The inner try defines the ResultSet resource. This is a common code structure.

If an exception is thrown from the inner one, and not caught there, the ResultSet resource will automatically be closed (if it exists, is not null). Following that, the PreparedStatement will be closed, and lastly the Connection is closed. Resources are automatically closed in reverse order in which they were declared within the try-with-resource statements.

The example code here is overly simplistic. As written, it could be executed with a single try-with-resources statement. But in a real work you will likely be doing more work between the nested pair of try calls. For example, you may be extracting values from your user-interface or a POJO, and then passing those to fulfill ? placeholders within your SQL via calls to PreparedStatement::set… methods.

Syntax notes

Trailing semicolon

Notice that the semicolon trailing the last resource statement within the parentheses of the try-with-resources is optional. I include it in my own work for two reasons: Consistency and it looks complete, and it makes copy-pasting a mix of lines easier without having to worry about end-of-line semicolons. Your IDE may flag the last semicolon as superfluous, but there is no harm in leaving it.

Java 9 – Use existing vars in try-with-resources

New in Java 9 is an enhancement to try-with-resources syntax. We can now declare and populate the resources outside the parentheses of the try statement. I have not yet found this useful for JDBC resources, but keep it in mind in your own work.

ResultSet should close itself, but may not

In an ideal world the ResultSet would close itself as the documentation promises:

A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.

Unfortunately, in the past some JDBC drivers infamously failed to fulfill this promise. As a result, many JDBC programmers learned to explicitly close all their JDBC resources including Connection, PreparedStatement, and ResultSet too. The modern try-with-resources syntax has made doing so easier, and with more compact code. Notice that the Java team went to the bother of marking ResultSet as AutoCloseable, and I suggest we make use of that. Using a try-with-resources around all your JDBC resources makes your code more self-documenting as to your intentions.

Code example

package work.basil.example;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.Objects;

public class App
{
    public static void main ( String[] args )
    {
        App app = new App();
        app.doIt();
    }

    private void doIt ( )
    {
        System.out.println( "Hello World!" );

        org.postgresql.ds.PGSimpleDataSource dataSource = new org.postgresql.ds.PGSimpleDataSource();

        dataSource.setServerName( "1.2.3.4" );
        dataSource.setPortNumber( 5432 );

        dataSource.setDatabaseName( "example_db_" );
        dataSource.setUser( "scott" );
        dataSource.setPassword( "tiger" );

        dataSource.setApplicationName( "ExampleApp" );

        System.out.println( "INFO - Attempting to connect to database: " );
        if ( Objects.nonNull( dataSource ) )
        {
            String sql = "SELECT CURRENT_DATE ;";
            try (
                    Connection conn = dataSource.getConnection() ;
                    PreparedStatement ps = conn.prepareStatement( sql ) ;
            )
            {
                … make `PreparedStatement::set…` calls here.
                try (
                        ResultSet rs = ps.executeQuery() ;
                )
                {
                    if ( rs.next() )
                    {
                        LocalDate ld = rs.getObject( 1 , LocalDate.class );
                        System.out.println( "INFO - date is " + ld );
                    }
                }
            }
            catch ( SQLException e )
            {
                e.printStackTrace();
            }
        }

        System.out.println( "INFO - all done." );
    }
}
```

Body:
I have a method for getting users from a database with JDBC:

public List<User> getUser(int userId) {
    String sql = "SELECT id, name FROM users WHERE id = ?";
    List<User> users = new ArrayList<User>();
    try {
        Connection con = DriverManager.getConnection(myConnectionURL);
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setInt(1, userId);
        ResultSet rs = ps.executeQuery();
        while(rs.next()) {
            users.add(new User(rs.getInt("id"), rs.getString("name")));
        }
        rs.close();
        ps.close();
        con.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return users;
}

How should I use Java 7 try-with-resources to improve this code?

I have tried with the code below, but it uses many try blocks, and doesn't improve the readability much. Should I use try-with-resources in another way?

public List<User> getUser(int userId) {
    String sql = "SELECT id, name FROM users WHERE id = ?";
    List<User> users = new ArrayList<>();
    try {
        try (Connection con = DriverManager.getConnection(myConnectionURL);
             PreparedStatement ps = con.prepareStatement(sql);) {
            ps.setInt(1, userId);
            try (ResultSet rs = ps.executeQuery();) {
                while(rs.next()) {
                    users.add(new User(rs.getInt("id"), rs.getString("name")));
                }
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return users;
}


问:
Not able to figure out the logical error in C program
A program that prints its input one word per line.

```<code>int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}
</code>```

The above program prints the result correctly, one word per line. After changing the condition accordingly, I was expecting the program below to also print one word per line. However I am not getting the correct result. Am I making some silly mistake or is something wrong?

```<code>int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}
</code>```

答: You could do what MByD said, or you could change your or's (||) to and's (&&).</p>

Body:
A program that prints its input one word per line.

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}

The above program prints the result correctly, one word per line. After changing the condition accordingly, I was expecting the program below to also print one word per line. However I am not getting the correct result. Am I making some silly mistake or is something wrong?

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}


问:
How to call a Javascript Function which is nested inside a forEach loop
I'm trying to modify a plugin for adding input tags which is available here

I've written a dumbed down version of my issue below. The pluggin searches the page for any HTML with the class 'tags-input' and creates a bunch of functions for each one found to add and remove tags.
The pluggin triggers the addTag() function whenever a keydown event is detected.

```<code>[].forEach.call(document.getElementsByClassName('tags-input'), function (el) {
  function addTag(str){
    //code here adds a tag with a certain string "str"
  }
});

addTag("some string"); //function not found!
</code>```

I want to be able to call the addTag() function from outside the forEach loop when a link from a live search is selected.

I've tried adding listeners within the loop, however, since the links from the live search are generated from a database after the page loads the listeners don't appear to pick them up.

How can I call the addTag() function from my live search?

Similar questions did not help with this specific issue:

Call javascript inside foreach loop - No Answer Given

call javascript function outside foreach loop - Different issue as far as I can tell

答:
Something Like This, No?

I understand what you're trying to do: But to make this simple I've used a List of String Values just to represent another possible approach:

//  Why not create a list of functions which correspond to each list item?
var doSomeThingFuncList = [];

["Yes","No","Maybe"].forEach(function (item) {
  // Assuming that we will create a function for each list item that must be called outside of the loop
  doSomeThingFuncList.push(
    () => {
      alert("Do Something");
    }
  );
});
// The functions we have defined inside the for-loop can now be called from outside the forEach loop through indexing the function list defined at the beginning

doSomeThingFuncList[0]();```

Basically, knowing what function to run what index of the array you'd be able to callback these functions through events on those buttons. But I am not sure what the scenario is behind this.

Body:
I'm trying to modify a plugin for adding input tags which is available here

I've written a dumbed down version of my issue below. The pluggin searches the page for any HTML with the class 'tags-input' and creates a bunch of functions for each one found to add and remove tags.
The pluggin triggers the addTag() function whenever a keydown event is detected.

[].forEach.call(document.getElementsByClassName('tags-input'), function (el) {
  function addTag(str){
    //code here adds a tag with a certain string "str"
  }
});

addTag("some string"); //function not found!

I want to be able to call the addTag() function from outside the forEach loop when a link from a live search is selected.

I've tried adding listeners within the loop, however, since the links from the live search are generated from a database after the page loads the listeners don't appear to pick them up.

How can I call the addTag() function from my live search?

Similar questions did not help with this specific issue:

Call javascript inside foreach loop - No Answer Given

call javascript function outside foreach loop - Different issue as far as I can tell

Body:
Something Like This, No?

I understand what you're trying to do: But to make this simple I've used a List of String Values just to represent another possible approach:

//  Why not create a list of functions which correspond to each list item?
var doSomeThingFuncList = [];

["Yes","No","Maybe"].forEach(function (item) {
  // Assuming that we will create a function for each list item that must be called outside of the loop
  doSomeThingFuncList.push(
    () => {
      alert("Do Something");
    }
  );
});
// The functions we have defined inside the for-loop can now be called from outside the forEach loop through indexing the function list defined at the beginning

doSomeThingFuncList[0]();

Basically, knowing what function to run what index of the array you'd be able to callback these functions through events on those buttons. But I am not sure what the scenario is behind this.


问:
Flutter html response not being recorded properly (Maybe Variable-Types? Issue?)
Okay, so this is a confusing one for me...  I HAVE the server-response, but different parts of my program don't seem to be communicating the information properly.

```<code>void setNumber(String password) async {
  info = await getHistory(password);
  Duration waitTimer = new Duration(seconds: 1);
  new Timer.periodic(waitTimer, (timer) async {
    print('Still checking');
    if (info != null) {
      timer.cancel();
      print('Done updating info.');
    }
  });
}
</code>```

And the server-call I'm using is as follows:

```<code>Future<List> getHistory(String password) async {
  List<dynamic> data2;
  Duration waitTimer = new Duration(seconds: 1);
  new Timer.periodic(waitTimer, (historyTimer) async {
    http.Response response = await
    http.post(
      //http response request data redacted for privacy reasons
    );
    if (response.body != null) {
      print('Testing');
      if (response.body != '[]') {
        historyTimer.cancel();
        print(response.body);
        return jsonDecode(response.body);
      } else {
        historyTimer.cancel();
        print('No Data');
        return new List();
      }
    }
  });
  print('Should NEVER print');
  return data2;
}
</code>```

Now in my Debug Console I receive the following:

```<code>flutter: Still checking
flutter: Testing
flutter: [<VERY large response from the server, with all the information I need>]
flutter: Still checking
flutter: Still checking
...
...
... <repeat>
</code>```

Meaning that for whatever reason, I AM receiving the information I need from the Server...  And it's NOT being sent appropriately to the other part of my program, and recorded.  Maybe there's a Variable-Types issue?  I know from flutter that what I'm being sent after the jsonDecode is a List as I tried to convert it to a Map and it told me you can't convert a List to a Map.  However, even when instantiating everything correctly as a List none of the information is staying inside the list object that is created.  Why?

答:
Maybe stick the info = await getHistory(password) declaration inside the async Timer.periodic function body? It's possible that the info variable is out of scope, and info != null never returns true.

I would debug by adding print(info) right above the info != null check if that does not fix it.  See below:

```<code>void setNumber(String password) async {
  Duration waitTimer = new Duration(seconds: 1);
  new Timer.periodic(waitTimer, (timer) async {

    // MOVED INFO DECLARATION
    List info = await getHistory(password);
    // ADDED PRINT
    print(info.toString());

    print('Still checking');
    if (info != null) {
      timer.cancel();
      print('Done updating info.');
    }
  });
}
</code>```

Body:
Okay, so this is a confusing one for me...  I HAVE the server-response, but different parts of my program don't seem to be communicating the information properly.

void setNumber(String password) async {
  info = await getHistory(password);
  Duration waitTimer = new Duration(seconds: 1);
  new Timer.periodic(waitTimer, (timer) async {
    print('Still checking');
    if (info != null) {
      timer.cancel();
      print('Done updating info.');
    }
  });
}

And the server-call I'm using is as follows:

Future<List> getHistory(String password) async {
  List<dynamic> data2;
  Duration waitTimer = new Duration(seconds: 1);
  new Timer.periodic(waitTimer, (historyTimer) async {
    http.Response response = await
    http.post(
      //http response request data redacted for privacy reasons
    );
    if (response.body != null) {
      print('Testing');
      if (response.body != '[]') {
        historyTimer.cancel();
        print(response.body);
        return jsonDecode(response.body);
      } else {
        historyTimer.cancel();
        print('No Data');
        return new List();
      }
    }
  });
  print('Should NEVER print');
  return data2;
}

Now in my Debug Console I receive the following:

flutter: Still checking
flutter: Testing
flutter: [<VERY large response from the server, with all the information I need>]
flutter: Still checking
flutter: Still checking
...
...
... <repeat>

Meaning that for whatever reason, I AM receiving the information I need from the Server...  And it's NOT being sent appropriately to the other part of my program, and recorded.  Maybe there's a Variable-Types issue?  I know from flutter that what I'm being sent after the jsonDecode is a List as I tried to convert it to a Map and it told me you can't convert a List to a Map.  However, even when instantiating everything correctly as a List none of the information is staying inside the list object that is created.  Why?

Body:
Maybe stick the info = await getHistory(password) declaration inside the async Timer.periodic function body? It's possible that the info variable is out of scope, and info != null never returns true.

I would debug by adding print(info) right above the info != null check if that does not fix it.  See below:

void setNumber(String password) async {
  Duration waitTimer = new Duration(seconds: 1);
  new Timer.periodic(waitTimer, (timer) async {

    // MOVED INFO DECLARATION
    List info = await getHistory(password);
    // ADDED PRINT
    print(info.toString());

    print('Still checking');
    if (info != null) {
      timer.cancel();
      print('Done updating info.');
    }
  });
}


问:
How can you display your logs when testing android apps on real devices?
So I am developing my first app with Android Studio, it's a Shopping app and everything seems to work just fine when I try it out on the built-in Emulator (Android 9). However, when I connect my Smartphone (same Android version), I won't get pass my Login screen. Currently the data is stored through SQLite, which may cause issues.
I'd really like to look up what's the exact problem, but there is no Log feed showing up in Android Studios.

Are there any settings that provide the same Logs as if I was running it on an Emulator?

答: If I'm understanding correctly, you would want to use logcat?You can debug phone issues in it also, just select your phone in the options. I have two external phones I test on, logcat shows those phones.


问:
I cant install Flask
I am trying to install flask but everytime i get this error
ModuleNotFoundError: No module named 'flask'. I have added python to path and have even reinstalled it but it just isnt working. I followed steps of activating virtual environment and using pip install flask but it still doesn't seem to work. I need to get my a level coursework completed in a week! Please help.

答:
To check if you have actually installed flask, try this command:pip freeze then check if it is actually listed.
Normal procedure to start a flask app would be:
- create a virtual environment.Make sure you are using python 3. check by using this command. python --version. It should print out the latest version.
- Install Flask. For good measure you could use pip3 to make sure you are using python3.

```<code>pip3 install Flask
</code>```

- Run your app.

Title: I cant install Flask

Body:
To check if you have actually installed flask, try this command:pip freeze then check if it is actually listed.
Normal procedure to start a flask app would be:
- create a virtual environment.Make sure you are using python 3. check by using this command. python --version. It should print out the latest version.
- Install Flask. For good measure you could use pip3 to make sure you are using python3.

pip3 install Flask

- Run your app.


问:
Scraping multiple div classes with the same name using Beautiful Soup in Python
I have succesfully scraped the image and title of a webpage (URL in code). I want to do this for all movies that are on this page. 'movie_list' contains all of this, but only the first movie information is scraped.

I tried changing .find to .find_all but this gives me an error.

url = 'https://5movies.to/movie/'
content = session.get(url, verify=False).content
soup = BeautifulSoup(content, "html.parser")
movie_list = soup.find_all('div', {'class': 'movie-list'})
all_item = []

for allContainers in movie_list:
    filmName = allContainers.find('img').get('alt')
    filmFoto = allContainers.find('img').get('src')
    filmLink = allContainers.find('a').get('href')
print(filmName)
```

答:
Moving the print statement inside of the for loop made it print out the whole list.
Indeed I replaced the print with all_item.append((filmName, filmFoto, filmLink)) to send it to my frontend.

Acknowledgements to @furas for the information!

url = 'https://5movies.to/movie/'
content = session.get(url, verify=False).content
soup = BeautifulSoup(content, "html.parser")
movie_list = soup.find_all('div', {'class': 'movie-list'})
all_item = []

for allContainers in movie_list:
    filmName = allContainers.find('img').get('alt')
    filmFoto = allContainers.find('img').get('src')
    filmLink = allContainers.find('a').get('href')
    print(filmName)
```


问:
Finding element in Selenium + Python with repeating classes
I'm using Selenium + Python to scrape match results on a Battlefy page for later manipulation and entering into a database. I'm trying to scrape the names of the teams and the results using Selenium because the dynamically loading JS requires me to use a headless browser. However, I'm trying to get the text of each college using the class name, but using Selenium's find_elements_by_class_name method doesn't seem to be working.

Web page: https://battlefy.com/college-league-of-legends/2020-north-conference/5de98dd4196d1311d9e6edbd/stage/5e23b6e395e72856dac06997/bracket/1

Current code:

```<code>>>> chrome_path = r"C:\Users\...\chromedriver.exe"
>>> driver = webdriver.Chrome(chrome_path)
>>> driver.get("https://battlefy.com/college-league-of-legends/2020-north-conference/5de98dd4196d1311d9e6edbd/stage/5e23b6e395e72856dac06997/bracket/1")
>>> team = driver.find_elements_by_class_name("team-name overflow-ellipsis float-right")
>>> for item in teams:
    print(item.text)
</code>```

Which does not print anything and returns an empty array. I must be doing something incorrectly. How can I scrape each team name's text when it's covered by a class name?

答:
team-name overflow-ellipsis float-right is combination of classes and when you use find_elements_by_class_name/find_element_by_class_name method, the locator will be converted to CSS internally but selenium library. Hence you have to mask all the spaces (white spaces) with ..

Try with below.

```<code>team = driver.find_elements_by_class_name("team-name.overflow-ellipsis.float-right")
</code>```

Edit 1:

Here is the selenium implementation, where we can see the locator is pre-pended with . and it uses By.CSS_SELECTOR internally. So, we don't have to add . for the first class name.

Body:
I'm using Selenium + Python to scrape match results on a Battlefy page for later manipulation and entering into a database. I'm trying to scrape the names of the teams and the results using Selenium because the dynamically loading JS requires me to use a headless browser. However, I'm trying to get the text of each college using the class name, but using Selenium's find_elements_by_class_name method doesn't seem to be working.

Web page: https://battlefy.com/college-league-of-legends/2020-north-conference/5de98dd4196d1311d9e6edbd/stage/5e23b6e395e72856dac06997/bracket/1

Current code:

>>> chrome_path = r"C:\Users\...\chromedriver.exe"
>>> driver = webdriver.Chrome(chrome_path)
>>> driver.get("https://battlefy.com/college-league-of-legends/2020-north-conference/5de98dd4196d1311d9e6edbd/stage/5e23b6e395e72856dac06997/bracket/1")
>>> team = driver.find_elements_by_class_name("team-name overflow-ellipsis float-right")
>>> for item in teams:
    print(item.text)

Which does not print anything and returns an empty array. I must be doing something incorrectly. How can I scrape each team name's text when it's covered by a class name?

Body:
team-name overflow-ellipsis float-right is combination of classes and when you use find_elements_by_class_name/find_element_by_class_name method, the locator will be converted to CSS internally but selenium library. Hence you have to mask all the spaces (white spaces) with ..

Try with below.

team = driver.find_elements_by_class_name("team-name.overflow-ellipsis.float-right")

Edit 1:

Here is the selenium implementation, where we can see the locator is pre-pended with . and it uses By.CSS_SELECTOR internally. So, we don't have to add . for the first class name.


问:
Crash when allocating and reallocating memory
I'm trying to split a list of ids by a comma and then concatenate each ID to a string but my code isn't working. I think I need to allocate memory dynamically because I have no way of knowing how much buffer space I will need... The program should be able to concatenate hundreds or even thousands of different ids to "tmp" or maybe just a couple. It's up to the user really. I need to be able to increase the size of tmp as needed but I noticed the program crashes if I put too many ids in id_list. What am I doing wrong?</p>

```<code>size_t size = 512;
char *tmp = malloc(512);

char download_item[100];
snprintf(download_item, 100, "+download_item_id %s ", pch);

if (tmp = realloc(tmp, size += strlen(download_item)) == NULL)
    return;

strcat(tmp, download_item);
</code>```

答:
This line is not doing what you expect:

```<code>    if (tmp = realloc(tmp, size += strlen(download_item)) == NULL)
</code>```

== has higher precedence than =, so it's assigning the result of the comparison to tmp, not assigning the result of realloc(). Add parentheses.

```<code>    if ((tmp = realloc(tmp, size += strlen(download_item))) == NULL)
</code>```

Body:
I'm trying to split a list of ids by a comma and then concatenate each ID to a string but my code isn't working. I think I need to allocate memory dynamically because I have no way of knowing how much buffer space I will need... The program should be able to concatenate hundreds or even thousands of different ids to "tmp" or maybe just a couple. It's up to the user really. I need to be able to increase the size of tmp as needed but I noticed the program crashes if I put too many ids in id_list. What am I doing wrong?

size_t size = 512;
char *tmp = malloc(512);

char download_item[100];
snprintf(download_item, 100, "+download_item_id %s ", pch);

if (tmp = realloc(tmp, size += strlen(download_item)) == NULL)
    return;

strcat(tmp, download_item);

Body:
This line is not doing what you expect:

    if (tmp = realloc(tmp, size += strlen(download_item)) == NULL)

== has higher precedence than =, so it's assigning the result of the comparison to tmp, not assigning the result of realloc(). Add parentheses.

    if ((tmp = realloc(tmp, size += strlen(download_item))) == NULL)


问:
How to make dropdownlist from the DataTable not outside your table?
I have dropdownlist but its outside my DataTable and needs to be inside, but i am struggling to achieve this and see my code below for logic. Please help me to improve this logic for user readability. The reason for this logic that i want my dropdownlist it should allow user the option to select from the given data not data being exposed outside this record list, i hope i am making sense as exactly to what i am aiming to achieve.

```<code> // Drop downlist for WhoAttended.

    public enum Attendees
    {
        Engineers,
        Technicians,
        Inspectors
    }

// View cshtml

<link href="//cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.6/semantic.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.15/css/dataTables.semanticui.min.css" rel="stylesheet" />

@section scripts{

      <script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.semanticui.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.6/semantic.min.js"></script>

    <script>

        $(document).ready(function () {

            $("#EventsManagementsTable").DataTable({

                "columnDefs": [
                { "width": "5%", "targets": [0] },
                { "className": "text-center custom-middle-align" ,"targets":[0, 1, 2, 3, 4, 5, 6] },
                ],

                "serverSide": "true",
                "order":[0,"asc"],
                "processing": "true",
                "language": {
                    "processing": "processing...... please wait"
                },
                "ajax": {
                    "url": "/Dashboard/GetData",
                    "type": "POST",
                    "datatype": "JSON"

                },
                "columns": [
                    {"data": "TrainingType", "name": "TrainingType"},
                    { "data": "TrainingDescription", "name": "TrainingDescription"},
                    { "data": "Price", "name": "Price"},
                    { "data": "Venue", "name": "Venue"},
                    { "data": "Facilitator", "name":"Facilitator" },
                    { "data": "WhoAttend", "name" : "WhoAttend" },
                    {"data": "RSVP", "name":"RSVP" },
                ]

            });

        });

    </script>
</code>```

// What i am doing currently to get dropdownlist on DataTable.

```<code> <script>

        $(document).ready(function () {

            $("#EventsManagementsTable").DataTable({

                "columnDefs": [
                { "width": "5%", "targets": [0] },
                { "className": "text-center custom-middle-align" ,"targets":[0, 1, 2, 3, 4, 5, 6] },
                ],

                "serverSide": "true",
                "order":[0,"asc"],
                "processing": "true",
                "language": {
                    "processing": "processing...... please wait"
                },
                "ajax": {
                    "url": "/Dashboard/GetData",
                    "type": "POST",
                    "datatype": "JSON",

                },

                "columns": [
                    {"data": "TrainingType", "name": "TrainingType"},
                    { "data": "TrainingDescription", "name": "TrainingDescription"},
                    { "data": "Price", "name": "Price"},
                    { "data": "Venue", "name": "Venue"},
                    { "data": "Facilitator", "name":"Facilitator" },
                    { "data": "WhoAttend", "name" : "WhoAttend" },
                    { "data": "RSVP", "name": "RSVP" },

                    "columns":[
                    {

                        "data": "WhoAttend",
                        "name": "WhoAttend",
                        "render": function (value) {
                            return $("<select/>")
                                .addClass("form-control")
                                .attr("name", "WhoAttend")
                                .append($("<option/>").text("Engineers"))
                                .append($("<option/>").text("Inspectors"))
                                .append($("<option/>").text("Technicians"))
                                .val(value)
                                .html();
                        }

                    }

                ],

                ]

            });

        });
</code>```

答:
Hi in your columns section add this code to add a custom HTML element:

```<code>"columns": [
                {"data": "TrainingType", "name": "TrainingType"},
                { "data": "TrainingDescription", "name": "TrainingDescription"},
                { "data": "Price", "name": "Price"},
                { "data": "Venue", "name": "Venue"},
                { "data": "Facilitator", "name":"Facilitator" },
                { "data": "WhoAttend", "name" : "WhoAttend" },
                {"data": "RSVP", "name":"RSVP" }
                   {
                className: "center",
                defaultContent:`<select name='slcCustom' class='custom' >
                  <option value='default'>select something</option>
                  <option value='1'>Apple</option>
                  </select>`
              }
               ]
</code>```

Here is a jsfiddle you can check.

Hope it helps

Body:
I have dropdownlist but its outside my DataTable and needs to be inside, but i am struggling to achieve this and see my code below for logic. Please help me to improve this logic for user readability. The reason for this logic that i want my dropdownlist it should allow user the option to select from the given data not data being exposed outside this record list, i hope i am making sense as exactly to what i am aiming to achieve.

 // Drop downlist for WhoAttended.

    public enum Attendees
    {
        Engineers,
        Technicians,
        Inspectors
    }

// View cshtml

<link href="//cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.6/semantic.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.15/css/dataTables.semanticui.min.css" rel="stylesheet" />

@section scripts{

// What i am doing currently to get dropdownlist on DataTable.

Body:
Hi in your columns section add this code to add a custom HTML element:

"columns": [
                {"data": "TrainingType", "name": "TrainingType"},
                { "data": "TrainingDescription", "name": "TrainingDescription"},
                { "data": "Price", "name": "Price"},
                { "data": "Venue", "name": "Venue"},
                { "data": "Facilitator", "name":"Facilitator" },
                { "data": "WhoAttend", "name" : "WhoAttend" },
                {"data": "RSVP", "name":"RSVP" }
                   {
                className: "center",
                defaultContent:`<select name='slcCustom' class='custom' >
                  <option value='default'>select something</option>
                  <option value='1'>Apple</option>
                  </select>`
              }
               ]

Here is a jsfiddle you can check.

Hope it helps


问:
close position after 'x' days
i've this basic strategy on pinescript that enter a position based on the crossover of 2 moving averages. what i would do is this:
when the cross occurs enter a long/short (weather on is a bull or bear cross)
exit the position 3 candles later.
i've tried with the function 'barssince' but i'm not very good at coding.
this is my strategy:</p>

```<code>strategy("MovingAvg2Line Cross", overlay=true, initial_capital=10000)
fastLength = input(50)
slowLength = input(200)
price = close

mafast = sma(price, fastLength)
maslow = sma(price, slowLength)

if (crossover(mafast, maslow))
    strategy.entry("MA2CrossLE", strategy.long, comment="MA2CrossLE")

if (crossunder(mafast, maslow))
    strategy.entry("MA2CrossSE", strategy.short, comment="MA2CrossSE") ```
</code>```

答:
Add this at the end. It detects changes in the number of open trades and counts bars from then:</p>

```<code>strategy.close_all(when = barssince(change(strategy.opentrades)) == 2)
</code>```

Title: close position after 'x' days

Body:
i've this basic strategy on pinescript that enter a position based on the crossover of 2 moving averages. what i would do is this:
when the cross occurs enter a long/short (weather on is a bull or bear cross)
exit the position 3 candles later.
i've tried with the function 'barssince' but i'm not very good at coding.
this is my strategy:

strategy("MovingAvg2Line Cross", overlay=true, initial_capital=10000)
fastLength = input(50)
slowLength = input(200)
price = close

mafast = sma(price, fastLength)
maslow = sma(price, slowLength)

if (crossover(mafast, maslow))
    strategy.entry("MA2CrossLE", strategy.long, comment="MA2CrossLE")

if (crossunder(mafast, maslow))
    strategy.entry("MA2CrossSE", strategy.short, comment="MA2CrossSE") ```

Body:
Add this at the end. It detects changes in the number of open trades and counts bars from then:

strategy.close_all(when = barssince(change(strategy.opentrades)) == 2)


问:
How to limit hour in Date Range Picker JQuery Plugin
I am using Date Range Picker JQuery plugin and i can't limit the hour. I want to user can select 8 AM to 5 PM.

My Code:

```<code>$('input[name="date"]').daterangepicker({
    singleDatePicker: true,
    showDropdowns: true,
    timePicker: true,
    timePicker24Hour: true,
    timePickerIncrement: 30,
    "locale": {
        "format": "YYYY-MM-DD hh:mm",
        "applyLabel": "Onayla",
        "cancelLabel": "İptal",
        "weekLabel": "H",
        "daysOfWeek": [
            "Pa",
            "Pt",
            "Sa",
            "Ça",
            "Pe",
            "Cu",
            "Ct"
        ],
        "monthNames": [
            "Ocak",
            "Şubat",
            "Mart",
            "Nisan",
            "Mayıs",
            "Haziran",
            "Temmuz",
            "Ağustos",
            "Eylül",
            "Ekim",
            "Kasım",
            "Aralık"
        ],
        "firstDay": 1
    },
    minDate: moment().startOf('day').add(1,'day'),
    maxDate: moment().startOf('month').add(6,'month'),
    startDate: moment().startOf('day').add(1,'day'),
    MinTime: moment().hour(0).add(8)
});
</code>```

I solve this problem with this code:

```<code>$('input[name="date"]').on('apply.daterangepicker', function(ev, picker) {
    if(picker.startDate.hour() > 17 || picker.startDate.hour() < 8){
        $('input[name="date"]').data('daterangepicker').setStartDate(picker.startDate.hour(0).add(8,'hour'));
        //ev.preventDefault();
    }
});
</code>```

But i don't want to show them 0 to 24 hours. Just 8 to 17.

Edit: I used that code but didn't change anything.

```<code>hourMin: 8,
hourMax: 16,
</code>```

答:
It seems that the library does not allow natively what you want to achieve. It would be nice to have minHour and maxHour (as you suggest).

What you can do to trick the user is to hide with CSS the hours you do not want him to choose:

```<code>// This will hide the first 8 items so that 8 hours is the first option shown.
.hourselect option:nth-child(-n+8) {
    display: none;
}
// This will hide the hours from 18 onwards.
.hourselect option:nth-child(n+19) {
    display: none;
}
</code>```

With this you are hiding the unwanted hours. The problem is the first time you open the range picker you see 0 as the selected hour. To correct this you can set your startDate so that it starts from 8:

```<code>startDate: moment().startOf('day').add(1,'day').add(8, 'hours'),
</code>```

Another solution based on JavaScript is to remove the undesired hours when the user opens the range picker:

```<code>$('input[name="daterange"]').on('show.daterangepicker', function(ev, picker) {
    var $hours = picker.container.find('.hourselect').children();

    $hours.filter(':gt(17)').remove();
    $hours.filter(':lt(8)').remove();
});
</code>```

Body:
I am using Date Range Picker JQuery plugin and i can't limit the hour. I want to user can select 8 AM to 5 PM.

My Code:

$('input[name="date"]').daterangepicker({
    singleDatePicker: true,
    showDropdowns: true,
    timePicker: true,
    timePicker24Hour: true,
    timePickerIncrement: 30,
    "locale": {
        "format": "YYYY-MM-DD hh:mm",
        "applyLabel": "Onayla",
        "cancelLabel": "İptal",
        "weekLabel": "H",
        "daysOfWeek": [
            "Pa",
            "Pt",
            "Sa",
            "Ça",
            "Pe",
            "Cu",
            "Ct"
        ],
        "monthNames": [
            "Ocak",
            "Şubat",
            "Mart",
            "Nisan",
            "Mayıs",
            "Haziran",
            "Temmuz",
            "Ağustos",
            "Eylül",
            "Ekim",
            "Kasım",
            "Aralık"
        ],
        "firstDay": 1
    },
    minDate: moment().startOf('day').add(1,'day'),
    maxDate: moment().startOf('month').add(6,'month'),
    startDate: moment().startOf('day').add(1,'day'),
    MinTime: moment().hour(0).add(8)
});

I solve this problem with this code:

$('input[name="date"]').on('apply.daterangepicker', function(ev, picker) {
    if(picker.startDate.hour() > 17 || picker.startDate.hour() < 8){
        $('input[name="date"]').data('daterangepicker').setStartDate(picker.startDate.hour(0).add(8,'hour'));
        //ev.preventDefault();
    }
});

But i don't want to show them 0 to 24 hours. Just 8 to 17.

Edit: I used that code but didn't change anything.

hourMin: 8,
hourMax: 16,

Body:
It seems that the library does not allow natively what you want to achieve. It would be nice to have minHour and maxHour (as you suggest).

What you can do to trick the user is to hide with CSS the hours you do not want him to choose:

// This will hide the first 8 items so that 8 hours is the first option shown.
.hourselect option:nth-child(-n+8) {
    display: none;
}
// This will hide the hours from 18 onwards.
.hourselect option:nth-child(n+19) {
    display: none;
}

With this you are hiding the unwanted hours. The problem is the first time you open the range picker you see 0 as the selected hour. To correct this you can set your startDate so that it starts from 8:

startDate: moment().startOf('day').add(1,'day').add(8, 'hours'),

Another solution based on JavaScript is to remove the undesired hours when the user opens the range picker:

$('input[name="daterange"]').on('show.daterangepicker', function(ev, picker) {
    var $hours = picker.container.find('.hourselect').children();

    $hours.filter(':gt(17)').remove();
    $hours.filter(':lt(8)').remove();
});


问:
Groovy object's method invokeMethod in Jenkins sandbox mode
I am trying to implement decorator pattern in my jenkins shared library.
I want to decorate 'timeout-try-catch' block, so whenever some method of some class invoked (decorator doesnt care what class is that and what method is that), it automatically being wrapped in timeout-try-catch block.
But for that, I need to override method 'invokeMethod' in decorator class. Here is the smallest piece of code in Jenkinsfile that causes error:

```<code>node {
    sh 'echo "the content"'
    new MyClass().doSomething() // output: doSomething
}

class MyClass {
    def invokeMethod(String name, args) {
        println name
    }
}
</code>```

And I get following error:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method groovy.lang.GroovyObject invokeMethod java.lang.String java.lang.Object (MyClass doSomething)

Is that any way to override invokeMethod or implement dynamic decorator pattern (which doesnt cares about decorating class and it's methods) without exiting Jenkins's 'sandbox' mode?

答:
Assuming you have admin access, you could go and specifically approve the use of that method (see https://stackoverflow.com/a/56023403/107331 ), though be aware that if you have non-admin users submitting jobs on your Jenkins instance that method can be a dangerous one to simply approve.

Another option is to approve each script that uses this decorator.

Body:
I am trying to implement decorator pattern in my jenkins shared library.
I want to decorate 'timeout-try-catch' block, so whenever some method of some class invoked (decorator doesnt care what class is that and what method is that), it automatically being wrapped in timeout-try-catch block.
But for that, I need to override method 'invokeMethod' in decorator class. Here is the smallest piece of code in Jenkinsfile that causes error:

node {
    sh 'echo "the content"'
    new MyClass().doSomething() // output: doSomething
}

class MyClass {
    def invokeMethod(String name, args) {
        println name
    }
}

And I get following error:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method groovy.lang.GroovyObject invokeMethod java.lang.String java.lang.Object (MyClass doSomething)

Is that any way to override invokeMethod or implement dynamic decorator pattern (which doesnt cares about decorating class and it's methods) without exiting Jenkins's 'sandbox' mode?


问:
SQL query that displays the current date and count of days between two specific dates
I am trying to write a SQL query that shows the count of the days and date depending upon the financial period it falls in. The financial period starts 5 days before the month end eg march 27th to 26th April

For the above mentioned period if the day is 29th march, the count of the day should be 3 and the date should be 2020-04. The date should adjust depending upon the period it falls in.

I tried to adress the second part of this query by writing the below script but it does not bring any result

```<code>declare @date datetime
set @date = getdate()
SELECT format (date,'yyyy-MM-dd') as date

where @date

between dateadd(day,-5,EOMONTH(getdate(),-1)) and dateadd(day,-5,EOMONTH(getdate()))
</code>```

答:
updated to include 5 days from previous month.

Is this what you are looking for the second part?

Edit: Modifying the query. I guess this should give you what you need for both the parts.
you can try changing the dates in set @date.

Please note that the -4 instead of -5 is done intentionally as you said the financial month starts 5 days earlier. For March, 31 - 5 would give 26, but it should start on 27 right?  so that on 29th the no. of days should be 3 including 27 and 29. Anyways, the query should be self explanatory, might just need to change the number depending on your requirement.

```<code>declare @date datetime
--set @date = getdate()
set @date = '2020-02-14'

SELECT format(@date,'yyyy-MM-dd') as date,
case WHEN @date < dateadd(day,-4,EOMONTH(@date)) THEN format(EOMONTH(@date),'yyyy-MM')
     ELSE format(EOMONTH(@date, 1),'yyyy-MM') END
     AS FinancialMonth,
     CASE WHEN @date < dateadd(day,-4,EOMONTH(@date)) THEN DATEDIFF(day,dateadd(day,-5,EOMONTH(@date,-1)), @date)
     ELSE DATEDIFF(day, dateadd(day,-5,EOMONTH(@date)), @date) END
     AS CountDays
</code>```

Body:
I am trying to write a SQL query that shows the count of the days and date depending upon the financial period it falls in. The financial period starts 5 days before the month end eg march 27th to 26th April

For the above mentioned period if the day is 29th march, the count of the day should be 3 and the date should be 2020-04. The date should adjust depending upon the period it falls in.

I tried to adress the second part of this query by writing the below script but it does not bring any result

declare @date datetime
set @date = getdate()
SELECT format (date,'yyyy-MM-dd') as date

where @date

between dateadd(day,-5,EOMONTH(getdate(),-1)) and dateadd(day,-5,EOMONTH(getdate()))

Body:
updated to include 5 days from previous month.

Is this what you are looking for the second part?

Edit: Modifying the query. I guess this should give you what you need for both the parts.
you can try changing the dates in set @date.

Please note that the -4 instead of -5 is done intentionally as you said the financial month starts 5 days earlier. For March, 31 - 5 would give 26, but it should start on 27 right?  so that on 29th the no. of days should be 3 including 27 and 29. Anyways, the query should be self explanatory, might just need to change the number depending on your requirement.

declare @date datetime
--set @date = getdate()
set @date = '2020-02-14'

SELECT format(@date,'yyyy-MM-dd') as date,
case WHEN @date < dateadd(day,-4,EOMONTH(@date)) THEN format(EOMONTH(@date),'yyyy-MM')
     ELSE format(EOMONTH(@date, 1),'yyyy-MM') END
     AS FinancialMonth,
     CASE WHEN @date < dateadd(day,-4,EOMONTH(@date)) THEN DATEDIFF(day,dateadd(day,-5,EOMONTH(@date,-1)), @date)
     ELSE DATEDIFF(day, dateadd(day,-5,EOMONTH(@date)), @date) END
     AS CountDays


问:
Pass Array into ASP.NET Core Route Query String
I want to do this, but I want to also be able to pass in arrays into the query string. I've tried things like:

```<code>http://www.sitename.com/route?arr[]=this&arr[]=that
http://www.sitename.com/route?arr[]=this&that
http://www.sitename.com/route?arr[0]=this&arr[1]=that
http://www.sitename.com/route?arr0=this&arr1=that
http://www.sitename.com/route?arr=this&arr=that
</code>```

And my route in the C# code looks like this:

```<code>[Route("route")]
[HttpGet]
public void DoSomething(string[] values)
{
    // ...
}
</code>```

But in all of these cases, values is always null when it gets to the C# code. What do I need my query string to be to pass an array of strings?

答:
I had the same problem with .NET Core 3, while trying to pass in a string Array. I solved it by passing in the query parameter as a temporary json string. I then deserialized the string to the resulting array using Newtonsoft's Json package </p>

```<code>using Newtonsoft.Json;

public IActionResult Get([FromQuery(Name = "array")] string arrayJson)
{
    List<string> array = JsonConvert.DeserializeObject<List<string>>(arrayJson);
}
</code>```

Body:
I want to do this, but I want to also be able to pass in arrays into the query string. I've tried things like:

http://www.sitename.com/route?arr[]=this&arr[]=that
http://www.sitename.com/route?arr[]=this&that
http://www.sitename.com/route?arr[0]=this&arr[1]=that
http://www.sitename.com/route?arr0=this&arr1=that
http://www.sitename.com/route?arr=this&arr=that

And my route in the C# code looks like this:

[Route("route")]
[HttpGet]
public void DoSomething(string[] values)
{
    // ...
}

But in all of these cases, values is always null when it gets to the C# code. What do I need my query string to be to pass an array of strings?

Body:
I had the same problem with .NET Core 3, while trying to pass in a string Array. I solved it by passing in the query parameter as a temporary json string. I then deserialized the string to the resulting array using Newtonsoft's Json package

using Newtonsoft.Json;

public IActionResult Get([FromQuery(Name = "array")] string arrayJson)
{
    List<string> array = JsonConvert.DeserializeObject<List<string>>(arrayJson);
}


问:
What's the difference between 'verbose_name' and 'name' fields in a constructor of the Model class?

What's the difference between 'verbose_name' and 'name' fields in a constructor of the Model class?

class Account(models.Model):
    name = models.CharField("Name of Account", "Name", max_length=64)
```
<p>I found that "Name of Account" is <code>verbose_field</code> and "Name" is <code>name</code>.<br/>
I know <code>verbose_field</code> is used for a field name in Admin page.<br/>
But I don't know where the <code>name</code> field is used for? <br/></p>
<pre class="lang-py prettyprint-override"><code>createdAt = models.DateTimeField("Created At", auto_now_add=True)
</code>```

And why does the name not used in this field?

答:
Name will be use as a field name, for example:

If you have:

```<code>class Account(models.Model):
    some_text = models.CharField(name="bla", max_length=64)
</code>```

When you use this model you can see that you have a property bla but not have a property some_text.

Body:
What's the difference between 'verbose_name' and 'name' fields in a constructor of the Model class?

class Account(models.Model):
    name = models.CharField("Name of Account", "Name", max_length=64)

I found that "Name of Account" is verbose_field and "Name" is name.

I know verbose_field is used for a field name in Admin page.

But I don't know where the name field is used for?

createdAt = models.DateTimeField("Created At", auto_now_add=True)

And why does the name not used in this field?

Body:
Name will be use as a field name, for example:

If you have:

class Account(models.Model):
    some_text = models.CharField(name="bla", max_length=64)

When you use this model you can see that you have a property bla but not have a property some_text.


问:
Amazon MWS endpoint to get all offers for an ASIN with PRICE and SELLER NAME of each Offer?
I have a list of ASINs and I want to get the price of the offer from Amazon (if there is any).

I expect that there must be a MWS endpoint with which I can retrieve all offers for an ASIN. The Offer must have price and seller nam. Then I just loop the Offer data and search for Amazon as a seller for this offer.

Anyways I can't find any endpoint which does the job.

Any ideas?

答: To get that kind of detail, you're going to need to subscribe to the AnyOfferChangedNotification notification.</p>


问:
Quickly navigating through an ASP.NET MVC app in Visual Studio
I spent a fair bit of time developing Rails apps in VIM with an amazing plugin called Rails.Vim

Whenever I wanted to navigate to a Model I would hit:

esc :Rmodel topic[enter] to find the topic model.

In this mode tab completion works so I could hit :Rmo[tab] to[tab][enter]

(for an added bonus :RSmodel topic[enter] would split the window and open the model in the split

Or :RTmodel topic[enter] would open it in a new tab)

Similar shortcuts exist for navigation to javascript, css, views, helpers, controllers and so on.

Is there a similar plugin for Visual Studio 2010 that would allow me to approximate this kind of behavior, allowing me to navigate my MVC project with keyboard shortcuts only?

答: You can also customize the shortcut keys to navigate from the controller to the views and back http://ebersys.blogspot.com/2011/05/visual-studio-aspnet-mvc-flip-quickly.html</p>

ContentLicense: CC BY-SA 2.5


问:
Find duplicate objects by a user defined set of fields
my goal is to find duplicates in list of approximately 500000 objects and more. But it should be possible to define what a duplicate is at runtime. Simply but, it should be possible to find duplicates by a (changing) set of user defined fields of those objects.

My approach

create a decorator class for every field

overwrite equal and hash methods

create the desired objects (maybe just the fields color, height out of color, height, width, weight)

find duplicates (not the problem here)

But is this a good approach? I have the feeling that is way too much boilerplate. Is there something more simple?

Restrictions: No SQL.

答:
I was thinking about this some more, so I thought I'd make my comment-suggestion into an actual answer.

I would just create a BiPredicate<T, T> which was concerned with the fields requested (at runtime) and would return true if they were equal with regards to those fields, and false otherwise.

For example, say you had the following type:

```<code>public class YourType {
    private final String name;
    private final int age;
    private final int hatSize;
    // Constructors and getters omitted...
}
</code>```

and you wanted to find duplicates ignoring hatSize, then you could write something like:

```<code>public BiPredicate<YourType, YourType> makeChecker(
        final Collection<Function<YourType, ?>> fieldGetters) {
    // 'first' and 'second' are the two 'YourType' instances
    // to be compared
    return (first, second) -> {
        // Iterate over all the field getters
        for (final Function<YourType, ?> fieldGetter : fieldGetters) {
           // Retrieve the field values from each object
           final Object firstsField = fieldGetter.apply(first);
           final Object secondsField = fieldGetter.apply(second);

           // If they're not equal, break early
           if (!Objects.equals(firstsField, secondsField)) {
               return false;
           }
        }
        // All of the requested properties were equal
        return true;
    };
}
</code>```

and invoke it with something like:

```<code>makeChecker(Arrays.asList(YourType::getName, YourType::getAge));
</code>```

You can then do any normal 'remove duplicates' approach across the collection, comparing them using the returned BiPredicate's test method.

Body:
I was thinking about this some more, so I thought I'd make my comment-suggestion into an actual answer.

I would just create a BiPredicate<T, T> which was concerned with the fields requested (at runtime) and would return true if they were equal with regards to those fields, and false otherwise.

For example, say you had the following type:

public class YourType {
    private final String name;
    private final int age;
    private final int hatSize;
    // Constructors and getters omitted...
}

and you wanted to find duplicates ignoring hatSize, then you could write something like:

public BiPredicate<YourType, YourType> makeChecker(
        final Collection<Function<YourType, ?>> fieldGetters) {
    // 'first' and 'second' are the two 'YourType' instances
    // to be compared
    return (first, second) -> {
        // Iterate over all the field getters
        for (final Function<YourType, ?> fieldGetter : fieldGetters) {
           // Retrieve the field values from each object
           final Object firstsField = fieldGetter.apply(first);
           final Object secondsField = fieldGetter.apply(second);

           // If they're not equal, break early
           if (!Objects.equals(firstsField, secondsField)) {
               return false;
           }
        }
        // All of the requested properties were equal
        return true;
    };
}

and invoke it with something like:

makeChecker(Arrays.asList(YourType::getName, YourType::getAge));

You can then do any normal 'remove duplicates' approach across the collection, comparing them using the returned BiPredicate's test method.


问:
Attempting to save todo list items to local storage
I have a pretty simple to do app that creates to dos and displays them to the screen. However, I wan't to save these to local storage so if someone leaves the page and returns, reloads the page, etc. the to do items remain.

I'm having trouble wrapping my head around how to use local storage though. I know relatively what I need to do, represented in pseudo code in my JavaScript document, but I can't seem to make it work. Any guidance would be greatly appreciated.

https://codepen.io/constequalsexcel/pen/GRJpzoE

function addTodo() {
  let todoItem = document.createElement('li');
  todoItem.setAttribute('class', 'list-item');
  let text = document.getElementById('todo-input').value;
  if (text.length < 1) return;
  let textnode = document.createElement('span');
  textnode.innerText = text;
  // Create delete todo button
  let deleteButton = document.createElement('button');
  let deleteButtonX = document.createTextNode('X');
  deleteButton.appendChild(deleteButtonX);
  deleteButton.addEventListener('click', removeNode);
  // Create strike through radio input
  let StrikeThroughRadio = document.createElement('input');
  StrikeThroughRadio.setAttribute('id', 'checkbox-styles');
  StrikeThroughRadio.setAttribute('type', 'checkbox');
  StrikeThroughRadio.addEventListener('click', function(e) {
    StrikeThroughRadio.checked ?
      e.target.nextElementSibling.classList.add('strike-text') :
      e.target.nextElementSibling.classList.remove('strike-text');
  });

  todoItem.appendChild(StrikeThroughRadio);
  todoItem.appendChild(textnode);
  todoItem.appendChild(deleteButton);
  enter code here

  document.getElementById('display').appendChild(todoItem);

// get saved todos from local storage and save it in a variable
// if saved todos variable is null then re-assign saved todoso variable equal to an empty array
// add current todo text to the saved todos array variable
// re-save saved todos into local storage (using the setItem() method)
    }
    function removeNode(e) {
      e.target.parentElement.remove();
    }
    `enter code here`

    function ClearInputOnSubmit() {
      document.getElementById('todo-input').value = '';
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>

    <html lang="en">

    <head>
      <meta charset="utf-8" />

      <title>To-Do App</title>

      <link rel="stylesheet" href="styles.css" />
      <link href="https://fonts.googleapis.com/css?family=Roboto+Mono&display=swap" rel="stylesheet" />
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" />
    </head>

    <body>
      <h1 id="header">TO DO LIST</h1>
      <div class="main">
        <form class="container" class="needs-validation" novalidate>
          <div class="input-group-prepend">
            <input type="text" id="todo-input" class="form-control input-group shadow-lg" aria-describedby="button-addon2" required />
            <input type="button" value="Add ToDo" id="todo-button" id="button-addon2" class="btn btn-info btn-sm" onclick="addTodo(); ClearInputOnSubmit()" />
          </div>
        </form>
        <div class="todo-container">
          <h4 id="display" class="list-group">TODOS</h4>
        </div>
      </div>
      <script src="scripts.js"></script>
    </body>

</html></code>```

答:
You can save only strings to the localStorage, and you can't stringify element nodes. But innerHTML gets the node as a string, so you can save it in the localStorage.

```<code>//to save the todo-list as a text in the local storage
localStorage.setItem('todoItem', todoItem.innerHTML);

//if you save single todo item at a time in the local storage,
//get the saved text(innerHTML) of the todo-list and append it to the container
todoItem = localStorage.getItem('todoItem');

document.getElementById('display').insertAdjacentHTML('afterend', todoItem);

//or if you save all of the todo-list at once, set the innerHTML of the container
document.getElementById('display').innerHTML = todoItem;
</code>```

Body:
I have a pretty simple to do app that creates to dos and displays them to the screen. However, I wan't to save these to local storage so if someone leaves the page and returns, reloads the page, etc. the to do items remain.

I'm having trouble wrapping my head around how to use local storage though. I know relatively what I need to do, represented in pseudo code in my JavaScript document, but I can't seem to make it work. Any guidance would be greatly appreciated.

https://codepen.io/constequalsexcel/pen/GRJpzoE

function addTodo() {
  let todoItem = document.createElement('li');
  todoItem.setAttribute('class', 'list-item');
  let text = document.getElementById('todo-input').value;
  if (text.length < 1) return;
  let textnode = document.createElement('span');
  textnode.innerText = text;
  // Create delete todo button
  let deleteButton = document.createElement('button');
  let deleteButtonX = document.createTextNode('X');
  deleteButton.appendChild(deleteButtonX);
  deleteButton.addEventListener('click', removeNode);
  // Create strike through radio input
  let StrikeThroughRadio = document.createElement('input');
  StrikeThroughRadio.setAttribute('id', 'checkbox-styles');
  StrikeThroughRadio.setAttribute('type', 'checkbox');
  StrikeThroughRadio.addEventListener('click', function(e) {
    StrikeThroughRadio.checked ?
      e.target.nextElementSibling.classList.add('strike-text') :
      e.target.nextElementSibling.classList.remove('strike-text');
  });

  todoItem.appendChild(StrikeThroughRadio);
  todoItem.appendChild(textnode);
  todoItem.appendChild(deleteButton);
  enter code here

  document.getElementById('display').appendChild(todoItem);

// get saved todos from local storage and save it in a variable
// if saved todos variable is null then re-assign saved todoso variable equal to an empty array
// add current todo text to the saved todos array variable
// re-save saved todos into local storage (using the setItem() method)
    }
    function removeNode(e) {
      e.target.parentElement.remove();
    }
    `enter code here`

    function ClearInputOnSubmit() {
      document.getElementById('todo-input').value = '';
    }

    <!DOCTYPE html>

      <meta charset="utf-8" />

      <title>To-Do App</title>

      <link rel="stylesheet" href="styles.css" />
      <link href="https://fonts.googleapis.com/css?family=Roboto+Mono&display=swap" rel="stylesheet" />
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" />

TO DO LIST

        <form class="container" class="needs-validation" novalidate>

            <input type="text" id="todo-input" class="form-control input-group shadow-lg" aria-describedby="button-addon2" required />
            <input type="button" value="Add ToDo" id="todo-button" id="button-addon2" class="btn btn-info btn-sm" onclick="addTodo(); ClearInputOnSubmit()" />

        </form>

TODOS

Body:
You can save only strings to the localStorage, and you can't stringify element nodes. But innerHTML gets the node as a string, so you can save it in the localStorage.

//to save the todo-list as a text in the local storage
localStorage.setItem('todoItem', todoItem.innerHTML);

//if you save single todo item at a time in the local storage,
//get the saved text(innerHTML) of the todo-list and append it to the container
todoItem = localStorage.getItem('todoItem');

document.getElementById('display').insertAdjacentHTML('afterend', todoItem);

//or if you save all of the todo-list at once, set the innerHTML of the container
document.getElementById('display').innerHTML = todoItem;


问:
How to Implement T-SQL CHECKSUM() in JavaScript for BigQuery?
The end result I'm looking for is to implement T-SQL CHECKSUM in BigQuery with a JavaScript UDF. I would settle for having the C/C++ source code to translate but if someone has already done this work then I'd love to use it.

Alternatively, if someone can think of a way to create an equivalent hash code between strings stored in Microsoft SQL Server compared to those in BigQuery then that would help me too.

UPDATE: I've found some source code through HABO's link in the comments which is written in T-SQL to perform the same CHECKSUM but I'm having difficulty converting it to JavaScript which inherently cannot handle 64bit integers. I'm playing with some small examples and have found that the algorithm works on the low nibble of each byte only.

UPDATE 2: I got really curious about replicating this algorithm and I can see some definite patterns but my brain isn't up to the task of distilling that into a reverse engineered solution. I did find that BINARY_CHECKSUM() and CHECKSUM() return different things so the work done on the former didn't help me with the latter.

Body:
fyi, for those of you who are stuck in T-SQL legacy mode, here's a C# implementation that was tested and looks good for most strings/ints that I've been working with:

public static int[] xorcodes = {
    0, 1, 2, 3, 4, 5, 6, 7,
    8, 9, 10, 11, 12, 13, 14, 15,
    16, 17, 18, 19, 20, 21, 22, 23,
    24, 25, 26, 27, 28, 29, 30, 31,
    0, 33, 34, 35, 36, 37, 38, 39,  //  !"#$%&'
    40, 41, 42, 43, 44, 45, 46, 47,  // ()*+,-./
    132, 133, 134, 135, 136, 137, 138, 139,  // 01234567
    140, 141, 48, 49, 50, 51, 52, 53, 54,  // 89:;<=>?@
    142, 143, 144, 145, 146, 147, 148, 149,  // ABCDEFGH
    150, 151, 152, 153, 154, 155, 156, 157,  // IJKLMNOP
    158, 159, 160, 161, 162, 163, 164, 165,  // QRSTUVWX
    166, 167, 55, 56, 57, 58, 59, 60,  // YZ[\]^_`
    142, 143, 144, 145, 146, 147, 148, 149,  // abcdefgh
    150, 151, 152, 153, 154, 155, 156, 157,  // ijklmnop
    158, 159, 160, 161, 162, 163, 164, 165,  // qrstuvwx
    166, 167, 61, 62, 63, 64, 65, 66,  // yz{|}~
};

public static int rol(int x, int n) {
    // simulate a rotate shift left (>>> preserves the sign bit)
    return ((int)x << n) | ((int)((uint)x >> (32 - n)));
}

public static int checksum(string s) {
    int checksum = 0;
    for (var i = 0; i < s.Length; i++) {
        checksum = rol(checksum, 4);

        var c = ((int)s[i]);
        int xorcode = 0;
        if (c < xorcodes.Length) {
            xorcode = xorcodes[c];
        }
        checksum ^= xorcode;
    }
    return checksum;
}