问:
How to allocate large contiguous, memory regions in Linux
Yes, I will ultimately be using this for DMA but lets leave coherency aside for the moment. I have 64 bit BAR registers, therefore, AFAIK, all of RAM (e.g. higher than 4G) is available for DMA.

I am looking for about 64MB of contiguous RAM. Yes, that's a lot.

Ubuntu 16 and 18 have CONFIG_CMA=y but CONFIG_DMA_CMA is not set at kernel compile time.

I note that if both were set (at Kernel build time) I could simply call dma_alloc_coherent, however, for logistical reasons, it is undesirable to recompile the kernel.

The machines will always have at least 32GB of RAM, do not run anything RAM intensive, and the kernel module will load shortly after boot before RAM becomes significantly fragmented and, AFAIK, nothing else is using the CMA.

I have set the kernel parameter CMA=1G. (and have tried 256M and 512M)

```<code># dmesg | grep cma
[    0.000000] Command line: BOOT_IMAGE=/boot/vmlinuz-4.4.170 root=UUID=2b25933c-e10c-4833-b5b2-92e9d3a33fec ro cma=1G
[    0.000000] Kernel command line: BOOT_IMAGE=/boot/vmlinuz-4.4.170 root=UUID=2b25933c-e10c-4833-b5b2-92e9d3a33fec ro cma=1G
[    0.000000] Memory: 65612056K/67073924K available (8604K kernel code, 1332K rwdata, 3972K rodata, 1484K init, 1316K bss, 1461868K reserved, 0K cma-reserved)
</code>```

I have tried alloc_pages(GFP_KERNEL | __GFP_HIGHMEM, order), no joy.

And finally the actual question: How does one get large contiguous blocks from the CMA? Everything I have found online suggests the use of dma_alloc_coherent but I know this only works with CONFIG_CMA=y and CONFIG_DMA_CMA=yes.

The module source, tim.c

```<code>#include <linux/module.h>       /* Needed by all modules */
#include <linux/kernel.h>       /* Needed for KERN_INFO */
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/gfp.h>
unsigned long big;
const int order = 15;
static int __init tim_init(void)
{
    printk(KERN_INFO "Hello Tim!\n");
    big = __get_free_pages(GFP_KERNEL | __GFP_HIGHMEM, order);
    printk(KERN_NOTICE "big = %lx\n", big);
    if (!big)
        return -EIO; // AT&T

    return 0; // success
}

static void __exit tim_exit(void)
{
    free_pages(big, order);
    printk(KERN_INFO "Tim says, Goodbye world\n");
}

module_init(tim_init);
module_exit(tim_exit);
MODULE_LICENSE("GPL");
</code>```

Inserting the module yields...

```<code># insmod tim.ko
insmod: ERROR: could not insert module tim.ko: Input/output error
# dmesg | tail -n 33

[  176.137053] Hello Tim!
[  176.137056] ------------[ cut here ]------------
[  176.137062] WARNING: CPU: 4 PID: 2829 at mm/page_alloc.c:3198 __alloc_pages_nodemask+0xd14/0xe00()
[  176.137063] Modules linked in: tim(OE+) xt_CHECKSUM iptable_mangle ipt_MASQUERADE nf_nat_masquerade_ipv4 iptable_nat nf_nat_ipv4 nf_nat nf_conntrack_ipv4 nf_defrag_ipv4 xt_conntrack nf_conntrack ipt_REJECT nf_reject_ipv4 xt_tcpudp bridge stp llc ebtable_filter ebtables ip6table_filter ip6_tables iptable_filter ip_tables x_tables configfs vxlan ip6_udp_tunnel udp_tunnel uio pf_ring(OE) x86_pkg_temp_thermal intel_powerclamp coretemp kvm_intel kvm mei_me mei irqbypass sb_edac ioatdma edac_core shpchp serio_raw input_leds lpc_ich dca acpi_pad 8250_fintek mac_hid ib_iser rdma_cm iw_cm ib_cm ib_sa ib_mad ib_core ib_addr iscsi_tcp libiscsi_tcp libiscsi scsi_transport_iscsi autofs4 btrfs raid10 raid456 async_raid6_recov async_memcpy async_pq async_xor async_tx xor raid6_pq libcrc32c raid0 multipath linear
[  176.137094]  hid_generic usbhid crct10dif_pclmul crc32_pclmul ghash_clmulni_intel e1000e aesni_intel raid1 aes_x86_64 isci lrw libsas ahci gf128mul ptp glue_helper ablk_helper cryptd psmouse hid libahci scsi_transport_sas pps_core wmi fjes
[  176.137105] CPU: 4 PID: 2829 Comm: insmod Tainted: G           OE   4.4.170 #1
[  176.137106] Hardware name: Supermicro X9SRL-F/X9SRL-F, BIOS 3.3 11/13/2018
[  176.137108]  0000000000000286 8ba89d23429d5749 ffff88100f5cba90 ffffffff8140a061
[  176.137110]  0000000000000000 ffffffff81cd89dd ffff88100f5cbac8 ffffffff810852d2
[  176.137112]  ffffffff821da620 0000000000000000 000000000000000f 000000000000000f
[  176.137113] Call Trace:
[  176.137118]  [<ffffffff8140a061>] dump_stack+0x63/0x82
[  176.137121]  [<ffffffff810852d2>] warn_slowpath_common+0x82/0xc0
[  176.137123]  [<ffffffff8108541a>] warn_slowpath_null+0x1a/0x20
[  176.137125]  [<ffffffff811a2504>] __alloc_pages_nodemask+0xd14/0xe00
[  176.137128]  [<ffffffff810ddaef>] ? msg_print_text+0xdf/0x1a0
[  176.137132]  [<ffffffff8117bc3e>] ? irq_work_queue+0x8e/0xa0
[  176.137133]  [<ffffffff810de04f>] ? console_unlock+0x20f/0x550
[  176.137137]  [<ffffffff811edbdc>] alloc_pages_current+0x8c/0x110
[  176.137139]  [<ffffffffc0024000>] ? 0xffffffffc0024000
[  176.137141]  [<ffffffff8119ca2e>] __get_free_pages+0xe/0x40
[  176.137143]  [<ffffffffc0024020>] tim_init+0x20/0x1000 [tim]
[  176.137146]  [<ffffffff81002125>] do_one_initcall+0xb5/0x200
[  176.137149]  [<ffffffff811f90c5>] ? kmem_cache_alloc_trace+0x185/0x1f0
[  176.137151]  [<ffffffff81196eb5>] do_init_module+0x5f/0x1cf
[  176.137154]  [<ffffffff81111b05>] load_module+0x22e5/0x2960
[  176.137156]  [<ffffffff8110e080>] ? __symbol_put+0x60/0x60
[  176.137159]  [<ffffffff81221710>] ? kernel_read+0x50/0x80
[  176.137161]  [<ffffffff811123c4>] SYSC_finit_module+0xb4/0xe0
[  176.137163]  [<ffffffff8111240e>] SyS_finit_module+0xe/0x10
[  176.137167]  [<ffffffff8186179b>] entry_SYSCALL_64_fastpath+0x22/0xcb
[  176.137169] ---[ end trace 6aa0b905b8418c7b ]---
[  176.137170] big = 0
</code>```

curiously, trying it again yields...

```<code># insmod tim.ko
insmod: ERROR: could not insert module tim.ko: Input/output error
...and dmesg just shows:

[  302.068396] Hello Tim!
[  302.068398] big = 0
</code>```

why no stack dump the second (and subsequent) try(s)?

答:
The short version is that __GFP_DIRECT_RECLAIM (also provided by __GFP_RECLAIM) is necessary as dma_alloc_contiguous is eventually called and it checks, via a call to gfpflags_allow_blocking, that blocking is okay. I used the usual GFP_KERNEL which provides __GFP_RECLAIM | __GFP_IO | __GFP_FS. But before all that one must call dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64)) with DMA_BIT_MASK(64) not DMA_BIT_MASK(32).

```<code>err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
if (err) {
    printk(KERN_INFO "[%s:probe] dma_set_mask returned: %d\n", DRIVER_NAME, err);
    return -EIO;
}
vaddr = dma_alloc_coherent(&pdev->dev, dbsize, paddr, GFP_KERNEL);
if (!vaddr) {
    printk(KERN_ALERT "[%s:probe] failed to allocate coherent buffer\n", DRIVER_NAME);
    return -EIO;
}

iowrite32(paddr, ctx->bar0_base_addr + 0x140); // tell card where to DMA from
</code>```

Allocating Unreasonably Large DMA Regions Using the CMA with Ubuntu 16.04 & 18.04:

Rebuild Kernel

Use uname -r to ascertain your current kernel version

Issue apt install linux-source-$(uname -r) to fetch the kernel source

copy /boot/config-$(uname -r) to /usr/src/linux-source-$(uname -r)/.config

edit .config

Locate CONFIG_DMA_CMA is not set

change to CONFIG_DMA_CMA=y

build kernel

make -j[2 × # of cores]

make -j[2 × # of cores] modules

make install

You have rebuilt the kernel

Configure CMA to reserve RAM

Edit /etc/defualt/grub

Locate GRUB_CMDLINE_LINUX=""

Change to GRUB_CMDLINE_LINUX="cma=33G"

use your desired CMA reserved RAM in place of 33G

Issue update-grub

Reboot

Issue dmesg | grep cma

Look for Memory: 30788784K/67073924K available (14339K kernel code, 2370K rwdata, 4592K rodata, 2696K init, 5044K bss, 1682132K reserved, 34603008K cma-reserved

note: This example reserves 33G

You have configured CMA to hold back RAM from the normal allocation subsystems

Alter your kernel module (driver) source

Inform the kernel that the card can address 64b

In your probe function locate a line like dma_alloc_coherent(…

A few lines before that you may find dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32))

change this to dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64))

You have informed the kernel that the card in question is not restricted to low memory

dma_alloc_coherent(&pdev->dev, dbsize, paddr, GFP_KERNEL)

dbsize may specify up to 32G

Recompile your kernel module (driver) and test

Body:
Yes, I will ultimately be using this for DMA but lets leave coherency aside for the moment. I have 64 bit BAR registers, therefore, AFAIK, all of RAM (e.g. higher than 4G) is available for DMA.

I am looking for about 64MB of contiguous RAM. Yes, that's a lot.

Ubuntu 16 and 18 have CONFIG_CMA=y but CONFIG_DMA_CMA is not set at kernel compile time.

I note that if both were set (at Kernel build time) I could simply call dma_alloc_coherent, however, for logistical reasons, it is undesirable to recompile the kernel.

The machines will always have at least 32GB of RAM, do not run anything RAM intensive, and the kernel module will load shortly after boot before RAM becomes significantly fragmented and, AFAIK, nothing else is using the CMA.

I have set the kernel parameter CMA=1G. (and have tried 256M and 512M)

# dmesg | grep cma
[    0.000000] Command line: BOOT_IMAGE=/boot/vmlinuz-4.4.170 root=UUID=2b25933c-e10c-4833-b5b2-92e9d3a33fec ro cma=1G
[    0.000000] Kernel command line: BOOT_IMAGE=/boot/vmlinuz-4.4.170 root=UUID=2b25933c-e10c-4833-b5b2-92e9d3a33fec ro cma=1G
[    0.000000] Memory: 65612056K/67073924K available (8604K kernel code, 1332K rwdata, 3972K rodata, 1484K init, 1316K bss, 1461868K reserved, 0K cma-reserved)

I have tried alloc_pages(GFP_KERNEL | __GFP_HIGHMEM, order), no joy.

And finally the actual question: How does one get large contiguous blocks from the CMA? Everything I have found online suggests the use of dma_alloc_coherent but I know this only works with CONFIG_CMA=y and CONFIG_DMA_CMA=yes.

The module source, tim.c

#include <linux/module.h>       /* Needed by all modules */
#include <linux/kernel.h>       /* Needed for KERN_INFO */
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/gfp.h>
unsigned long big;
const int order = 15;
static int __init tim_init(void)
{
    printk(KERN_INFO "Hello Tim!\n");
    big = __get_free_pages(GFP_KERNEL | __GFP_HIGHMEM, order);
    printk(KERN_NOTICE "big = %lx\n", big);
    if (!big)
        return -EIO; // AT&T

    return 0; // success
}

static void __exit tim_exit(void)
{
    free_pages(big, order);
    printk(KERN_INFO "Tim says, Goodbye world\n");
}

module_init(tim_init);
module_exit(tim_exit);
MODULE_LICENSE("GPL");

Inserting the module yields...

# insmod tim.ko
insmod: ERROR: could not insert module tim.ko: Input/output error
# dmesg | tail -n 33

[  176.137053] Hello Tim!
[  176.137056] ------------[ cut here ]------------
[  176.137062] WARNING: CPU: 4 PID: 2829 at mm/page_alloc.c:3198 __alloc_pages_nodemask+0xd14/0xe00()
[  176.137063] Modules linked in: tim(OE+) xt_CHECKSUM iptable_mangle ipt_MASQUERADE nf_nat_masquerade_ipv4 iptable_nat nf_nat_ipv4 nf_nat nf_conntrack_ipv4 nf_defrag_ipv4 xt_conntrack nf_conntrack ipt_REJECT nf_reject_ipv4 xt_tcpudp bridge stp llc ebtable_filter ebtables ip6table_filter ip6_tables iptable_filter ip_tables x_tables configfs vxlan ip6_udp_tunnel udp_tunnel uio pf_ring(OE) x86_pkg_temp_thermal intel_powerclamp coretemp kvm_intel kvm mei_me mei irqbypass sb_edac ioatdma edac_core shpchp serio_raw input_leds lpc_ich dca acpi_pad 8250_fintek mac_hid ib_iser rdma_cm iw_cm ib_cm ib_sa ib_mad ib_core ib_addr iscsi_tcp libiscsi_tcp libiscsi scsi_transport_iscsi autofs4 btrfs raid10 raid456 async_raid6_recov async_memcpy async_pq async_xor async_tx xor raid6_pq libcrc32c raid0 multipath linear
[  176.137094]  hid_generic usbhid crct10dif_pclmul crc32_pclmul ghash_clmulni_intel e1000e aesni_intel raid1 aes_x86_64 isci lrw libsas ahci gf128mul ptp glue_helper ablk_helper cryptd psmouse hid libahci scsi_transport_sas pps_core wmi fjes
[  176.137105] CPU: 4 PID: 2829 Comm: insmod Tainted: G           OE   4.4.170 #1
[  176.137106] Hardware name: Supermicro X9SRL-F/X9SRL-F, BIOS 3.3 11/13/2018
[  176.137108]  0000000000000286 8ba89d23429d5749 ffff88100f5cba90 ffffffff8140a061
[  176.137110]  0000000000000000 ffffffff81cd89dd ffff88100f5cbac8 ffffffff810852d2
[  176.137112]  ffffffff821da620 0000000000000000 000000000000000f 000000000000000f
[  176.137113] Call Trace:
[  176.137118]  [<ffffffff8140a061>] dump_stack+0x63/0x82
[  176.137121]  [<ffffffff810852d2>] warn_slowpath_common+0x82/0xc0
[  176.137123]  [<ffffffff8108541a>] warn_slowpath_null+0x1a/0x20
[  176.137125]  [<ffffffff811a2504>] __alloc_pages_nodemask+0xd14/0xe00
[  176.137128]  [<ffffffff810ddaef>] ? msg_print_text+0xdf/0x1a0
[  176.137132]  [<ffffffff8117bc3e>] ? irq_work_queue+0x8e/0xa0
[  176.137133]  [<ffffffff810de04f>] ? console_unlock+0x20f/0x550
[  176.137137]  [<ffffffff811edbdc>] alloc_pages_current+0x8c/0x110
[  176.137139]  [<ffffffffc0024000>] ? 0xffffffffc0024000
[  176.137141]  [<ffffffff8119ca2e>] __get_free_pages+0xe/0x40
[  176.137143]  [<ffffffffc0024020>] tim_init+0x20/0x1000 [tim]
[  176.137146]  [<ffffffff81002125>] do_one_initcall+0xb5/0x200
[  176.137149]  [<ffffffff811f90c5>] ? kmem_cache_alloc_trace+0x185/0x1f0
[  176.137151]  [<ffffffff81196eb5>] do_init_module+0x5f/0x1cf
[  176.137154]  [<ffffffff81111b05>] load_module+0x22e5/0x2960
[  176.137156]  [<ffffffff8110e080>] ? __symbol_put+0x60/0x60
[  176.137159]  [<ffffffff81221710>] ? kernel_read+0x50/0x80
[  176.137161]  [<ffffffff811123c4>] SYSC_finit_module+0xb4/0xe0
[  176.137163]  [<ffffffff8111240e>] SyS_finit_module+0xe/0x10
[  176.137167]  [<ffffffff8186179b>] entry_SYSCALL_64_fastpath+0x22/0xcb
[  176.137169] ---[ end trace 6aa0b905b8418c7b ]---
[  176.137170] big = 0

curiously, trying it again yields...

# insmod tim.ko
insmod: ERROR: could not insert module tim.ko: Input/output error
...and dmesg just shows:

[  302.068396] Hello Tim!
[  302.068398] big = 0

why no stack dump the second (and subsequent) try(s)?

Body:
The short version is that __GFP_DIRECT_RECLAIM (also provided by __GFP_RECLAIM) is necessary as dma_alloc_contiguous is eventually called and it checks, via a call to gfpflags_allow_blocking, that blocking is okay. I used the usual GFP_KERNEL which provides __GFP_RECLAIM | __GFP_IO | __GFP_FS. But before all that one must call dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64)) with DMA_BIT_MASK(64) not DMA_BIT_MASK(32).

err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
if (err) {
    printk(KERN_INFO "[%s:probe] dma_set_mask returned: %d\n", DRIVER_NAME, err);
    return -EIO;
}
vaddr = dma_alloc_coherent(&pdev->dev, dbsize, paddr, GFP_KERNEL);
if (!vaddr) {
    printk(KERN_ALERT "[%s:probe] failed to allocate coherent buffer\n", DRIVER_NAME);
    return -EIO;
}

iowrite32(paddr, ctx->bar0_base_addr + 0x140); // tell card where to DMA from

Allocating Unreasonably Large DMA Regions Using the CMA with Ubuntu 16.04 & 18.04:

Rebuild Kernel

Use uname -r to ascertain your current kernel version

Issue apt install linux-source-$(uname -r) to fetch the kernel source

copy /boot/config-$(uname -r) to /usr/src/linux-source-$(uname -r)/.config

edit .config

Locate CONFIG_DMA_CMA is not set

change to CONFIG_DMA_CMA=y

build kernel

make -j[2 × # of cores]

make -j[2 × # of cores] modules

make install

You have rebuilt the kernel

Configure CMA to reserve RAM

Edit /etc/defualt/grub

Locate GRUB_CMDLINE_LINUX=""

Change to GRUB_CMDLINE_LINUX="cma=33G"

use your desired CMA reserved RAM in place of 33G

Issue update-grub

Reboot

Issue dmesg | grep cma

Look for Memory: 30788784K/67073924K available (14339K kernel code, 2370K rwdata, 4592K rodata, 2696K init, 5044K bss, 1682132K reserved, 34603008K cma-reserved

note: This example reserves 33G

You have configured CMA to hold back RAM from the normal allocation subsystems

Alter your kernel module (driver) source

Inform the kernel that the card can address 64b

In your probe function locate a line like dma_alloc_coherent(…

A few lines before that you may find dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32))

change this to dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64))

You have informed the kernel that the card in question is not restricted to low memory

dma_alloc_coherent(&pdev->dev, dbsize, paddr, GFP_KERNEL)

dbsize may specify up to 32G

Recompile your kernel module (driver) and test


来源: stackexchange

问:
Lengths of series not matching for np.where
I have a dataframe, MSYs_init, that contains an existing column "Start Date" with about 250 values.  I want to take the year from that column's dates and match it to the year in a series of grant start dates.  Please see below, as I believe I have overcomplicated things and cannot get the solution through Google-fu.

```<code>MSYs_init['Start Date'] = pd.to_datetime(MSYs_init['Start Date'], errors='coerce')
VISTAMbrStartYr = pd.DatetimeIndex(MSYs_init['Start Date']).year

VISTAGrantYrStarts = pd.Series(['2020, 8, 17','2019, 8, 18', '2018, 8, 19', '2017, 9, 17'])
VISTAGrantYrStarts = pd.to_datetime(VISTAGrantYrStarts, errors='coerce')
VISTAGrantYr = pd.DatetimeIndex(VISTAGrantYrStarts).year

MSYs_init['VISTA Grant Year'] = np.where(VISTAMbrStartYr == VISTAGrantYr, VISTAGrantYrStarts, np.nan)
</code>```

This is my error:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-129-27a1a1454145> in <module>
     12 VISTAGrantYr = pd.DatetimeIndex(VISTAGrantYrStarts).year
     13
---> 14 MSYs_init['Mbr Starting Grant Yr'] = np.where((VISTAMbrStartYr == VISTAGrantYr) &
     15                                               (VISTAMbrStartMoDay >= VISTAGrantYrStartMoDay),
     16                                               VISTAMbrStartYr,VISTAMbrStartYr-1)

~\anaconda3\envs\PythonData\lib\site-packages\pandas\core\indexes\base.py in cmp_method(self, other)
    100         if isinstance(other, (np.ndarray, Index, ABCSeries)):
    101             if other.ndim > 0 and len(self) != len(other):
--> 102                 raise ValueError("Lengths must match to compare")
    103
    104         if is_object_dtype(self) and not isinstance(self, ABCMultiIndex):

ValueError: Lengths must match to compare
</code>```

答:
If I understand correctly, what you are trying to achieve can be done with the following:

```<code>MSYs_init['Start Date'] = pd.to_datetime(MSYs_init['Start Date'], errors='coerce')
VISTAGrantYrStarts = pd.to_datetime(VISTAGrantYrStarts, errors='coerce')
VISTAGrantYr = VISTAGrantYrStarts.year
MSYs_init['VISTA Grand Year'] = np.where(MSYs_init['Start Date'].dt.year.isin(VISTAGrantYr),
                                         MSYs_init['Start Date'].dt.year,
                                         np.nan)
</code>```

Working example:

```<code>import pandas as pd
import numpy as np
df=pd.DataFrame({'index':[0,1,2,3],
                 'dates':['2019-02-20','2019-02-21','2020-02-21','2021-02-20']})
df['dates'] = pd.to_datetime(df['dates'],errors='coerce')
aux = pd.to_datetime(['2017-02-20','2018-02-21','2019-02-21','2019-02-20'],errors='coerce').year
df['dates_2'] = np.where(df['dates'].dt.year.isin(aux),df['dates'].dt.year,np.nan)
</code>```

Output:

```<code>   index      dates  dates_2
0      0 2019-02-20   2019.0
1      1 2019-02-21   2019.0
2      2 2020-02-21      NaN
3      3 2021-02-20      NaN
</code>```

@Celius, I need it to return the VISTAGrantYrStarts, not "Start Date", and so when I try to do this, it doesn't work.

```<code>MSYs_init['Start Date'] = pd.to_datetime(MSYs_init['Start Date'],errors='coerce')
GrantStarts = pd.to_datetime(['2017-02-20','2018-02-21','2019-02-21','2019-02-20'],errors='coerce').year
MSYs_init['Mbr Grant Start'] = np.where(MSYs_init['Start Date'].dt.year.isin(GrantStarts),GrantStarts.dt.year,np.nan)
MSYs_init.head(50)

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-71-52fd06b959bf> in <module>
      1 MSYs_init['Start Date'] = pd.to_datetime(MSYs_init['Start Date'],errors='coerce')
      2 GrantStarts = pd.to_datetime(['2017-02-20','2018-02-21','2019-02-21','2019-02-20'],errors='coerce').year
----> 3 MSYs_init['Mbr Grant Start'] = np.where(MSYs_init['Start Date'].dt.year.isin(GrantStarts),GrantStarts.dt.year,np.nan)
      4 MSYs_init.head(50)

AttributeError: 'Int64Index' object has no attribute 'dt'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe, MSYs_init, that contains an existing column "Start Date" with about 250 values.  I want to take the year from that column's dates and match it to the year in a series of grant start dates.  Please see below, as I believe I have overcomplicated things and cannot get the solution through Google-fu.

MSYs_init['Start Date'] = pd.to_datetime(MSYs_init['Start Date'], errors='coerce')
VISTAMbrStartYr = pd.DatetimeIndex(MSYs_init['Start Date']).year

VISTAGrantYrStarts = pd.Series(['2020, 8, 17','2019, 8, 18', '2018, 8, 19', '2017, 9, 17'])
VISTAGrantYrStarts = pd.to_datetime(VISTAGrantYrStarts, errors='coerce')
VISTAGrantYr = pd.DatetimeIndex(VISTAGrantYrStarts).year

MSYs_init['VISTA Grant Year'] = np.where(VISTAMbrStartYr == VISTAGrantYr, VISTAGrantYrStarts, np.nan)

This is my error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-129-27a1a1454145> in <module>
     12 VISTAGrantYr = pd.DatetimeIndex(VISTAGrantYrStarts).year
     13
---> 14 MSYs_init['Mbr Starting Grant Yr'] = np.where((VISTAMbrStartYr == VISTAGrantYr) &
     15                                               (VISTAMbrStartMoDay >= VISTAGrantYrStartMoDay),
     16                                               VISTAMbrStartYr,VISTAMbrStartYr-1)

~\anaconda3\envs\PythonData\lib\site-packages\pandas\core\indexes\base.py in cmp_method(self, other)
    100         if isinstance(other, (np.ndarray, Index, ABCSeries)):
    101             if other.ndim > 0 and len(self) != len(other):
--> 102                 raise ValueError("Lengths must match to compare")
    103
    104         if is_object_dtype(self) and not isinstance(self, ABCMultiIndex):

ValueError: Lengths must match to compare

Body:
If I understand correctly, what you are trying to achieve can be done with the following:

MSYs_init['Start Date'] = pd.to_datetime(MSYs_init['Start Date'], errors='coerce')
VISTAGrantYrStarts = pd.to_datetime(VISTAGrantYrStarts, errors='coerce')
VISTAGrantYr = VISTAGrantYrStarts.year
MSYs_init['VISTA Grand Year'] = np.where(MSYs_init['Start Date'].dt.year.isin(VISTAGrantYr),
                                         MSYs_init['Start Date'].dt.year,
                                         np.nan)

Working example:

import pandas as pd
import numpy as np
df=pd.DataFrame({'index':[0,1,2,3],
                 'dates':['2019-02-20','2019-02-21','2020-02-21','2021-02-20']})
df['dates'] = pd.to_datetime(df['dates'],errors='coerce')
aux = pd.to_datetime(['2017-02-20','2018-02-21','2019-02-21','2019-02-20'],errors='coerce').year
df['dates_2'] = np.where(df['dates'].dt.year.isin(aux),df['dates'].dt.year,np.nan)

Output:

   index      dates  dates_2
0      0 2019-02-20   2019.0
1      1 2019-02-21   2019.0
2      2 2020-02-21      NaN
3      3 2021-02-20      NaN

@Celius, I need it to return the VISTAGrantYrStarts, not "Start Date", and so when I try to do this, it doesn't work.

MSYs_init['Start Date'] = pd.to_datetime(MSYs_init['Start Date'],errors='coerce')
GrantStarts = pd.to_datetime(['2017-02-20','2018-02-21','2019-02-21','2019-02-20'],errors='coerce').year
MSYs_init['Mbr Grant Start'] = np.where(MSYs_init['Start Date'].dt.year.isin(GrantStarts),GrantStarts.dt.year,np.nan)
MSYs_init.head(50)

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-71-52fd06b959bf> in <module>
      1 MSYs_init['Start Date'] = pd.to_datetime(MSYs_init['Start Date'],errors='coerce')
      2 GrantStarts = pd.to_datetime(['2017-02-20','2018-02-21','2019-02-21','2019-02-20'],errors='coerce').year
----> 3 MSYs_init['Mbr Grant Start'] = np.where(MSYs_init['Start Date'].dt.year.isin(GrantStarts),GrantStarts.dt.year,np.nan)
      4 MSYs_init.head(50)

AttributeError: 'Int64Index' object has no attribute 'dt'


问:
Sinatra success stories
Have you used Sinatra successfully? What kind of a project was it? In what situations would you recommend using Sinatra instead of Rails or Merb?</p>

答:
I think sinatra is best suited for micro-applications development (no big surprise, it's a micro-framework)

Sinatra provides you with a sufficient level of abstraction to build almost everything you want quickly. And what I like about sinatra is that the framework gives you tight control over what your app is actually doing, you can really "feel" what you are writing. So, I would say Sinatra is a subtly balanced framework.

I also think Sinatra is attractive for "people who likes writing Ruby" as said before. You start writing ruby class before implementing a sinatra interface. (good exemple of this kind of workflow here : http://dev-logger.blogspot.com/2009/01/ric-rac-roe-in-soup-of-technologies.html)

OwnerDisplayName: Antti Tarvainen

ContentLicense: CC BY-SA 2.5

Title: Sinatra success stories

LastEditorDisplayName: Antti Tarvainen

OwnerDisplayName: Gaetan Dubar


问:
I am getting error for isDisplayed method?
if (driver.findElement(By.id(id)).isDisplayed()) {

}

Always execution is failed when element is not available?

Environment:

Appium 1.15.1

java Client 7.3.0

selenium-java 3.141.59

error logs:

Android Loding Problem Pages

org.openqa.selenium.NoSuchElementException: Can't locate an element by this strategy: By.chained({By.AccessibilityId: OK})
    at io.appium.java_client.pagefactory.AppiumElementLocator.findElement(AppiumElementLocator.java:126)
    at io.appium.java_client.pagefactory.interceptors.InterceptorOfASingleElement.intercept(InterceptorOfASingleElement.java:59)
    at io.appium.java_client.ios.IOSElement$$EnhancerByCGLIB$$d311658.isDisplayed()
    at
    at ✽.And Verify the On Side Menu List are Navigating to correspont Screen with OnBoared User(:12)
Caused by: org.openqa.selenium.TimeoutException: Expected condition failed: waiting for io.appium.java_client.pagefactory.AppiumElementLocator$WaitingFunction@66ba7e45 (tried for 1 second(s) with 500 milliseconds interval)
    at org.openqa.selenium.support.ui.FluentWait.timeoutException(FluentWait.java:304)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:272)
    at io.appium.java_client.pagefactory.AppiumElementLocator.waitFor(AppiumElementLocator.java:99)
    at io.appium.java_client.pagefactory.AppiumElementLocator.findElement(AppiumElementLocator.java:119)
    at io.appium.java_client.pagefactory.interceptors.InterceptorOfASingleElement.intercept(InterceptorOfASingleElement.java:59)
    at io.appium.java_client.ios.IOSElement$$EnhancerByCGLIB$$d311658.isDisplayed()
    at
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at cucumber.runtime.Utils$1.call(Utils.java:40)
    at cucumber.runtime.Timeout.timeout(Timeout.java:16)
    at cucumber.runtime.Utils.invoke(Utils.java:34)
    at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
    at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
    at cucumber.runtime.Runtime.runStep(Runtime.java:300)
    at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
    at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
    at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
    at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:102)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:95)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:38)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.api.junit.Cucumber.run(Cucumber.java:100)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:39)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.Iterator.forEachRemaining(Iterator.java:116)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
    at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:79)
    at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:70)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: org.openqa.selenium.NoSuchElementException: Cannot locate an element using By.chained({By.AccessibilityId: OK})
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'Elites-MacBook-Pro-4.local', ip: 'fe80:0:0:0:1c56:6e8a:fceb:a653%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.15.3', java.version: '1.8.0_201'
Driver info: driver.version: IOSDriver
    at io.appium.java_client.pagefactory.bys.builder.ByChained.findElement(ByChained.java:74)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
    at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:57)
    at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
    at io.appium.java_client.ios.IOSDriver.findElement(IOSDriver.java:1)
    at io.appium.java_client.pagefactory.bys.ContentMappedBy.findElement(ContentMappedBy.java:50)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
    at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:57)
    at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
    at io.appium.java_client.ios.IOSDriver.findElement(IOSDriver.java:1)
    at io.appium.java_client.pagefactory.AppiumElementLocator.lambda$0(AppiumElementLocator.java:120)
    at io.appium.java_client.pagefactory.AppiumElementLocator$WaitingFunction.apply(AppiumElementLocator.java:172)
    at io.appium.java_client.pagefactory.AppiumElementLocator$WaitingFunction.apply(AppiumElementLocator.java:1)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:249)
    ... 67 more

答:
You can write a custom function for mobile element’s visibility.

```<code>public boolean checkMobileElementExist(By by)  {
        boolean objectExist = false;
        try {
            objectExist = element.findElement(by).isDisplayed();

        } catch (NoSuchElementException e) {
            return false;
        }

        return objectExist;
    }
</code>```

Now you can use this function in you code

```<code>if (checkMobileElementExist(By.id(id))) {
}
</code>```

Body:
You can write a custom function for mobile element’s visibility.

public boolean checkMobileElementExist(By by)  {
        boolean objectExist = false;
        try {
            objectExist = element.findElement(by).isDisplayed();

        } catch (NoSuchElementException e) {
            return false;
        }

        return objectExist;
    }

Now you can use this function in you code

if (checkMobileElementExist(By.id(id))) {
}


问:
Tinkerpop: Creating nested Properties
I want to create a Vertex of label foo, which contains a property child. Child property will have two properties A, B. Child in itself can contain more nested children.

If vertex foo is deleted, its all properties including child property should be deleted. My query pattern would be to query all vertexes of label foo which has property A = 'bar'

This can be easily represented by representing the child as vertices instead of property, but then the child has to be deleted by doing dfs/bfs originating from vertex foo. This is proving a costly affair. If childs are saved as property, drop operation will be saved of dfs/bfs.

How do I create nested properties and how can I query them using apache tinkerpop. Is there any other data model I can adopt to reduce the query cost.

答:
Neptune does not support meta properties.  Even if it would, you should not have used them. If you have hierarchical structure, and you already use a graph DB, then you should benefit from its capabilities.
If just storing nested properties is your need, maybe you should look at document DB instead.

Deleting a child vertex should not be an expensive operation:

```<code>g.V(child_id).emit().repeat(out()).drop()
</code>```

Title: Tinkerpop: Creating nested Properties

Body:
Neptune does not support meta properties.  Even if it would, you should not have used them. If you have hierarchical structure, and you already use a graph DB, then you should benefit from its capabilities.
If just storing nested properties is your need, maybe you should look at document DB instead.

Deleting a child vertex should not be an expensive operation:

g.V(child_id).emit().repeat(out()).drop()


问:
Swift Compiler Error: Cannot convert value of type '()' to specified type 'String'
I am using Swift playgrounds and learning about parameters in Lesson 9 of Intro to Swift.

func sing(verb: String, noun: String) {
    print("\(verb), \(verb), \(verb) your \(noun)")
}

let line = sing(verb: "Row", noun: "Boat")
```

The last line gives me this warning:

Constant 'line' inferred to have type '()', which may be unexpected.

When I explicitly define the constant as a String—let line: String = sing(verb: "Row", noun: "Boat")—I get the following error:

error: cannot convert value of type '()' to specified type 'String'

I'm not sure what to do in order to resolve this.

Side note: If you have suggestions for how to make the function read more like a sentence, I'd appreciate it!

答:
Your function sing() is not returning a String object.

Hence you cannot use variable = void function() as it’s not a valid assignment operation.

You can specify String as a return type of sing(), and return the string you are printing in the function. That will solve your problem.

```<code>func sing(verb: String, noun: String) -> String {
  return "\(verb), \(verb), \(verb) your \(noun)"
}

let line = sing(verb: "Row", noun: "Boat")
</code>```

Body:
I am using Swift playgrounds and learning about parameters in Lesson 9 of Intro to Swift.

func sing(verb: String, noun: String) {
    print("\(verb), \(verb), \(verb) your \(noun)")
}

let line = sing(verb: "Row", noun: "Boat")

The last line gives me this warning:

Constant 'line' inferred to have type '()', which may be unexpected.

When I explicitly define the constant as a String—let line: String = sing(verb: "Row", noun: "Boat")—I get the following error:

error: cannot convert value of type '()' to specified type 'String'

I'm not sure what to do in order to resolve this.

Side note: If you have suggestions for how to make the function read more like a sentence, I'd appreciate it!

Body:
Your function sing() is not returning a String object.

Hence you cannot use variable = void function() as it’s not a valid assignment operation.

You can specify String as a return type of sing(), and return the string you are printing in the function. That will solve your problem.

func sing(verb: String, noun: String) -> String {
  return "\(verb), \(verb), \(verb) your \(noun)"
}

let line = sing(verb: "Row", noun: "Boat")


问:
How can I make my javascript animation faster?
I made a Vue component to make a div's loop over the X axis. But I noticed that it uses alot of CPU. I works like I want to but I would like to optimize it. How could I make my animation faster. The galeryItems moves over the x axis and when they reach the width of their parent div they get moves to the other side. So the keep looping. I would preferer not to use external plugins.</p>

```<code><template>
    <div class="placeholder">
      <div class="galery" ref="galery">
          <div class="galery-item" v-for="i in 10" :key="i" ref="galeryItems" />
      </div>
    </div>
</template>

<script>
export default {
    props:{
      xoffset : {
        type: Number,
        default: 0,
      },
      speed : {
        type: Number,
        default: 1,
      },
      spaceBetween : {
        type: Number,
        default: 50,
      },
    },
    data() {
      return {
      }
    },
    mounted(){
      for(let i = 0; i < this.$refs.galeryItems.length; i++)
        this.$refs.galeryItems[i].style.transform = 'translateX(' + (this.$refs.galeryItems[i].clientWidth + this.spaceBetween) * i + 'px)';
      this.animate();
    },
    methods:{
      animate(){
        window.requestAnimationFrame(this.animate);
        for(let i = 0; i < this.$refs.galeryItems.length; i++)
        {
          let galeryItemRect = this.$refs.galeryItems[i].getBoundingClientRect();
          if(galeryItemRect.x > this.$refs.galery.clientWidth)
          {
            this.$refs.galeryItems[i].style.transform = 'translateX(' + -galeryItemRect.width + 'px)';
            continue;
          }

          this.$refs.galeryItems[i].style.transform = 'translateX(' + (galeryItemRect.x + this.speed) + 'px)';
        }
      }
    }
}
</script>

<style lang="scss" scoped>
.placeholder{
  height: 100vh;
  display: flex;
  align-items: center;
}

.galery
{
  position: relative;
  background-color: green;
  height: 100px;
  width: 100%;
  overflow: hidden;
}

.galery-item{
  display: block;
  position: absolute;
  background-color: black;
  height: inherit;
  min-width: 100px;
  transition: 0s;
}
</style>
</code>```

答:
try to use external plugin , its better in performance and quality, in vue.js use the framework options like v-animate and transition in the link below:

https://v2.vuejs.org/v2/guide/transitions.html

Body:
I made a Vue component to make a div's loop over the X axis. But I noticed that it uses alot of CPU. I works like I want to but I would like to optimize it. How could I make my animation faster. The galeryItems moves over the x axis and when they reach the width of their parent div they get moves to the other side. So the keep looping. I would preferer not to use external plugins.

<template>

</template>


问:
How to zip each element from a 1D array with the elements from each row of a 2D array?
I am trying to plot a dataset using matplotlib which contains multiple y coordinates per x. To plot them I have to combine these arrays to show them in a single plot. How do I zip each element from a 1D array with the elements from each row of a 2D array (corresponding with the index for the element of the 1D array)? Without using explicit for-loops. Using built-ins (eg. zip/list comprehension) or even better: numpy?

Turning:

```<code>x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]
</code>```

Into:

```<code>r = [(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]
</code>```

答:
Inspired by approach 5 here:

```<code>from functools import reduce

x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]

def listOfTuples(l1, l2):
    l = list(map(lambda x, y:[(x,y[0]), (x,y[1])], l1, l2))
    m = reduce(lambda x, y: x + y, l)
    return(m)

r = listOfTuples(x, y)
</code>```

Gives

```<code>[(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]
</code>```

Body:
I am trying to plot a dataset using matplotlib which contains multiple y coordinates per x. To plot them I have to combine these arrays to show them in a single plot. How do I zip each element from a 1D array with the elements from each row of a 2D array (corresponding with the index for the element of the 1D array)? Without using explicit for-loops. Using built-ins (eg. zip/list comprehension) or even better: numpy?

Turning:

x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]

Into:

r = [(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]

Body:
Inspired by approach 5 here:

from functools import reduce

x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]

def listOfTuples(l1, l2):
    l = list(map(lambda x, y:[(x,y[0]), (x,y[1])], l1, l2))
    m = reduce(lambda x, y: x + y, l)
    return(m)

r = listOfTuples(x, y)

Gives

[(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]


问:
Forming system of constraint equations using GEKKO optimization framework
I'm trying to solve a simple minimum time optimal control problem using double integrator dynamics of the form,

```<code>dx1/dt = x2
dx2/dt = u
</code>```

with the GEKKO optimization framework as follows:

```<code>from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt

model = GEKKO(remote=False)

x1_initial = 0.0
x1_final = 10.0

x2_initial = 0.0
x2_final = 0.0

t_initial = 0.0
t_final = 25.0
num_timesteps = 1000
dt = (t_final - t_initial) / num_timesteps

x = model.Array(model.Var, (2, num_timesteps + 1))
u = model.Array(model.Var, num_timesteps + 1)
tf = model.Var()

for k in range(num_timesteps + 1):
    u[k].lower = -0.4
    u[k].upper = 0.4
    u[k].value = 0.0

for k in range(num_timesteps + 1):
    x[0, k].value = 5.0
    x[1, k].value = 0.0

tf.lower = t_initial
tf.upper = t_final
tf.value = t_final
dt = (tf - t_initial) / num_timesteps

def f(x, u, k):
    return np.array([x[1,k], u[k]])

for k in range(num_timesteps):
    model.Equations([x[:, k + 1] == x[:, k] + (dt/2.0)*(f(x, u, k + 1) + f(x, u, k))])
    # model.Equation(x[0, k + 1] == x[0, k] + (dt/2.0)*(x[1, k + 1] + x[1, k]))
    # model.Equation(x[1, k + 1] == x[1, k] + (dt/2.0)*(u[k + 1] + u[k]))

model.Equation(x[0, 0] == x1_initial)
model.Equation(x[0, num_timesteps] == x1_final)

model.Equation(x[1, 0] == x2_initial)
model.Equation(x[1, num_timesteps] == x2_final)

model.Minimize(tf)
model.options.solver = 3
model.solve()

# Plotting results
t = np.linspace(t_initial, tf.value, num_timesteps + 1)

u_optimal = []
for k in range(num_timesteps + 1):
    u_optimal.append(u[k].value)

x1_optimal = []
for k in range(num_timesteps + 1):
    x1_optimal.append(x[0, k].value)

x2_optimal = []
for k in range(num_timesteps + 1):
    x2_optimal.append(x[1, k].value)

plt.figure()
plt.plot(t, u_optimal)
plt.xlabel('time (s)')
plt.ylabel('u(t)')
plt.grid()

plt.figure()
plt.plot(t, x1_optimal)
plt.xlabel('time (s)')
plt.ylabel('x1(t)')
plt.grid()

plt.figure()
plt.plot(t, x2_optimal)
plt.xlabel('time (s)')
plt.ylabel('x2(t)')
plt.grid()

plt.show()
</code>```

What I'm trying to do is to form a system of equality constraints using trapezoidal integration and then solve this system for the optimal control inputs using GEKKO. However, using the function definition,

```<code>def f(x, u, k):
    return np.array([x[1,k], u[k]])
</code>```

in conjunction with the system of equality constraints,

```<code>for k in range(num_timesteps):
    model.Equations([x[:, k + 1] == x[:, k] + (dt/2.0)*(f(x, u, k + 1) + f(x, u, k))])
</code>```

gives me the following error,

```<code>Exception: @error: Equation Definition
 Equation without an equality (=) or inequality (>,<)
 false
 STOPPING...
</code>```

I've added two commented lines of code in the above code snippet that will allow the program to run correctly, but I'm hoping to avoid having to separate each equation out, since I'd like to extend this to problems that deal with more complicated system dynamics, and to also use more sophisticated collocation methods instead of the trapezoidal approach.

I know that GEKKO has some nice features for dynamic optimization, but I'm looking to try and implement various direct collocation methods myself to understand the theory a bit better.

Body:
I'm trying to solve a simple minimum time optimal control problem using double integrator dynamics of the form,

dx1/dt = x2
dx2/dt = u

with the GEKKO optimization framework as follows:

from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt

model = GEKKO(remote=False)

x1_initial = 0.0
x1_final = 10.0

x2_initial = 0.0
x2_final = 0.0

t_initial = 0.0
t_final = 25.0
num_timesteps = 1000
dt = (t_final - t_initial) / num_timesteps

x = model.Array(model.Var, (2, num_timesteps + 1))
u = model.Array(model.Var, num_timesteps + 1)
tf = model.Var()

for k in range(num_timesteps + 1):
    u[k].lower = -0.4
    u[k].upper = 0.4
    u[k].value = 0.0

for k in range(num_timesteps + 1):
    x[0, k].value = 5.0
    x[1, k].value = 0.0

tf.lower = t_initial
tf.upper = t_final
tf.value = t_final
dt = (tf - t_initial) / num_timesteps

def f(x, u, k):
    return np.array([x[1,k], u[k]])

for k in range(num_timesteps):
    model.Equations([x[:, k + 1] == x[:, k] + (dt/2.0)*(f(x, u, k + 1) + f(x, u, k))])
    # model.Equation(x[0, k + 1] == x[0, k] + (dt/2.0)*(x[1, k + 1] + x[1, k]))
    # model.Equation(x[1, k + 1] == x[1, k] + (dt/2.0)*(u[k + 1] + u[k]))

model.Equation(x[0, 0] == x1_initial)
model.Equation(x[0, num_timesteps] == x1_final)

model.Equation(x[1, 0] == x2_initial)
model.Equation(x[1, num_timesteps] == x2_final)

model.Minimize(tf)
model.options.solver = 3
model.solve()

# Plotting results
t = np.linspace(t_initial, tf.value, num_timesteps + 1)

u_optimal = []
for k in range(num_timesteps + 1):
    u_optimal.append(u[k].value)

x1_optimal = []
for k in range(num_timesteps + 1):
    x1_optimal.append(x[0, k].value)

x2_optimal = []
for k in range(num_timesteps + 1):
    x2_optimal.append(x[1, k].value)

plt.figure()
plt.plot(t, u_optimal)
plt.xlabel('time (s)')
plt.ylabel('u(t)')
plt.grid()

plt.figure()
plt.plot(t, x1_optimal)
plt.xlabel('time (s)')
plt.ylabel('x1(t)')
plt.grid()

plt.figure()
plt.plot(t, x2_optimal)
plt.xlabel('time (s)')
plt.ylabel('x2(t)')
plt.grid()

plt.show()

What I'm trying to do is to form a system of equality constraints using trapezoidal integration and then solve this system for the optimal control inputs using GEKKO. However, using the function definition,

def f(x, u, k):
    return np.array([x[1,k], u[k]])

in conjunction with the system of equality constraints,

for k in range(num_timesteps):
    model.Equations([x[:, k + 1] == x[:, k] + (dt/2.0)*(f(x, u, k + 1) + f(x, u, k))])

gives me the following error,

Exception: @error: Equation Definition
 Equation without an equality (=) or inequality (>,<)
 false
 STOPPING...

I've added two commented lines of code in the above code snippet that will allow the program to run correctly, but I'm hoping to avoid having to separate each equation out, since I'd like to extend this to problems that deal with more complicated system dynamics, and to also use more sophisticated collocation methods instead of the trapezoidal approach.

I know that GEKKO has some nice features for dynamic optimization, but I'm looking to try and implement various direct collocation methods myself to understand the theory a bit better.

Body:
There are some examples of orthogonal collocation on finite elements in the Machine Learning and Dynamic Optimization course.

from __future__ import division
import numpy as np
from scipy.optimize import fsolve
from scipy.integrate import odeint
import matplotlib.pyplot as plt

# final time
tf = 1.0

# solve with ODEINT (for comparison)
def model(x,t):
    u = 4.0
    return (-x**2 + u)/5.0
t = np.linspace(0,tf,20)
y0 = 0
y = odeint(model,y0,t)
plt.figure(1)
plt.plot(t,y,'r-',label='ODEINT')

# ----------------------------------------------------
# Approach #1 - Write the model equations in Python
# ----------------------------------------------------
# define collocation matrices
def colloc(n):
    if (n==2):
        NC = np.array([[1.0]])
    if (n==3):
        NC = np.array([[0.75,-0.25], \
                       [1.00, 0.00]])
    if (n==4):
        NC = np.array([[0.436,-0.281, 0.121], \
                       [0.614, 0.064, 0.0461], \
                       [0.603, 0.230, 0.167]])
    if (n==5):
        NC = np.array([[0.278, -0.202, 0.169, -0.071], \
                       [0.398,  0.069, 0.064, -0.031], \
                       [0.387,  0.234, 0.278, -0.071], \
                       [0.389,  0.222, 0.389,  0.000]])
    if (n==6):
        NC = np.array([[0.191, -0.147, 0.139, -0.113, 0.047],
                       [0.276,  0.059, 0.051, -0.050, 0.022],
                       [0.267,  0.193, 0.252, -0.114, 0.045],
                       [0.269,  0.178, 0.384,  0.032, 0.019],
                       [0.269,  0.181, 0.374,  0.110, 0.067]])
    return NC

# define collocation points from Lobatto quadrature
def tc(n):
    if (n==2):
        time = np.array([0.0,1.0])
    if (n==3):
        time = np.array([0.0,0.5,1.0])
    if (n==4):
        time = np.array([0.0, \
                         0.5-np.sqrt(5)/10.0, \
                         0.5+np.sqrt(5)/10.0, \
                         1.0])
    if (n==5):
        time = np.array([0.0,0.5-np.sqrt(21)/14.0, \
                         0.5,0.5+np.sqrt(21)/14.0, 1])
    if (n==6):
        time = np.array([0.0, \
                         0.5-np.sqrt((7.0+2.0*np.sqrt(7.0))/21.0)/2.0, \
                         0.5-np.sqrt((7.0-2.0*np.sqrt(7.0))/21.0)/2.0, \
                         0.5+np.sqrt((7.0-2.0*np.sqrt(7.0))/21.0)/2.0, \
                         0.5+np.sqrt((7.0+2.0*np.sqrt(7.0))/21.0)/2.0, \
                         1.0])
    return time*tf

# solve with SciPy fsolve
def myFunction(z,*param):
    n = param[0]
    m = param[1]
    # rename z as x and xdot variables
    x = np.empty(n-1)
    xdot = np.empty(n-1)
    x[0:n-1] = z[0:n-1]
    xdot[0:n-1] = z[n-1:m]

    # initial condition (x0)
    x0 = 0.0
    # input parameter (u)
    u = 4.0
    # final time
    tn = tf

    # function evaluation residuals
    F = np.empty(m)
    # nonlinear differential equations at each node
    # 5 dx/dt = -x^2 + u
    F[0:n-1] = 5.0 * xdot[0:n-1] + x[0:n-1]**2 - u
    # collocation equations
    # tn * NC * xdot = x - x0
    NC = colloc(n)
    F[n-1:m] = tn * np.dot(NC,xdot) - x + x0 * np.ones(n-1)
    return F

sol_py = np.empty(5) # store 5 results
for i in range(2,7):
    n = i
    m = (i-1)*2
    zGuess = np.ones(m)
    z = fsolve(myFunction,zGuess,args=(n,m))
    # add to plot
    yc = np.insert(z[0:n-1],0,0)
    plt.plot(tc(n),yc,'o',markersize=10,label='Nodes = '+str(i))
    # store just the last x[n] value
    sol_py[i-2] = z[n-2]
plt.legend(loc='best')

# ----------------------------------------------------
# Approach #2 - Write model in APMonitor and let
#   modeling language create the collocation equations
# ----------------------------------------------------
# load GEKKO
from gekko import GEKKO

sol_apm = np.empty(5) # store 5 results
i = 0
for nodes in range(2,7):
    m = GEKKO(remote=False)

    u = m.Param(value=4)
    x = m.Var(value=0)
    m.Equation(5*x.dt() == -x**2 + u)

    m.time = [0,tf]

    m.options.imode = 4
    m.options.time_shift = 0
    m.options.nodes = nodes

    m.solve() # solve problem
    sol_apm[i] = x.value[-1] # store solution (last point)
    i += 1

# print the solutions
print(sol_py)
print(sol_apm)

# show plot
plt.ylabel('x(t)')
plt.xlabel('time')
plt.show()

You can define variables with the same name (such as x) or use m.Array(m.Var,n) to define the variables. One thing to look at is the model file by opening the run folder with m.open_folder() before you send the m.solve() command. Look at the .apm file in that folder with a text editor.


问:
Add a list of variables in a powershell script
I am sure this is obvious but for the life of me I can not find the information.  Many postings on splitting output to multiple lines, but I can't find information on using Multiple lines as input.

I often create text files with lists of variables then use $servers=GC servers.txt and use a "For each" loop to process them.  There has to be a way to just include that list in the script.

For example if I normally create a 'servers.txt' consisting of:

server1

server2

server3....

Is it possible to list those server in the script it self.  Something like (and I know this doesn't work as writen:

```<code>$servers= @(
    Server1
    Server2
    Server3
    )
</code>```

UPDATE

I know I could separate them in to quotes and add commas but that is specifically what I am trying to avoid.  If I copy a list of servers from a spread sheet with right click copy, I'd like to be able to paste it in my script without having to add commas and single quotes.  Right now I avoid this by dumping the contents in to a text file then use Get-Content to import it, but I am trying to find a way to bypass that extra step and just be able to paste it in the script then click run without having to alter the text.

答:
From the comments, it appears you want to copy and paste a list of systems into a script and have it process as an array. One way to do this is using here-strings.

```<code>$servers = @'
server1
server2
server3
'@ -split '\r?\n'
</code>```

Output

```<code>$servers
server1
server2
server3
$servers.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String[]                                 System.Array
</code>```

Just paste your server list between the @''@ lines. Keep in mind that @' and '@ should be on lines with no other values.

See About Quoting Rules for information on here-strings.

Body:
I am sure this is obvious but for the life of me I can not find the information.  Many postings on splitting output to multiple lines, but I can't find information on using Multiple lines as input.

I often create text files with lists of variables then use $servers=GC servers.txt and use a "For each" loop to process them.  There has to be a way to just include that list in the script.

For example if I normally create a 'servers.txt' consisting of:

server1

server2

server3....

Is it possible to list those server in the script it self.  Something like (and I know this doesn't work as writen:

$servers= @(
    Server1
    Server2
    Server3
    )

UPDATE

I know I could separate them in to quotes and add commas but that is specifically what I am trying to avoid.  If I copy a list of servers from a spread sheet with right click copy, I'd like to be able to paste it in my script without having to add commas and single quotes.  Right now I avoid this by dumping the contents in to a text file then use Get-Content to import it, but I am trying to find a way to bypass that extra step and just be able to paste it in the script then click run without having to alter the text.

Body:
From the comments, it appears you want to copy and paste a list of systems into a script and have it process as an array. One way to do this is using here-strings.

$servers = @'
server1
server2
server3
'@ -split '\r?\n'

Output

$servers
server1
server2
server3
$servers.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String[]                                 System.Array

Just paste your server list between the @''@ lines. Keep in mind that @' and '@ should be on lines with no other values.

See About Quoting Rules for information on here-strings.


问:
Tax Amount is not updating in sales order when creating programmatically
Tax Amount field is not holding the value when we try to create the sales order programmatically. I'm using the manual tax. From screen it is working fine but while trying to create from code the value is not taking, even I'm trying to provide the values to the field after the order creation it is reverting to 0.

Here the code that i'm using to update the Tax Amount.

```<code>orderTax.CuryTaxAmt = tax;
sOOrderEntry.Taxes.Cache.Update(orderTax);
sOOrderEntry.Document.SetValueExt<SOOrder.curyTaxTotal>(sOOrderEntry.Document.Current, tax);
orderTotal = sOOrderEntry.Document.Current.OrderTotal + orderTax.CuryTaxAmt;
sOOrderEntry.Document.SetValueExt<SOOrder.curyOrderTotal>(sOOrderEntry.Document.Current, orderTotal);
sOOrderEntry.Document.Cache.Update(sOOrderEntry.Document.Current);
</code>```

答:
Updating tax amount in the sales order field is not a good idea.
CuryTaxTotal field in sales order is calculated field. It is calculated from SOTaxTran lines.
So, in order to update tax amount in sales order you actually need to insert SOTaxTran lines into Taxes view of the SOOrderEntry graph.

Something like that:

```<code>//indicate that taxes are inserted in manual mode
TaxAttribute.SetTaxCalc<SOLine.taxCategoryID>(graph.Transactions.Cache, null, TaxCalc.ManualCalc);
// insert SOTaxTran
SOTaxTran newTaxTran= new SOTaxTran();
newTaxTran.TaxRate = 0.1; //put your actual values here
newTaxTran.CuryTaxableAmt =  100; //put your actual values here
newTaxTran.CuryTaxAmt =  10; //put your actual values here
var taxTran = graph.Taxes.Insert(newTaxTran);
</code>```

Body:
Tax Amount field is not holding the value when we try to create the sales order programmatically. I'm using the manual tax. From screen it is working fine but while trying to create from code the value is not taking, even I'm trying to provide the values to the field after the order creation it is reverting to 0.

Here the code that i'm using to update the Tax Amount.

orderTax.CuryTaxAmt = tax;
sOOrderEntry.Taxes.Cache.Update(orderTax);
sOOrderEntry.Document.SetValueExt<SOOrder.curyTaxTotal>(sOOrderEntry.Document.Current, tax);
orderTotal = sOOrderEntry.Document.Current.OrderTotal + orderTax.CuryTaxAmt;
sOOrderEntry.Document.SetValueExt<SOOrder.curyOrderTotal>(sOOrderEntry.Document.Current, orderTotal);
sOOrderEntry.Document.Cache.Update(sOOrderEntry.Document.Current);

Body:
Updating tax amount in the sales order field is not a good idea.
CuryTaxTotal field in sales order is calculated field. It is calculated from SOTaxTran lines.
So, in order to update tax amount in sales order you actually need to insert SOTaxTran lines into Taxes view of the SOOrderEntry graph.

Something like that:

//indicate that taxes are inserted in manual mode
TaxAttribute.SetTaxCalc<SOLine.taxCategoryID>(graph.Transactions.Cache, null, TaxCalc.ManualCalc);
// insert SOTaxTran
SOTaxTran newTaxTran= new SOTaxTran();
newTaxTran.TaxRate = 0.1; //put your actual values here
newTaxTran.CuryTaxableAmt =  100; //put your actual values here
newTaxTran.CuryTaxAmt =  10; //put your actual values here
var taxTran = graph.Taxes.Insert(newTaxTran);


问:
Centroid tracking for background subtracking with python-opencv
I am doing object tacking using backgoundsubtraction and i applied this tutorial https://www.pyimagesearch.com/2018/07/23/simple-object-tracking-with-opencv/ for live stream video its giving output properly. but when i gave sequence of image frames all the ID is being printed on the new image and along with old ID and OLD id is not being removed

the next frame will get the new ID and the previous id will also be printed on it
How do i fix this

```<code>def detection():
    backsub = cv2. createBackgroundSubtractorMOG2(128, cv2.THRESH_BINARY, 1)
    minarea = 50
    counter = 0
    counter = 0
    counter1 = 0
    ct = CentroidTracker()
    rects = []
    #cx = 0
    #cy = 0
    (H, W) = (None, None)
    filenames = [img for img in glob.glob("img location/*.jpg")]
    filenames.sort()
    print("start2")
    for img in filenames:
        frame = cv2.imread(img)

        t = time.localtime()
        timestamp = int(round(time.time() * 1000))
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        blur = cv2.medianBlur(frame, 21)
        #blur = cv2.GaussianBlur(frame, (21,21), 0)
        fgmask = backsub.apply(blur)
        fgmask[fgmask==127] = 0
        thresh = cv2.threshold(fgmask, 25, 255, cv2.THRESH_BINARY)[1]
        thresh = cv2.dilate(thresh, None, iterations=4)
        #cv2.line(frame, (138, 265), (344, 640), (0, 255, 0),1)
        cv2.line(frame, (103, 209), (332, 607), (0, 255, 0),1)

        #pts = np.array([[0, 640], [0, 264], [138, 265], [344, 640]], np.int32)
        pts = np.array([[0, 607], [0, 215], [103, 209], [332, 607]], np.int32)

        #bbPath = mplPath.Path(np.array([[0, 640], [0, 264], [138, 265], [344, 640]]))
        bbPath = mplPath.Path(np.array([[0, 607], [0, 215], [103, 209], [332, 607]]))

        frame = cv2.polylines(frame, [pts], True, (0, 255,0))
        cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        cnts = imutils.grab_contours(cnts)
        for c in cnts:
            M = cv2.moments(c)
            A = cv2.contourArea(c)
            if cv2.contourArea(c) >= minarea:
                (x, y, w, h) = cv2.boundingRect(c)
                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
                rectang = [x,y,(x + w),(y + h)]

                rects.append(rectang)

                if M["m00"] != 0:
                    cx = int(M["m10"] / M["m00"])
                    cy = int(M["m01"] / M["m00"])
                    cv2.circle(frame, (cx, cy),5, (255, 255, 255), -1)
                    centroid1 = (cx, cy)

                    cv2.imwrite("Writelocation/I%s.jpg"%timestamp,frame)

                    print("Area is : ",A)
        objects = ct.update(rects)
        if object is not None:
            for (objectID, centroid) in objects.items():
            # draw both the ID of the object and the centroid of the
            # object on the output frame
                text = "ID:{}".format(objectID)
                cv2.putText(frame, text, (centroid[0], centroid[1] - 10),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
                cv2.circle(frame, (centroid[0], centroid[1]), 4, (0, 255, 0), -1)
                cv2.imshow("fgmask", thresh)
                cv2.imshow("img",frame)

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
            cv2.imwrite("Writelocation/V%s.jpg"%timestamp,frame)

    print("Done")
detection()
</code>```

Above is the BackgroundSubtraction pgm
Below is the Centroid tracking pgm

```<code>    from scipy.spatial import distance as dist
from collections import OrderedDict
import numpy as np

class CentroidTracker():
    def __init__(self, maxDisappeared=3):
        self.nextObjectID = 0
        self.objects = OrderedDict()
        self.disappeared = OrderedDict()

        self.maxDisappeared = maxDisappeared

    def register(self, centroid):
        self.objects[self.nextObjectID] = centroid
        self.disappeared[self.nextObjectID] = 0
        self.nextObjectID += 1

    def deregister(self, objectID):
        del self.objects[objectID]
        del self.disappeared[objectID]

    def update(self, rects):
        if len(rects) == 0:
            for objectID in list(self.disappeared.keys()):
                self.disappeared[objectID] += 1

                if self.disappeared[objectID] > self.maxDisappeared:
                    self.deregister(objectID)

            return self.objects

        inputCentroids = np.zeros((len(rects), 2), dtype="int")

        for (i, (startX, startY, endX, endY)) in enumerate(rects):
            cX = int((startX + endX) / 2.0)
            cY = int((startY + endY) / 2.0)
            inputCentroids[i] = (cX, cY)

        if len(self.objects) == 0:
            for i in range(0, len(inputCentroids)):
                self.register(inputCentroids[i])

        else:
            objectIDs = list(self.objects.keys())
            objectCentroids = list(self.objects.values())

            D = dist.cdist(np.array(objectCentroids), inputCentroids)

            rows = D.min(axis=1).argsort()

            cols = D.argmin(axis=1)[rows]

            usedRows = set()
            usedCols = set()

            for (row, col) in zip(rows, cols):
                if row in usedRows or col in usedCols:
                    continue

                objectID = objectIDs[row]
                self.objects[objectID] = inputCentroids[col]
                self.disappeared[objectID] = 0

                usedRows.add(row)
                usedCols.add(col)

            unusedRows = set(range(0, D.shape[0])).difference(usedRows)
            unusedCols = set(range(0, D.shape[1])).difference(usedCols)

            if D.shape[0] >= D.shape[1]:
                for row in unusedRows:
                    objectID = objectIDs[row]
                    self.disappeared[objectID] += 1

                    if self.disappeared[objectID] > self.maxDisappeared:
                        self.deregister(objectID)

            else:
                for col in unusedCols:
                    self.register(inputCentroids[col])

        return self.objects
</code>```

答: Try placing the line rects = [] in detection() inside the first for loop, i.e. after the line for img in filenames:

Body:
I am doing object tacking using backgoundsubtraction and i applied this tutorial https://www.pyimagesearch.com/2018/07/23/simple-object-tracking-with-opencv/ for live stream video its giving output properly. but when i gave sequence of image frames all the ID is being printed on the new image and along with old ID and OLD id is not being removed

the next frame will get the new ID and the previous id will also be printed on it
How do i fix this

def detection():
    backsub = cv2. createBackgroundSubtractorMOG2(128, cv2.THRESH_BINARY, 1)
    minarea = 50
    counter = 0
    counter = 0
    counter1 = 0
    ct = CentroidTracker()
    rects = []
    #cx = 0
    #cy = 0
    (H, W) = (None, None)
    filenames = [img for img in glob.glob("img location/*.jpg")]
    filenames.sort()
    print("start2")
    for img in filenames:
        frame = cv2.imread(img)

        t = time.localtime()
        timestamp = int(round(time.time() * 1000))
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        blur = cv2.medianBlur(frame, 21)
        #blur = cv2.GaussianBlur(frame, (21,21), 0)
        fgmask = backsub.apply(blur)
        fgmask[fgmask==127] = 0
        thresh = cv2.threshold(fgmask, 25, 255, cv2.THRESH_BINARY)[1]
        thresh = cv2.dilate(thresh, None, iterations=4)
        #cv2.line(frame, (138, 265), (344, 640), (0, 255, 0),1)
        cv2.line(frame, (103, 209), (332, 607), (0, 255, 0),1)

        #pts = np.array([[0, 640], [0, 264], [138, 265], [344, 640]], np.int32)
        pts = np.array([[0, 607], [0, 215], [103, 209], [332, 607]], np.int32)

        #bbPath = mplPath.Path(np.array([[0, 640], [0, 264], [138, 265], [344, 640]]))
        bbPath = mplPath.Path(np.array([[0, 607], [0, 215], [103, 209], [332, 607]]))

        frame = cv2.polylines(frame, [pts], True, (0, 255,0))
        cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        cnts = imutils.grab_contours(cnts)
        for c in cnts:
            M = cv2.moments(c)
            A = cv2.contourArea(c)
            if cv2.contourArea(c) >= minarea:
                (x, y, w, h) = cv2.boundingRect(c)
                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
                rectang = [x,y,(x + w),(y + h)]

                rects.append(rectang)

                if M["m00"] != 0:
                    cx = int(M["m10"] / M["m00"])
                    cy = int(M["m01"] / M["m00"])
                    cv2.circle(frame, (cx, cy),5, (255, 255, 255), -1)
                    centroid1 = (cx, cy)

                    cv2.imwrite("Writelocation/I%s.jpg"%timestamp,frame)

                    print("Area is : ",A)
        objects = ct.update(rects)
        if object is not None:
            for (objectID, centroid) in objects.items():
            # draw both the ID of the object and the centroid of the
            # object on the output frame
                text = "ID:{}".format(objectID)
                cv2.putText(frame, text, (centroid[0], centroid[1] - 10),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
                cv2.circle(frame, (centroid[0], centroid[1]), 4, (0, 255, 0), -1)
                cv2.imshow("fgmask", thresh)
                cv2.imshow("img",frame)

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
            cv2.imwrite("Writelocation/V%s.jpg"%timestamp,frame)

    print("Done")
detection()

Above is the BackgroundSubtraction pgm
Below is the Centroid tracking pgm

    from scipy.spatial import distance as dist
from collections import OrderedDict
import numpy as np

class CentroidTracker():
    def __init__(self, maxDisappeared=3):
        self.nextObjectID = 0
        self.objects = OrderedDict()
        self.disappeared = OrderedDict()

        self.maxDisappeared = maxDisappeared

    def register(self, centroid):
        self.objects[self.nextObjectID] = centroid
        self.disappeared[self.nextObjectID] = 0
        self.nextObjectID += 1

    def deregister(self, objectID):
        del self.objects[objectID]
        del self.disappeared[objectID]

    def update(self, rects):
        if len(rects) == 0:
            for objectID in list(self.disappeared.keys()):
                self.disappeared[objectID] += 1

                if self.disappeared[objectID] > self.maxDisappeared:
                    self.deregister(objectID)

            return self.objects

        inputCentroids = np.zeros((len(rects), 2), dtype="int")

        for (i, (startX, startY, endX, endY)) in enumerate(rects):
            cX = int((startX + endX) / 2.0)
            cY = int((startY + endY) / 2.0)
            inputCentroids[i] = (cX, cY)

        if len(self.objects) == 0:
            for i in range(0, len(inputCentroids)):
                self.register(inputCentroids[i])

        else:
            objectIDs = list(self.objects.keys())
            objectCentroids = list(self.objects.values())

            D = dist.cdist(np.array(objectCentroids), inputCentroids)

            rows = D.min(axis=1).argsort()

            cols = D.argmin(axis=1)[rows]

            usedRows = set()
            usedCols = set()

            for (row, col) in zip(rows, cols):
                if row in usedRows or col in usedCols:
                    continue

                objectID = objectIDs[row]
                self.objects[objectID] = inputCentroids[col]
                self.disappeared[objectID] = 0

                usedRows.add(row)
                usedCols.add(col)

            unusedRows = set(range(0, D.shape[0])).difference(usedRows)
            unusedCols = set(range(0, D.shape[1])).difference(usedCols)

            if D.shape[0] >= D.shape[1]:
                for row in unusedRows:
                    objectID = objectIDs[row]
                    self.disappeared[objectID] += 1

                    if self.disappeared[objectID] > self.maxDisappeared:
                        self.deregister(objectID)

            else:
                for col in unusedCols:
                    self.register(inputCentroids[col])

        return self.objects


问:
Implementation of Cross-validation
I am confused since many individuals have their own approach to apply the cross-validation. For instance, some apply it on the whole dataset and some apply it on the training set.

My question is whether the below code is appropriate to implement cross-validation and make predictions from such model while having Cross-validation being applied?

```<code>from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import KFold

model= GradientBoostingClassifier(n_estimators= 10,max_depth = 10, random_state = 0)#sepcifying the model
cv = KFold(n_splits=5, shuffle=True)

from sklearn.model_selection import cross_val_predict
from sklearn.model_selection import cross_val_score

#X -the whole dataset
#y - the whole dataset but target attributes only

y_pred = cross_val_predict(model, X, y, cv=cv)
scores = cross_val_score(model, X, y, cv=cv)
</code>```

答:
You need to have a test set to evaluate performance on completely unseen data even for cross validation. Performance tuning should not be done on this test set to avoid data leakage.

Split data into two segments train and test. There are various CV methods such as K-Fold, Stratified K-Fold etc. Visualization and further reading material here,

https://scikit-learn.org/stable/auto_examples/model_selection/plot_cv_indices.html

https://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html

In K-Fold CV training data is split into K sets. Then for each fold, K-1 of the fold is trained and the remaining one is used for performance evaluation.

The image and further detail about cross validation, train/validation/test split etc. can be found here.

https://scikit-learn.org/stable/modules/cross_validation.html

Visualization of K-Fold cross validation for 3 classes,

Title: Implementation of Cross-validation

Body:
I am confused since many individuals have their own approach to apply the cross-validation. For instance, some apply it on the whole dataset and some apply it on the training set.

My question is whether the below code is appropriate to implement cross-validation and make predictions from such model while having Cross-validation being applied?

from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import KFold

model= GradientBoostingClassifier(n_estimators= 10,max_depth = 10, random_state = 0)#sepcifying the model
cv = KFold(n_splits=5, shuffle=True)

from sklearn.model_selection import cross_val_predict
from sklearn.model_selection import cross_val_score

#X -the whole dataset
#y - the whole dataset but target attributes only

y_pred = cross_val_predict(model, X, y, cv=cv)
scores = cross_val_score(model, X, y, cv=cv)


问:
Get Complete data on dropdown in web site with using macro
normally I use an excel chart to upload my data to website. but I realized that in time new additions can be added to a dropdown and unfortunately, i dont know is there anything added or not. So I want to add refresh button to my excel sheet to refresh data inside my excel and get data from website dropdown menu.
below you may find the code in web site. by the way I cannot share the link because it is behind the firewall and credentials. so here is the code

```<code>        <select name="ddfener" id="ddlfener" tabindex="2" class="normalText">
    <option value="0">Select a fener....</option>
    <option value="81ca032h">ahmet</option>
    <option value="345">mehmet</option>
    <option value="123">ayse</option>

</code>```

I need to download this data like

```<code> 81ca032h  ahmet
 345       mehmet
 123       ayse
</code>```

thanks

答:
You have to adjust the macro for the values read out so that they end up in the right places in your Excel table. Everything else is in the comments of the macro:</p>

```<code>Sub ReadDropdownValues()

  Dim browser As Object
  Dim url As String
  Dim nodeDropdown As Object
  Dim nodesOption As Object
  Dim optionTagNo As Long
  'Only for this demo
  'You write the single readed
  'values to your Excel table
  Dim result As String

  'Place your internal url here
  url = "file:///E:/testDropdown.htm"

  'Initialize Internet Explorer, set visibility,
  'call URL and wait until page is fully loaded
  '
  'This could be problematic on the intranet due to security guidelines
  'Set browser = CreateObject("InternetExplorer.Application")
  '
  'Try this instead to initialize the IE
  Set browser = GetObject("new:{D5E8041D-920F-45e9-B8FB-B1DEB82C6E5E}")
  browser.Visible = False 'Set to 'True' to see the IE
  browser.navigate url
  Do Until browser.ReadyState = 4: DoEvents: Loop

  'Get dropdown html structure
  On Error Resume Next
  Set nodeDropdown = browser.document.getElementByID("ddlfener")
  On Error GoTo 0

  'Check if object 'nodeDropdown' was build
  If Not nodeDropdown Is Nothing Then
    'Create node collection of option tags from object 'nodeDropdown'
    Set nodesOption = nodeDropdown.getElementsByTagName("option")

    'Loop through all option tags from, the second one
    '(The first one is only the placeholder 'Select a fener....')
    For optionTagNo = 1 To nodesOption.Length - 1
      'Get the value of the attribute 'value'
      result = result & Trim(nodesOption(optionTagNo).getAttribute("value"))
      'Insert tab only for demo string
      result = result & Chr(9)
      'Get dropdown value
      result = result & Trim(nodesOption(optionTagNo).innertext)
      'Insert new line only for demo string
      result = result & Chr(13)
    Next optionTagNo
  Else
    'If object 'nodeDropdown' wasn't build
    result = "Dropdown not found"
  End If

  'Clean up
  browser.Quit
  Set browser = Nothing
  Set nodeDropdown = Nothing
  Set nodesOption = Nothing

  'Show demo result
  MsgBox result
End Sub
</code>```

Body:
normally I use an excel chart to upload my data to website. but I realized that in time new additions can be added to a dropdown and unfortunately, i dont know is there anything added or not. So I want to add refresh button to my excel sheet to refresh data inside my excel and get data from website dropdown menu.
below you may find the code in web site. by the way I cannot share the link because it is behind the firewall and credentials. so here is the code

        <select name="ddfener" id="ddlfener" tabindex="2" class="normalText">
    <option value="0">Select a fener....</option>
    <option value="81ca032h">ahmet</option>
    <option value="345">mehmet</option>
    <option value="123">ayse</option>

I need to download this data like

 81ca032h  ahmet
 345       mehmet
 123       ayse

thanks

Body:
You have to adjust the macro for the values read out so that they end up in the right places in your Excel table. Everything else is in the comments of the macro:

Sub ReadDropdownValues()

  Dim browser As Object
  Dim url As String
  Dim nodeDropdown As Object
  Dim nodesOption As Object
  Dim optionTagNo As Long
  'Only for this demo
  'You write the single readed
  'values to your Excel table
  Dim result As String

  'Place your internal url here
  url = "file:///E:/testDropdown.htm"

  'Initialize Internet Explorer, set visibility,
  'call URL and wait until page is fully loaded
  '
  'This could be problematic on the intranet due to security guidelines
  'Set browser = CreateObject("InternetExplorer.Application")
  '
  'Try this instead to initialize the IE
  Set browser = GetObject("new:{D5E8041D-920F-45e9-B8FB-B1DEB82C6E5E}")
  browser.Visible = False 'Set to 'True' to see the IE
  browser.navigate url
  Do Until browser.ReadyState = 4: DoEvents: Loop

  'Get dropdown html structure
  On Error Resume Next
  Set nodeDropdown = browser.document.getElementByID("ddlfener")
  On Error GoTo 0

  'Check if object 'nodeDropdown' was build
  If Not nodeDropdown Is Nothing Then
    'Create node collection of option tags from object 'nodeDropdown'
    Set nodesOption = nodeDropdown.getElementsByTagName("option")

    'Loop through all option tags from, the second one
    '(The first one is only the placeholder 'Select a fener....')
    For optionTagNo = 1 To nodesOption.Length - 1
      'Get the value of the attribute 'value'
      result = result & Trim(nodesOption(optionTagNo).getAttribute("value"))
      'Insert tab only for demo string
      result = result & Chr(9)
      'Get dropdown value
      result = result & Trim(nodesOption(optionTagNo).innertext)
      'Insert new line only for demo string
      result = result & Chr(13)
    Next optionTagNo
  Else
    'If object 'nodeDropdown' wasn't build
    result = "Dropdown not found"
  End If

  'Clean up
  browser.Quit
  Set browser = Nothing
  Set nodeDropdown = Nothing
  Set nodesOption = Nothing

  'Show demo result
  MsgBox result
End Sub


问:
Load image from URL
I've searched and tried a couple different methods. I am coming up short on both. This is my current method:

```<code>package com.dop.mobilevforum;

import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.VideoView;

public class Vforum extends Activity
{
    private String imgPath = "http://mysite.com/mv/vfdemo1/slides/slide1.jpg";

    private ImageView slideHolder;

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.vforum);

        slideHolder = (ImageView) findViewById(R.id.slideHolder);

        Drawable drawable = LoadImageFromWebOperations(imgPath);
        slideHolder.setImageDrawable(drawable);
    }

    private Drawable LoadImageFromWebOperations(String url)
    {
        try
        {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        }
        catch (Exception e)
        {
            Log.w("LoadImageFromWebOperations",e.toString());
            return null;
        }
    }
}
</code>```

the LoadImageFromWebOperations method is returning a bitmap, so I know that part is working. It is the slideHolder.setImageDrawable(drawable); that I think it failing. This is my XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/mobile_vforum_bg">
    <ImageView
        android:id="@+id/slideHolder"
        android:layout_width="320px"
        android:layout_height="240px">
    </ImageView>
</FrameLayout>
</code>```

any ideas? I just get a black screen, no errors.

答:
Your code work, my dear friend your url don't work http://mysite.com/mv/vfdemo1/slides/slide1.jpg.

You can use this it works 100%, but your code also works

```<code>URL url = new URL("http://variable3.com/files/images/email-sig.jpg");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
slideHolder.setImageBitmap(bmp);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Load image from URL

Body:
I've searched and tried a couple different methods. I am coming up short on both. This is my current method:

package com.dop.mobilevforum;

import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.VideoView;

public class Vforum extends Activity
{
    private String imgPath = "http://mysite.com/mv/vfdemo1/slides/slide1.jpg";

    private ImageView slideHolder;

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.vforum);

        slideHolder = (ImageView) findViewById(R.id.slideHolder);

        Drawable drawable = LoadImageFromWebOperations(imgPath);
        slideHolder.setImageDrawable(drawable);
    }

    private Drawable LoadImageFromWebOperations(String url)
    {
        try
        {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        }
        catch (Exception e)
        {
            Log.w("LoadImageFromWebOperations",e.toString());
            return null;
        }
    }
}

the LoadImageFromWebOperations method is returning a bitmap, so I know that part is working. It is the slideHolder.setImageDrawable(drawable); that I think it failing. This is my XML:

<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/mobile_vforum_bg">
    <ImageView
        android:id="@+id/slideHolder"
        android:layout_width="320px"
        android:layout_height="240px">
    </ImageView>
</FrameLayout>

any ideas? I just get a black screen, no errors.

Body:
Your code work, my dear friend your url don't work http://mysite.com/mv/vfdemo1/slides/slide1.jpg.

You can use this it works 100%, but your code also works

URL url = new URL("http://variable3.com/files/images/email-sig.jpg");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
slideHolder.setImageBitmap(bmp);


问:
How does kube-proxy behave when it can't reach the master?
From what I've read about Kubernetes, if the master(s) die, the workers should still be able to function as normal (https://stackoverflow.com/a/39173007/281469), although no new scheduling will occur.

However, I've found this to not be the case when the master can also schedule worker pods. Take a 2-node cluster, where one node is a master and the other a worker, and the master has the taints removed:

If I shut down the master and docker exec into one of the containers on the worker I can see that:

```<code>nc -zv ip-of-pod 80
</code>```

succeeds, but

```<code>nc -zv ip-of-service 80
</code>```

fails half of the time. The Kubernetes version is v1.15.10, using iptables mode for kube-proxy.

I'm guessing that since the kube-proxy on the worker node can't connect to the apiserver, it will not remove the master node from the iptables rules.

Questions:

Is it expected behaviour that kube-proxy won't stop routing to pods on master nodes, or is there something "broken"?

Are any workarounds available for this kind of setup to allow the worker nodes to still function correctly?

I realise the best thing to do is separate the CP nodes but that's not viable for what I'm working on at the moment.

答: There is nothing inherent in Kubernetes that would cause this. The master node role is just for humans, and if you've removed the taints then the nodes are just normal nodes. That said, remember that usual rules about scheduling and resource requests apply so if your pods don't all fit then things wouldn't be scheduled. It's possible your Kubernetes deploy system set up more specialized firewall rules or similar around the control plane nodes, but that would be dependent on that system.

Body:
From what I've read about Kubernetes, if the master(s) die, the workers should still be able to function as normal (https://stackoverflow.com/a/39173007/281469), although no new scheduling will occur.

However, I've found this to not be the case when the master can also schedule worker pods. Take a 2-node cluster, where one node is a master and the other a worker, and the master has the taints removed:

If I shut down the master and docker exec into one of the containers on the worker I can see that:

nc -zv ip-of-pod 80

succeeds, but

nc -zv ip-of-service 80

fails half of the time. The Kubernetes version is v1.15.10, using iptables mode for kube-proxy.

I'm guessing that since the kube-proxy on the worker node can't connect to the apiserver, it will not remove the master node from the iptables rules.

Questions:

Is it expected behaviour that kube-proxy won't stop routing to pods on master nodes, or is there something "broken"?

Are any workarounds available for this kind of setup to allow the worker nodes to still function correctly?

I realise the best thing to do is separate the CP nodes but that's not viable for what I'm working on at the moment.


问:
Ionic 4 error showing on using component in 2 pages
I have created a loader component and i am trying to use in my pages. Problem is its working fine in one page but when i am using in other page its showing error of

component is part of the declarations of 2 modules: AppModule in

This is my first page category.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { LoaderComponent } from '../loader/loader.component';    //this is component i am using
import { IonicModule } from '@ionic/angular';

import { CategoryPageRoutingModule } from './category-routing.module';

import { CategoryPage } from './category.page';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    CategoryPageRoutingModule
  ],
  declarations: [CategoryPage, LoaderComponent]
})
export class CategoryPageModule {}
</code>```

My other mage login.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { LoaderComponent } from '../loader/loader.component'; //this is component

import { LoginPageRoutingModule } from './login-routing.module';

import { LoginPage } from './login.page';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    LoginPageRoutingModule,
  ],
  declarations: [LoginPage, LoaderComponent]
})
export class LoginPageModule {}
</code>```

Now if i am removing my component from second page its working fine. And in app.module.ts i have added my component in declaration array.

答:
I hope you are very well. You should think about creating a shared module, with this shared module you would have all your components/directives/pipes which you use around all the application.

Check this link

https://angular.io/guide/sharing-ngmodules

Body:
I have created a loader component and i am trying to use in my pages. Problem is its working fine in one page but when i am using in other page its showing error of

component is part of the declarations of 2 modules: AppModule in

This is my first page category.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { LoaderComponent } from '../loader/loader.component';    //this is component i am using
import { IonicModule } from '@ionic/angular';

import { CategoryPageRoutingModule } from './category-routing.module';

import { CategoryPage } from './category.page';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    CategoryPageRoutingModule
  ],
  declarations: [CategoryPage, LoaderComponent]
})
export class CategoryPageModule {}

My other mage login.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { LoaderComponent } from '../loader/loader.component'; //this is component

import { LoginPageRoutingModule } from './login-routing.module';

import { LoginPage } from './login.page';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    LoginPageRoutingModule,
  ],
  declarations: [LoginPage, LoaderComponent]
})
export class LoginPageModule {}

Now if i am removing my component from second page its working fine. And in app.module.ts i have added my component in declaration array.


问:
graphql-codegen not running with config file
In my package.json file I've got script entry that runs graphql-codegen but it complains that the --config argument is invalid:

```<code>$> yarn gen
yarn run v1.21.1
$ graphql-codegen --config codegen.yml
Error: Unknown argument: config
...
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

Since I believe the default file name is codegen.yml anyway, I try to run it with out that argument and nothing gets generated:

```<code>$> yarn graphql-codegen
yarn run v1.21.1
$ /home/aaron/projects/my_app/node_modules/.bin/graphql-codegen
Done in 0.17s.
</code>```

Any ideas?

答:
Ok, I'm not sure exactly what I did to fix this. I believe that I had also installed graphql-codegen globally and tried to uninstall it with sudo npm uninstall graphql-codegen which removed a bunch of packages but the executable still exists:

```<code>$>which graphql-codegen
/usr/bin/graphql-codegen
</code>```

However I decided to run yarn graphql-codegen init on a whim to see if init was valid and because I couldn't remember if I hadn't tried that already. I got the set up questions like normal so I ctrl+C'ed and just ran yarn graphql-codegen and it worked! Then I ran yarn graphql-codegen --watch to test that it took options and that also worked.

If anyone gets this issue, I hope these tips help you.

Body:
In my package.json file I've got script entry that runs graphql-codegen but it complains that the --config argument is invalid:

$> yarn gen
yarn run v1.21.1
$ graphql-codegen --config codegen.yml
Error: Unknown argument: config
...
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Since I believe the default file name is codegen.yml anyway, I try to run it with out that argument and nothing gets generated:

$> yarn graphql-codegen
yarn run v1.21.1
$ /home/aaron/projects/my_app/node_modules/.bin/graphql-codegen
Done in 0.17s.

Any ideas?

Body:
Ok, I'm not sure exactly what I did to fix this. I believe that I had also installed graphql-codegen globally and tried to uninstall it with sudo npm uninstall graphql-codegen which removed a bunch of packages but the executable still exists:

$>which graphql-codegen
/usr/bin/graphql-codegen

However I decided to run yarn graphql-codegen init on a whim to see if init was valid and because I couldn't remember if I hadn't tried that already. I got the set up questions like normal so I ctrl+C'ed and just ran yarn graphql-codegen and it worked! Then I ran yarn graphql-codegen --watch to test that it took options and that also worked.

If anyone gets this issue, I hope these tips help you.