问:
How to Combine CSV files according to some conditions in pandas python?
I have 4 CSV Files:
CSV Files Picture

I want to combine the 4 files into one data frame. I have to Use the Invoices.Customer_ID and Customers.ID.  When combining, I also have to make sure that the result set only contains customers and articles for which there are invoices and invoice items.

I have this simple code that reads the CSV file and displays the data.

```<code>from datetime import date, datetime
import os
import pandas as pd

article_csv = pd.read_csv('Input/Artikel.csv')
Invoices_items_csv = pd.read_csv('Input/Rechnungen_Positionen.csv')
Customers_csv = pd.read_csv('Input/Kunden.csv')
Invoices_csv = pd.read_csv('Input/Rechnungen.csv')
</code>```

Can someone help me here to achieve this goal? Thanks in advance

答:
According to this post, you can merge dataframes per column-definitions like this:

```<code>df = pd.merge(df1, df2, on=['document_id','item_id'])
</code>```

So for your case, i think you would have to do this from left to right, meaning from article_csv to Invoices_items_csv to Customers_csv etc., because you can only merge 2 dataframes at a time. Keep in mind that this represents an inner-join, meaning only data with the specified columns existing on both dataframes will be merged, which is what you described. Then, you simply can use ID for the first 3 dataframes, and ID and Invoice_ID for the last merge.

```<code>import pandas as pd

# sample data
article_csv = pd.DataFrame({
    "ID": [1, 2, 3],
    "Code": ["abc", "def", "elk"],
    "Discount": [2, None, 1.5]
})

Customers_csv = pd.DataFrame({
    "ID": [1, 2, 3, 4, 5, 6, 7, 8],
    "Country": ['AT']*8
})

Invoices_csv = pd.DataFrame({
    "ID": [1, 3],
    "Customer_id": [7, 8]
})

Invoices_items_csv = pd.DataFrame({
    "Invoice_ID": [1, 1, 3, 3],
    "Quantity": [5, 2, 7, 8]
})

# merge dataframes
merged_df = pd.merge(Customers_csv, article_csv, on=["ID", "ID"])
merged_df = pd.merge(merged_df, Invoices_csv, on=["ID", "ID"])
merged_df = pd.merge(merged_df, Invoices_items_csv, left_on="ID", right_on="Invoice_ID")
</code>```

Body:
I have 4 CSV Files:
CSV Files Picture

I want to combine the 4 files into one data frame. I have to Use the Invoices.Customer_ID and Customers.ID.  When combining, I also have to make sure that the result set only contains customers and articles for which there are invoices and invoice items.

I have this simple code that reads the CSV file and displays the data.

from datetime import date, datetime
import os
import pandas as pd

article_csv = pd.read_csv('Input/Artikel.csv')
Invoices_items_csv = pd.read_csv('Input/Rechnungen_Positionen.csv')
Customers_csv = pd.read_csv('Input/Kunden.csv')
Invoices_csv = pd.read_csv('Input/Rechnungen.csv')

Can someone help me here to achieve this goal? Thanks in advance

Body:
According to this post, you can merge dataframes per column-definitions like this:

df = pd.merge(df1, df2, on=['document_id','item_id'])

So for your case, i think you would have to do this from left to right, meaning from article_csv to Invoices_items_csv to Customers_csv etc., because you can only merge 2 dataframes at a time. Keep in mind that this represents an inner-join, meaning only data with the specified columns existing on both dataframes will be merged, which is what you described. Then, you simply can use ID for the first 3 dataframes, and ID and Invoice_ID for the last merge.

import pandas as pd

# sample data
article_csv = pd.DataFrame({
    "ID": [1, 2, 3],
    "Code": ["abc", "def", "elk"],
    "Discount": [2, None, 1.5]
})

Customers_csv = pd.DataFrame({
    "ID": [1, 2, 3, 4, 5, 6, 7, 8],
    "Country": ['AT']*8
})

Invoices_csv = pd.DataFrame({
    "ID": [1, 3],
    "Customer_id": [7, 8]
})

Invoices_items_csv = pd.DataFrame({
    "Invoice_ID": [1, 1, 3, 3],
    "Quantity": [5, 2, 7, 8]
})

# merge dataframes
merged_df = pd.merge(Customers_csv, article_csv, on=["ID", "ID"])
merged_df = pd.merge(merged_df, Invoices_csv, on=["ID", "ID"])
merged_df = pd.merge(merged_df, Invoices_items_csv, left_on="ID", right_on="Invoice_ID")


来源: stackexchange

问:
Connect QEMU-KVM VMs using vhost-user-client and ovs-dpdk
My goal is to connect two QEMU-KVM VMs on an overlay network. Each VM is running on a separate physical host and must have a static IP on the network 10.0.0.0/24. To achieve this goal, I want to use an OVS bridge with DPDK. I want to use the vhost-user-client protocol to connect the OVS bridge with the VMs.

My physical setup is the following: two physical machines equipped with a Mellanox ConnectX6-DX, and connected back-to-back (no physical switch). What I want to achieve is this:

```<code>+------------------+            +------------------+
| HOST_1           |            | HOST_2           |
|                  |            |                  |
|  +------------+  |            |  +------------+  |
|  | VM_1       |  |            |  | VM_2       |  |
|  |            |  |            |  |            |  |
|  | +--------+ |  |            |  | +--------+ |  |
|  | | ens_2  | |  |            |  | | ens_2  | |  |
|  | |10.0.0.1| |  |            |  | |10.0.0.2| |  |
|  +-+---+----+-+  |            |  +-+---+----+-+  |
|        |         |            |        |         |
|  vhost-client-1  |            |  vhost-client-1  |
|        |         |            |        |         |
|  +-----+------+  |            |  +-----+------+  |
|  |  bridge    |  |            |  |  bridge    |  |
|  |    br0     |  |            |  |    br0     |  |
|  |192.168.57.1|  |            |  |192.168.57.2|  |
|  +-----+------+  |            |  +-----+------+  |
|        |         |            |        |         |
|    +---+---      |            |    +---+---+     |
|    | dpdk0 |     |            |    | dpdk0 |     |
+----+---+--+------+            +----+---+---+-----+
         |                               |
         +-------------------------------+
</code>```

I successfully created the OVS bridge (here, br0) and the DPDK port (here, dpdk0). On each physical machine, I am able to ping the bridge on the other machine. Then, I created a vhost-user-client port and attached it to the bridge. On each guest, I assigned a static IP according to the above picture, and the ens2 interface is up.

However, at this point I am not able to ping VM2 from VM1 or vice-versa. It seems like no traffic is exchanged through the vhost-client port at all. Ping fails with the Destination Host Unreachable message.

Some useful information:

ovs-vsctl show

```<code>Bridge br0
        datapath_type: netdev
        Port br0
            Interface br0
                type: internal
        Port dpdk0
            Interface dpdk0
                type: dpdk
                options: {dpdk-devargs="0000:01:00.0"}
        Port vhost-client-1
            Interface vhost-client-1
                type: dpdkvhostuserclient
                options: {vhost-server-path="/tmp/vhost-client-1"}
    ovs_version: "2.16.1"
</code>```

ovs-vsctl -- --columns=name,ofport list Interface

```<code>name                : br0
ofport              : 65534

name                : dpdk0
ofport              : 6

name                : vhost-client-1
ofport              : 2
</code>```

ovs-ofctl dump-flows br0

```<code>cookie=0x0, duration=104.689s, table=0, n_packets=0, n_bytes=0, in_port="vhost-client-1" actions=output:dpdk0
cookie=0x0, duration=99.573s, table=0, n_packets=4, n_bytes=924, in_port=dpdk0 actions=output:"vhost-client-1"
</code>```

ovs-ofctl show br0

```<code>OFPT_FEATURES_REPLY (xid=0x2): dpid:0000b8cef64def2e
n_tables:254, n_buffers:0
capabilities: FLOW_STATS TABLE_STATS PORT_STATS QUEUE_STATS ARP_MATCH_IP
actions: output enqueue set_vlan_vid set_vlan_pcp strip_vlan mod_dl_src mod_dl_dst mod_nw_src mod_nw_dst mod_nw_tos mod_tp_src mod_tp_dst
 2(vhost-client-1): addr:00:00:00:00:00:00
     config:     0
     state:      LINK_DOWN
     speed: 0 Mbps now, 0 Mbps max
 6(dpdk0): addr:b8:ce:f6:4d:ef:2e
     config:     0
     state:      0
     current:    AUTO_NEG
     speed: 0 Mbps now, 0 Mbps max
 LOCAL(br0): addr:b8:ce:f6:4d:ef:2e
     config:     0
     state:      0
     current:    10MB-FD COPPER
     speed: 10 Mbps now, 0 Mbps max
OFPT_GET_CONFIG_REPLY (xid=0x4): frags=normal miss_send_len=0
</code>```

Libvirt XML configuration (relevant parts)

```<code><domain type='kvm'>
  <name>ubuntu-server</name>
  <devices>
    <emulator>/usr/bin/qemu-system-x86_64</emulator>
    <interface type='vhostuser'>
      <mac address='52:54:00:16:a5:76'/>
      <source type='unix' path='/tmp/vhost-client-1' mode='server'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
    </interface>
  </devices>
</domain>
</code>```

Which configuration option am I missing? I have followed several guides but still I am unable to route any traffic between my VMs.

I suspect that the problem is related to the LINK_DOWN status of the vhost-client-1 port as reported by the ovs-ofctl show command. I've tried to set that status as UP with the command ovs-ofctl mod-port br0 vhost-client-1 up. Even though the command did not fail, nothing changed.

Any thoughts?

答:
Eventually, I managed to solve my problem. Vipin's answer was useful, but did not solve the issue. The configuration option I was missing was the numa option within the cpu element.

I post the working configuration file just in case it is useful for other people. The first part is about memory backing (under the domain element):

```<code>  <memory unit='KiB'>[VM memory size]</memory>
  <currentMemory unit='KiB'>[VM memory size]</currentMemory>
  <memoryBacking>
    <hugepages>
      <page size='2048' unit='KiB'/>
    </hugepages>
    <locked/>
    <source type='file'/>
    <access mode='shared'/>
    <allocation mode='immediate'/>
    <discard/>
  </memoryBacking>
</code>```

But we also needed the numa configuration, even if our machine had just one processor:

```<code><cpu mode='custom' match='exact' check='full'>
    <model fallback='forbid'>qemu64</model>
    <feature policy='require' name='x2apic'/>
    <feature policy='require' name='hypervisor'/>
    <feature policy='require' name='lahf_lm'/>
    <feature policy='disable' name='svm'/>
    <numa>
      <cell id='0' cpus='0-1' memory='[VM memory size]' unit='KiB' memAccess='shared'/>
    </numa>
</cpu>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My goal is to connect two QEMU-KVM VMs on an overlay network. Each VM is running on a separate physical host and must have a static IP on the network 10.0.0.0/24. To achieve this goal, I want to use an OVS bridge with DPDK. I want to use the vhost-user-client protocol to connect the OVS bridge with the VMs.

My physical setup is the following: two physical machines equipped with a Mellanox ConnectX6-DX, and connected back-to-back (no physical switch). What I want to achieve is this:

+------------------+            +------------------+
| HOST_1           |            | HOST_2           |
|                  |            |                  |
|  +------------+  |            |  +------------+  |
|  | VM_1       |  |            |  | VM_2       |  |
|  |            |  |            |  |            |  |
|  | +--------+ |  |            |  | +--------+ |  |
|  | | ens_2  | |  |            |  | | ens_2  | |  |
|  | |10.0.0.1| |  |            |  | |10.0.0.2| |  |
|  +-+---+----+-+  |            |  +-+---+----+-+  |
|        |         |            |        |         |
|  vhost-client-1  |            |  vhost-client-1  |
|        |         |            |        |         |
|  +-----+------+  |            |  +-----+------+  |
|  |  bridge    |  |            |  |  bridge    |  |
|  |    br0     |  |            |  |    br0     |  |
|  |192.168.57.1|  |            |  |192.168.57.2|  |
|  +-----+------+  |            |  +-----+------+  |
|        |         |            |        |         |
|    +---+---      |            |    +---+---+     |
|    | dpdk0 |     |            |    | dpdk0 |     |
+----+---+--+------+            +----+---+---+-----+
         |                               |
         +-------------------------------+

I successfully created the OVS bridge (here, br0) and the DPDK port (here, dpdk0). On each physical machine, I am able to ping the bridge on the other machine. Then, I created a vhost-user-client port and attached it to the bridge. On each guest, I assigned a static IP according to the above picture, and the ens2 interface is up.

However, at this point I am not able to ping VM2 from VM1 or vice-versa. It seems like no traffic is exchanged through the vhost-client port at all. Ping fails with the Destination Host Unreachable message.

Some useful information:

ovs-vsctl show

Bridge br0
        datapath_type: netdev
        Port br0
            Interface br0
                type: internal
        Port dpdk0
            Interface dpdk0
                type: dpdk
                options: {dpdk-devargs="0000:01:00.0"}
        Port vhost-client-1
            Interface vhost-client-1
                type: dpdkvhostuserclient
                options: {vhost-server-path="/tmp/vhost-client-1"}
    ovs_version: "2.16.1"

ovs-vsctl -- --columns=name,ofport list Interface

name                : br0
ofport              : 65534

name                : dpdk0
ofport              : 6

name                : vhost-client-1
ofport              : 2

ovs-ofctl dump-flows br0

cookie=0x0, duration=104.689s, table=0, n_packets=0, n_bytes=0, in_port="vhost-client-1" actions=output:dpdk0
cookie=0x0, duration=99.573s, table=0, n_packets=4, n_bytes=924, in_port=dpdk0 actions=output:"vhost-client-1"

ovs-ofctl show br0

OFPT_FEATURES_REPLY (xid=0x2): dpid:0000b8cef64def2e
n_tables:254, n_buffers:0
capabilities: FLOW_STATS TABLE_STATS PORT_STATS QUEUE_STATS ARP_MATCH_IP
actions: output enqueue set_vlan_vid set_vlan_pcp strip_vlan mod_dl_src mod_dl_dst mod_nw_src mod_nw_dst mod_nw_tos mod_tp_src mod_tp_dst
 2(vhost-client-1): addr:00:00:00:00:00:00
     config:     0
     state:      LINK_DOWN
     speed: 0 Mbps now, 0 Mbps max
 6(dpdk0): addr:b8:ce:f6:4d:ef:2e
     config:     0
     state:      0
     current:    AUTO_NEG
     speed: 0 Mbps now, 0 Mbps max
 LOCAL(br0): addr:b8:ce:f6:4d:ef:2e
     config:     0
     state:      0
     current:    10MB-FD COPPER
     speed: 10 Mbps now, 0 Mbps max
OFPT_GET_CONFIG_REPLY (xid=0x4): frags=normal miss_send_len=0

Libvirt XML configuration (relevant parts)

<domain type='kvm'>
  <name>ubuntu-server</name>
  <devices>
    <emulator>/usr/bin/qemu-system-x86_64</emulator>
    <interface type='vhostuser'>
      <mac address='52:54:00:16:a5:76'/>
      <source type='unix' path='/tmp/vhost-client-1' mode='server'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
    </interface>
  </devices>
</domain>

Which configuration option am I missing? I have followed several guides but still I am unable to route any traffic between my VMs.

I suspect that the problem is related to the LINK_DOWN status of the vhost-client-1 port as reported by the ovs-ofctl show command. I've tried to set that status as UP with the command ovs-ofctl mod-port br0 vhost-client-1 up. Even though the command did not fail, nothing changed.

Any thoughts?

Body:
Eventually, I managed to solve my problem. Vipin's answer was useful, but did not solve the issue. The configuration option I was missing was the numa option within the cpu element.

I post the working configuration file just in case it is useful for other people. The first part is about memory backing (under the domain element):

  <memory unit='KiB'>[VM memory size]</memory>
  <currentMemory unit='KiB'>[VM memory size]</currentMemory>
  <memoryBacking>
    <hugepages>
      <page size='2048' unit='KiB'/>
    </hugepages>
    <locked/>
    <source type='file'/>
    <access mode='shared'/>
    <allocation mode='immediate'/>
    <discard/>
  </memoryBacking>

But we also needed the numa configuration, even if our machine had just one processor:

<cpu mode='custom' match='exact' check='full'>
    <model fallback='forbid'>qemu64</model>
    <feature policy='require' name='x2apic'/>
    <feature policy='require' name='hypervisor'/>
    <feature policy='require' name='lahf_lm'/>
    <feature policy='disable' name='svm'/>
    <numa>
      <cell id='0' cpus='0-1' memory='[VM memory size]' unit='KiB' memAccess='shared'/>
    </numa>
</cpu>


问:
Weird filter for function definition in Ocaml
Sorry for this noob question but I have this function definition :

```<code>let f x = function
    | 0 -> 0
    | y -> 1;;
</code>```

I understand that f is a function of x,y but why does it give :

0 if y = 0

1 if y = 1

Indeed according to the filter, should not f(0,1) give 0 since 0 -> 0 ?

答:
This definition of a function is shorthand for

```<code>let g x y = match y with | 0 -> 0 | y -> 1;;
</code>```

Its signature is:
val g : 'a -> int -> int = <fun>

and you call both f or g like this:

g "hello" 5
- : int = 1

g "hello" 0
- : int = 0
```
<p>So, the output of the function just depends on its second argument <code>y</code>.</p>
<p>If you do not need the name of the second argument (right hand side after <code>-></code>) does not refer to it, you can also use wild cards:</p>
```let f x = function
    | 0 -> 0
    | _ -> 1
```
<p>The different guards are being tested in order of how they were written. This is just the same in the Common Lisp construct</p>
<pre class="lang-lisp prettyprint-override"><code>(defun f (x y)
  (cond
    ((= y 0) 0)
    (t 1)))
</code>```

Where the last term of the cond form is the catch-all term.

Body:
Sorry for this noob question but I have this function definition :

let f x = function
    | 0 -> 0
    | y -> 1;;

I understand that f is a function of x,y but why does it give :

0 if y = 0

1 if y = 1

Indeed according to the filter, should not f(0,1) give 0 since 0 -> 0 ?

Body:
This definition of a function is shorthand for

let g x y = match y with | 0 -> 0 | y -> 1;;

Its signature is:
val g : 'a -> int -> int = <fun>

and you call both f or g like this:

g "hello" 5
- : int = 1

g "hello" 0
- : int = 0

So, the output of the function just depends on its second argument y.

If you do not need the name of the second argument (right hand side after ->) does not refer to it, you can also use wild cards:

let f x = function
    | 0 -> 0
    | _ -> 1

The different guards are being tested in order of how they were written. This is just the same in the Common Lisp construct

(defun f (x y)
  (cond
    ((= y 0) 0)
    (t 1)))

Where the last term of the cond form is the catch-all term.


问:
Find an alternating permutation of a list
Given a list, I want to generate a permutation of the list that is alternating: the first element must be greater than the second, which must be lower than the third, which must be greater than the second, etc.

I have tried the following code:

li=[10,2,11,13,21,12,6,7,8,9]
#  condition = a1>a2<a3>a4.....>an

li = sorted(li)
print(li)

for i in range(len(li)-1):
  li[i], li[i+1] = li[i+1], li[i]
  print(li[i],li[i+1])
print(li)
```
<p>But it doesn't satisfy the condition. It gives the Output as below- </p>
```'[2, 6, 7, 8, 9, 10, 11, 12, 13, 21]'
'[6, 7, 8, 9, 10, 11, 12, 13, 21, 2]'
```

答:
This problem can be solved rather efficiently with only a few steps:

>>> li=[10,2,11,13,21,12,6,7,8,9]
>>> # sort from smallest to largest
>>> li.sort()
>>> result = [None] * len(li)
>>> # use first/smallest half for a2, a4, a6, ...
>>> result[1::2] = li[:len(li)//2]
>>> # use second/largest half for a1, a3, a5, ...
>>> result[::2] = li[len(li)//2:]
>>> result
[10, 2, 11, 6, 12, 7, 13, 8, 21, 9]
```

The [::2] and [1::2] are a "slice from 0/1 with step 2", i.e. the odd/even positions.

Now why does this work?

Let's look at a small case first:

a1 > a2 < a3 > a4

We can rewrite this to separate criteria for each element:

a1 > a2

a3 > a2 and a3 > a4

a2 < a1 and a2 < a3

a4 < a3

These are only between each odd element and several even elements, and likewise between each even element and several odd elements. There are no relations between odd elements and no relations between even elements. This means there are several possible solutions and we can pick the one that works easiest:

Instead of worrying about the many triples of elements – like a2 a3 a4 – and how they relate to each other, it would be simpler if we could look at the two even/odd element groups at once.

We can do this by extending our relation between each odd element to all even elements and vice versa:

a1 > a2 and a1 > a4

a3 > a2 and a3 > a4

a2 < a1 and a2 < a3

a4 < a1 and a4 < a3

This still satisfies the initial criteria, it just excludes some possible solution.

Now, if we compare the rules for all odd elements, we can see that they are exactly the same and likewise for all even elements:

ai > a2 and ai > a4 for all i in {1, 3}

aj < a1 and aj < a3 for all i in {2, 4}

In fact, both are just a single rule for all elements:

ai > aj for all i in {1, 3} for all i in {2, 4}

At this point, it should be obvious1 that this does not just apply to the case of 4 elements but in fact to every number of elements:

ai > aj for all i in {1, 3, ...} for all i in {2, 4, ...}

In words, this means a possible solution is to have all odd elements larger than all even elements. This can be achieved by splitting the sorted input to get the largest/smallest elements, then assigning each of these groups to the even/odd positions.

1The proof is left as an exercise to the reader.

Body:
Given a list, I want to generate a permutation of the list that is alternating: the first element must be greater than the second, which must be lower than the third, which must be greater than the second, etc.

I have tried the following code:

li=[10,2,11,13,21,12,6,7,8,9]
#  condition = a1>a2<a3>a4.....>an

li = sorted(li)
print(li)

for i in range(len(li)-1):
  li[i], li[i+1] = li[i+1], li[i]
  print(li[i],li[i+1])
print(li)

But it doesn't satisfy the condition. It gives the Output as below-

'[2, 6, 7, 8, 9, 10, 11, 12, 13, 21]'
'[6, 7, 8, 9, 10, 11, 12, 13, 21, 2]'

Body:
This problem can be solved rather efficiently with only a few steps:

>>> li=[10,2,11,13,21,12,6,7,8,9]
>>> # sort from smallest to largest
>>> li.sort()
>>> result = [None] * len(li)
>>> # use first/smallest half for a2, a4, a6, ...
>>> result[1::2] = li[:len(li)//2]
>>> # use second/largest half for a1, a3, a5, ...
>>> result[::2] = li[len(li)//2:]
>>> result
[10, 2, 11, 6, 12, 7, 13, 8, 21, 9]

The [::2] and [1::2] are a "slice from 0/1 with step 2", i.e. the odd/even positions.

Now why does this work?

Let's look at a small case first:

a1 > a2 < a3 > a4

We can rewrite this to separate criteria for each element:

a1 > a2

a3 > a2 and a3 > a4

a2 < a1 and a2 < a3

a4 < a3

These are only between each odd element and several even elements, and likewise between each even element and several odd elements. There are no relations between odd elements and no relations between even elements. This means there are several possible solutions and we can pick the one that works easiest:

Instead of worrying about the many triples of elements – like a2 a3 a4 – and how they relate to each other, it would be simpler if we could look at the two even/odd element groups at once.

We can do this by extending our relation between each odd element to all even elements and vice versa:

a1 > a2 and a1 > a4

a3 > a2 and a3 > a4

a2 < a1 and a2 < a3

a4 < a1 and a4 < a3

This still satisfies the initial criteria, it just excludes some possible solution.

Now, if we compare the rules for all odd elements, we can see that they are exactly the same and likewise for all even elements:

ai > a2 and ai > a4 for all i in {1, 3}

aj < a1 and aj < a3 for all i in {2, 4}

In fact, both are just a single rule for all elements:

ai > aj for all i in {1, 3} for all i in {2, 4}

At this point, it should be obvious1 that this does not just apply to the case of 4 elements but in fact to every number of elements:

ai > aj for all i in {1, 3, ...} for all i in {2, 4, ...}

In words, this means a possible solution is to have all odd elements larger than all even elements. This can be achieved by splitting the sorted input to get the largest/smallest elements, then assigning each of these groups to the even/odd positions.

1The proof is left as an exercise to the reader.


问:
Memory allocation in c problem
I'm nearing the end of an introductory book on c programming called "C programming in easy steps" by Mike McGrath. I think I'll have a lot more to learn after this book by the looks of things though. Anyways, I'm working with memory allocation and I wrote this demo program, but it errors closed when I try to run it:

```<code>#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, *arr;

    arr = calloc(5, sizeof(int));
    if(arr!=NULL)
    {
        printf("Enter 5 integers, seperated by a space:");
        for(i=0; i<5; i++) scanf("%d", &arr[i]);
        printf("Adding more space...\n");
        arr = realloc(8, sizeof(int));
        printf("Enter 3 more integers seperated by a space:");
        for(i=5; i<8; i++) scanf("%d", &arr[i]);
        printf("Thanks.\nYour 8 entries were: ");
        for(i=0; i<8; i++) printf("%d, ", arr[i]);
        printf("\n");
        free(arr);
        return 0;
        }
    else {printf("!!! INSUFFICIENT MEMORY !!!\n"); return 1; }
}
</code>```

Warning message:

```<code>|13|warning: passing argument 1 of 'realloc' makes pointer from integer without a cast|
c:\program files\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\..\..\..\..\include\stdlib.h|365|note: expected 'void *' but argument is of type 'int'|
||=== Build finished: 0 errors, 1 warnings ===|
</code>```

The resulting compilation asks for 5 integers and prints "Adding more space..." at which point the program terminates, instead of asking for the additional three integers and printing the input.

Any help would be nice. :) Thanks!

答:
Your use of realloc is wrong.

```<code>    // ptr: Pointer to a memory block previously allocated with malloc, calloc or
    // realloc to be reallocated.
    void * realloc ( void * ptr, size_t size );
</code>```

You should use realloc(arr, 8 * sizeof(int));

ContentLicense: CC BY-SA 3.0

Title: Memory allocation in c problem

Body:
I'm nearing the end of an introductory book on c programming called "C programming in easy steps" by Mike McGrath. I think I'll have a lot more to learn after this book by the looks of things though. Anyways, I'm working with memory allocation and I wrote this demo program, but it errors closed when I try to run it:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, *arr;

    arr = calloc(5, sizeof(int));
    if(arr!=NULL)
    {
        printf("Enter 5 integers, seperated by a space:");
        for(i=0; i<5; i++) scanf("%d", &arr[i]);
        printf("Adding more space...\n");
        arr = realloc(8, sizeof(int));
        printf("Enter 3 more integers seperated by a space:");
        for(i=5; i<8; i++) scanf("%d", &arr[i]);
        printf("Thanks.\nYour 8 entries were: ");
        for(i=0; i<8; i++) printf("%d, ", arr[i]);
        printf("\n");
        free(arr);
        return 0;
        }
    else {printf("!!! INSUFFICIENT MEMORY !!!\n"); return 1; }
}

Warning message:

|13|warning: passing argument 1 of 'realloc' makes pointer from integer without a cast|
c:\program files\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\..\..\..\..\include\stdlib.h|365|note: expected 'void *' but argument is of type 'int'|
||=== Build finished: 0 errors, 1 warnings ===|

The resulting compilation asks for 5 integers and prints "Adding more space..." at which point the program terminates, instead of asking for the additional three integers and printing the input.

Any help would be nice. :) Thanks!

Body:
Your use of realloc is wrong.

    // ptr: Pointer to a memory block previously allocated with malloc, calloc or
    // realloc to be reallocated.
    void * realloc ( void * ptr, size_t size );

You should use realloc(arr, 8 * sizeof(int));


问:
How to get metadata of a blob from Event Grid Trigger in Azure Function
My requirement is to get metadata from the blob on an EventGridTrigger. The ask seems to be simple, however I am not able to find examples online. Below is my Azure Funtion.
I need to get the Metadata of the blob. What is the best way of getting it.

```<code>        public static void Run([EventGridTrigger] EventGridEvent eventGridEvent,
        [Blob("{data.url}", FileAccess.Read, Connection = "AzureWebJobsStorage")] Stream input,
        ExecutionContext context,
        ILogger log)
        {
              // other lines of code
              IDictionary<string, string> metadata = get_metadata_of_the_blob;
              // other lines of code
        }
</code>```

I need to somehow get the Metadata within the function code at: get_metadata_of_the_blob

答:
First you need a blog instance then you can get the blog meta data.</p>
```<code>try
    {
        BlobClient blob = new ....
        // Get the blob's properties and metadata.
        BlobProperties properties = await blob.GetPropertiesAsync();

        Console.WriteLine("Blob metadata:");

        // Enumerate the blob's metadata.
        foreach (var metadataItem in properties.Metadata)
        {
            Console.WriteLine($"\tKey: {metadataItem.Key}");
            Console.WriteLine($"\tValue: {metadataItem.Value}");
        }
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine(e.Message);
    }
</code>```

Body:
My requirement is to get metadata from the blob on an EventGridTrigger. The ask seems to be simple, however I am not able to find examples online. Below is my Azure Funtion.
I need to get the Metadata of the blob. What is the best way of getting it.

        public static void Run([EventGridTrigger] EventGridEvent eventGridEvent,
        [Blob("{data.url}", FileAccess.Read, Connection = "AzureWebJobsStorage")] Stream input,
        ExecutionContext context,
        ILogger log)
        {
              // other lines of code
              IDictionary<string, string> metadata = get_metadata_of_the_blob;
              // other lines of code
        }

I need to somehow get the Metadata within the function code at: get_metadata_of_the_blob

Body:
First you need a blog instance then you can get the blog meta data.

try
    {
        BlobClient blob = new ....
        // Get the blob's properties and metadata.
        BlobProperties properties = await blob.GetPropertiesAsync();

        Console.WriteLine("Blob metadata:");

        // Enumerate the blob's metadata.
        foreach (var metadataItem in properties.Metadata)
        {
            Console.WriteLine($"\tKey: {metadataItem.Key}");
            Console.WriteLine($"\tValue: {metadataItem.Value}");
        }
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine(e.Message);
    }


问:
C program prints 1 twice in a while loop, why?
Code snippet

```<code>```c
#include <stdio.h>

int main(void) {
  short int a;
  scanf("%hd", &a);
  while (a != 5) {
    printf("%hd\n", a);
    a++;
  }
  return 0;
}
```
<p>The output of this code is:</p>
<p>Code snippet</p>
```1
1
2
3
4
```
<p>I am expecting the output to be:</p>
<p>Code snippet</p>
```1
2
3
4
5
```

But why is the output different from what I am expecting?

I have tried the following:

I have checked the syntax of the code. It is correct.

I have run the code on different compilers. The output is the same on all compilers.

I have tried different values for a. The output is the same for all values of a.

答:
I think the first "1" is your input.
I tried to run the same code and that is what I observed the first "1" is the input I gave and then the code prints from 1 to 4.

Body:
Code snippet

```c
#include <stdio.h>

int main(void) {
  short int a;
  scanf("%hd", &a);
  while (a != 5) {
    printf("%hd\n", a);
    a++;
  }
  return 0;
}

The output of this code is:

Code snippet

1
1
2
3
4

I am expecting the output to be:

Code snippet

1
2
3
4
5

But why is the output different from what I am expecting?

I have tried the following:

I have checked the syntax of the code. It is correct.

I have run the code on different compilers. The output is the same on all compilers.

I have tried different values for a. The output is the same for all values of a.


问:
Adjust alertdialog heigh to display all items in listview
I m trying to implement an alert dialog with single choice items, and everything seems fine.

The only problem is that when the list contains multiple items, they are shown correctly, but when the list contains only 2 items, the list is cropped like that.

Screenshot is here

How can i adjust my alert dialog to show all items when there are no many items?

This is my code

```<code>val adapter : ArrayAdapter<*> = ArrayAdapter(context, R.layout.simple_list_item, items)

MaterialAlertDialogBuilder(context, R.style.dialog_custom_style)
    .setTitle("Dialog title")
    .setSingleChoiceItems(adapter, 0) { dialog, position ->

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

This is my simple_list_item layout

```<code><androidx.appcompat.widget.AppCompatCheckedTextView
    xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@android:id/text1"

    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:drawableStart="?android:attr/listChoiceIndicatorSingle"

    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:padding="16dp"/>
</code>```

And this is my dialog style

```<code><style name="Dialog.Custom.Style" parent="ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <item name="alertDialogStyle">@style/MaterialAlertDialog.App</item>
    <item name="materialAlertDialogTitleTextStyle">@style/MaterialAlertDialog.App.Title.Text</item>
    <item name="materialAlertDialogBodyTextStyle">@style/MaterialAlertDialog.App.Body.Text</item>
    <item name="buttonBarPositiveButtonStyle">@style/Widget.App.Button</item>
    <item name="buttonBarNeutralButtonStyle">@style/Widget.App.Button</item>
    <item name="textAllCaps">false</item>
    <item name="android:textAllCaps">false</item>
    <item name="android:textStyle">bold</item>
</style>

<style name="MaterialAlertDialog.App.Title.Text" parent="MaterialAlertDialog.MaterialComponents.Title.Text">
    <item name="android:textSize">18sp</item>
    <item name="android:textColor">@color/text</item>
</style>

<style name="MaterialAlertDialog.App.Body.Text" parent="MaterialAlertDialog.MaterialComponents">
    <item name="android:textSize">16sp</item>
    <item name="android:textColor">@color/text</item>
    <item name="android:textStyle">normal</item>
    <item name="android:singleLine">false</item>
</style>

<style name="Widget.App.Button" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
    <!--        <item name="materialThemeOverlay">@style/ThemeOverlay.App.Button.TextButton</item>-->
    <item name="shapeAppearance">@style/ShapeAppearance.App.SmallComponent</item>
    <item name="android:layout_marginEnd">16dp</item>
</style>
</code>```

答: Use a custom view with a RecyclerView or ListView then use wrap_content on the root.

Body:
I m trying to implement an alert dialog with single choice items, and everything seems fine.

The only problem is that when the list contains multiple items, they are shown correctly, but when the list contains only 2 items, the list is cropped like that.

Screenshot is here

How can i adjust my alert dialog to show all items when there are no many items?

This is my code

val adapter : ArrayAdapter<*> = ArrayAdapter(context, R.layout.simple_list_item, items)

MaterialAlertDialogBuilder(context, R.style.dialog_custom_style)
    .setTitle("Dialog title")
    .setSingleChoiceItems(adapter, 0) { dialog, position ->

        //...
    }
    .show()

This is my simple_list_item layout

<androidx.appcompat.widget.AppCompatCheckedTextView
    xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@android:id/text1"

    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:drawableStart="?android:attr/listChoiceIndicatorSingle"

    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:padding="16dp"/>

And this is my dialog style


问:
how to create another window after some seconds from creating one in TKinter
so I started learning Tkinter and i want to open another window after 3 seconds form opening the first one . but when i run the code the first window hide under the seconde window and the second window is empty. how to show the first window but after 3 seconds show the second window?

the code:

```<code>from tkinter import *
from PIL import ImageTk,Image
import time

root = Tk()
root.title('you got hacked')
root.iconbitmap('D:/pythonFiles/aim tren/tree.ico')
root.eval('tk::PlaceWindow . center')

def openwin2():
    root.destroy()
    #first win
    win1 = Tk()
    win1.title('???')
    win1.iconbitmap('D:/pythonFiles/aim tren/tree.ico')
    win1.eval('tk::PlaceWindow . center')

    text1 = Label(win1, text="do...")
    text1.grid(row=0, column=1, padx=10, pady=10)

    myimg = Image.open("i.png")
    resize_image = myimg.resize((50, 50), Image.ANTIALIAS)
    img = ImageTk.PhotoImage(resize_image)
    label = Label(image=img)
    label.myimg = img
    label.grid(row=0, column=0, padx=10, pady=5)

    #second win

    win2 = Tk()
    win2.title('???')
    win2.iconbitmap('D:/pythonFiles/aim tren/tree.ico')
    win2.eval('tk::PlaceWindow . center')

    text2 = Label(win2, text="you...")
    text2.grid(row=0, column=1, padx=10, pady=10)

    myimg = Image.open("i.png")
    resize_image = myimg.resize((50, 50), Image.ANTIALIAS)
    img = ImageTk.PhotoImage(resize_image)
    label = Label(image=img)
    label.myimg = img
    label.grid(row=0, column=0, padx=10, pady=5)

    time.sleep(3)
    win1.destroy()
    win2.mainloop()
    win1.mainloop()

text_erorr = Label(root, text="your pc has been hacked, you need to fix the pc before the virus get to 'system32'\n you need to be fast and answer the next questions.")
button_ok = Button(root, text="ok", padx=25, bg='lightgray', command= openwin2)

text_erorr.grid(row=0, column=1, columnspan=2, padx=15, pady=2)
button_ok.grid(row=1, column=3, padx=10, pady=10)

myimg = Image.open("tree.png")
resize_image = myimg.resize((50, 50), Image.ANTIALIAS)
img = ImageTk.PhotoImage(resize_image)
label = Label(image=img)
label.myimg = img
label.grid(row=0, column=0, padx=10, pady=5)

root.mainloop()
</code>```

答:
Use root.after("time in ms", create_window) to wait x seconds and declare a new window variable with window = tk.Toplevel(root):

```<code>import tkinter as tk

root = tk.Tk()

def create_window():
    new_window = tk.Toplevel(root)

root.after(3000, create_window)

root.mainloop()
</code>```

Body:
so I started learning Tkinter and i want to open another window after 3 seconds form opening the first one . but when i run the code the first window hide under the seconde window and the second window is empty. how to show the first window but after 3 seconds show the second window?

the code:

from tkinter import *
from PIL import ImageTk,Image
import time

root = Tk()
root.title('you got hacked')
root.iconbitmap('D:/pythonFiles/aim tren/tree.ico')
root.eval('tk::PlaceWindow . center')

def openwin2():
    root.destroy()
    #first win
    win1 = Tk()
    win1.title('???')
    win1.iconbitmap('D:/pythonFiles/aim tren/tree.ico')
    win1.eval('tk::PlaceWindow . center')

    text1 = Label(win1, text="do...")
    text1.grid(row=0, column=1, padx=10, pady=10)

    myimg = Image.open("i.png")
    resize_image = myimg.resize((50, 50), Image.ANTIALIAS)
    img = ImageTk.PhotoImage(resize_image)
    label = Label(image=img)
    label.myimg = img
    label.grid(row=0, column=0, padx=10, pady=5)

    #second win

    win2 = Tk()
    win2.title('???')
    win2.iconbitmap('D:/pythonFiles/aim tren/tree.ico')
    win2.eval('tk::PlaceWindow . center')

    text2 = Label(win2, text="you...")
    text2.grid(row=0, column=1, padx=10, pady=10)

    myimg = Image.open("i.png")
    resize_image = myimg.resize((50, 50), Image.ANTIALIAS)
    img = ImageTk.PhotoImage(resize_image)
    label = Label(image=img)
    label.myimg = img
    label.grid(row=0, column=0, padx=10, pady=5)

    time.sleep(3)
    win1.destroy()
    win2.mainloop()
    win1.mainloop()

text_erorr = Label(root, text="your pc has been hacked, you need to fix the pc before the virus get to 'system32'\n you need to be fast and answer the next questions.")
button_ok = Button(root, text="ok", padx=25, bg='lightgray', command= openwin2)

text_erorr.grid(row=0, column=1, columnspan=2, padx=15, pady=2)
button_ok.grid(row=1, column=3, padx=10, pady=10)

myimg = Image.open("tree.png")
resize_image = myimg.resize((50, 50), Image.ANTIALIAS)
img = ImageTk.PhotoImage(resize_image)
label = Label(image=img)
label.myimg = img
label.grid(row=0, column=0, padx=10, pady=5)

root.mainloop()

Body:
Use root.after("time in ms", create_window) to wait x seconds and declare a new window variable with window = tk.Toplevel(root):

import tkinter as tk

root = tk.Tk()

def create_window():
    new_window = tk.Toplevel(root)

root.after(3000, create_window)

root.mainloop()


问:
Storing different types in a single Hashmap
A bit of context to prevent xy:

I want to build a cache for my system. There are Type pairs consisting of IdType and EndpointType in a 1:1 relationship. Every IdType only ever refers to one EndpointType and vice versa. The Id trait (see code below) is not required, it only exists in my current iteration of trying to make this work.

There are way too many different types of endpoints - and usually an application will only use a small subset of them - to justify statically building a cache per endpoint and holding that in memory. Additionally, I want to be able to add new endpoints without touching any code related to caching or the client itself.

The Endpoint trait objects are not object safe and there is no way to make them object safe due to associated consts, Sized and methods not using self to make use of compile time optimizations.

I came up with the idea of storing them as kind of Any type. Now I like type safety, so I tried to restrict it a bit more. After failing to find a satisfying solution, I still have several issues with my idea:

How do I make this approach work?

Is there a better solution?

Is this sound? Why?

Is there a way to make it sound?

Can I achieve this without unsafe?

Link to the rust playground

use std::sync::Mutex;
use std::collections::HashMap;

pub trait Endpoint: Sized {
    type Id;
}

pub trait Id {
    type Endpoint;
}

pub struct Client {
    cache: Mutex<Cache>,
}

impl Client {
    fn get<T: Endpoint>(&self, id: T::Id) -> T {
        if let Some(result) = self.cache.lock().unwrap().get(id) {
            return result;
        }
        todo!()
    }
}

pub struct Cache {
    map: HashMap<Box<dyn Id>, Box<dyn Endpoint>>,
}

impl Cache {
    fn get<T: Id>(&self, id: T) -> Option<T::Endpoint> {
        if let Some(endpoint) = self.map.get(Box::new(id)) {
            let endpoint: Box<T::Endpoint> = unsafe { std::mem::transmute(endpoint) };
            Some(endpoint)
        } else {
            None
        }
    }
}
```

答:
I'd strongly recommend going with Box<dyn Any> over std::mem::transmute. A fairly common pattern is to have a HashMap<TypeId, Box<dyn Any>>. TypeId is a type that can be used to distinguish between other types, and it's Eq and Hash impls work how you'd expect: if the types are the same, the type ids are equal. So you could have something roughly like:

struct Cache {
  map: HashMap<TypeId, Box<dyn Any>>,
}

impl Cache {
  fn get<T>(&self) -> Option<&T> {
    let type_id = TypeId::of::<T>();
    let any = self.map.get(&type_id)?;
    any.downcast_ref()
  }
}
```
<p>This can act like a rough lookup table that associates a type with a single value of that type. If there is a <code>Box<dyn Any></code> that is associated with the type id for <code>T</code>, but points to a value of some other type, you won't get UB, you'll just get <code>None</code>.</p>
<p>This sort of primitive can be used to build a more complex cache around it. For example, you could have a struct that wraps this that provides access, but it only supports keys of type <code>(T, <T as Id>::Endpoint)</code>.</p>
<p>The key point is to use <code>Any</code> and <code>downcast_*</code> methods to avoid unsafe.</p>
<p><code>std::mem::transmute</code> is one of the more dangerous unsafe functions, and should largely be seen as a last resort. From the docs:</p>
<blockquote>
<p><code>transmute</code> is <strong>incredibly</strong> unsafe. There are a vast number of ways to cause undefined behaviour with this function. <code>transmute</code> should be the absolute last resort</p>
</blockquote>
<p>I'd also add, this pattern is common enough that there's probably a crate that provides a type safe interface, a quick search yielded this: https://crates.io/crates/anymap, though I can't speak for this crate's quality in particular</p>
<p>Edit:</p>
<p>If you also want to be able to distinguish between multiple instances of the same <code>Id</code>/<code>Endpoint</code> pair type, you could modify it to store a hashmap with the keys having a type <code>(TypeId, u64)</code>, where the <code>u64</code> is the result of hashing the original key (a bit like a SQL composite key):</p>
<pre class="lang-rust prettyprint-override"><code>struct Cache {
  map: HashMap<(TypeId, u64), Box<dyn Any>>,
}

impl Cache {
    fn insert<T>(&mut self, id: T::Id, endpoint: T)
    where
        T: Endpoint + 'static,
        T::Id: Hash,
    {
        let type_id = TypeId::of::<T>();
        let hash = {
            let mut hasher = DefaultHasher::new();
            id.hash(&mut hasher);
            hasher.finish()
        };

        self.map.insert((type_id, hash), Box::new(endpoint));
    }

    fn get<T>(&self, id: T::Id) -> Option<&T>
    where
        T: Endpoint + 'static,
        T::Id: Hash,
    {
        let type_id = ...;
        let hash = ...;

        let option_any = self.map.get(&(type_id, hash));
        option_any.and_then(|any| any.downcast_ref())
    }
}
</code>```

This lets you have multiple FooEndpoints (with FooIds), as well as BarEndpoints (and BarIds), while avoiding transmute/unsafe, all with a single map lookup. Hopefully I read your question more accurately this time ;p

P.S. I have no idea if this particular way of obtaining a u64 hash is "good", I've never actually had to do this before (I've only ever used the Hash trait with std::collections::HashMap/HashSet). Might be worth doing some googling to make sure this isn't doing something horrible

Body:
I'd strongly recommend going with Box<dyn Any> over std::mem::transmute. A fairly common pattern is to have a HashMap<TypeId, Box<dyn Any>>. TypeId is a type that can be used to distinguish between other types, and it's Eq and Hash impls work how you'd expect: if the types are the same, the type ids are equal. So you could have something roughly like:

struct Cache {
  map: HashMap<TypeId, Box<dyn Any>>,
}

impl Cache {
  fn get<T>(&self) -> Option<&T> {
    let type_id = TypeId::of::<T>();
    let any = self.map.get(&type_id)?;
    any.downcast_ref()
  }
}

This can act like a rough lookup table that associates a type with a single value of that type. If there is a Box<dyn Any> that is associated with the type id for T, but points to a value of some other type, you won't get UB, you'll just get None.

This sort of primitive can be used to build a more complex cache around it. For example, you could have a struct that wraps this that provides access, but it only supports keys of type (T, <T as Id>::Endpoint).

The key point is to use Any and downcast_* methods to avoid unsafe.

std::mem::transmute is one of the more dangerous unsafe functions, and should largely be seen as a last resort. From the docs:

transmute is incredibly unsafe. There are a vast number of ways to cause undefined behaviour with this function. transmute should be the absolute last resort

I'd also add, this pattern is common enough that there's probably a crate that provides a type safe interface, a quick search yielded this: https://crates.io/crates/anymap, though I can't speak for this crate's quality in particular

Edit:

If you also want to be able to distinguish between multiple instances of the same Id/Endpoint pair type, you could modify it to store a hashmap with the keys having a type (TypeId, u64), where the u64 is the result of hashing the original key (a bit like a SQL composite key):

struct Cache {
  map: HashMap<(TypeId, u64), Box<dyn Any>>,
}

impl Cache {
    fn insert<T>(&mut self, id: T::Id, endpoint: T)
    where
        T: Endpoint + 'static,
        T::Id: Hash,
    {
        let type_id = TypeId::of::<T>();
        let hash = {
            let mut hasher = DefaultHasher::new();
            id.hash(&mut hasher);
            hasher.finish()
        };

        self.map.insert((type_id, hash), Box::new(endpoint));
    }

    fn get<T>(&self, id: T::Id) -> Option<&T>
    where
        T: Endpoint + 'static,
        T::Id: Hash,
    {
        let type_id = ...;
        let hash = ...;

        let option_any = self.map.get(&(type_id, hash));
        option_any.and_then(|any| any.downcast_ref())
    }
}

This lets you have multiple FooEndpoints (with FooIds), as well as BarEndpoints (and BarIds), while avoiding transmute/unsafe, all with a single map lookup. Hopefully I read your question more accurately this time ;p

P.S. I have no idea if this particular way of obtaining a u64 hash is "good", I've never actually had to do this before (I've only ever used the Hash trait with std::collections::HashMap/HashSet). Might be worth doing some googling to make sure this isn't doing something horrible


问:
Base64 String throwing invalid character error
I keep getting a Base64 invalid character error even though I shouldn't.

The program takes an XML file and exports it to a document. If the user wants, it will compress the file as well. The compression works fine and returns a Base64 String which is encoded into UTF-8 and written to a file.

When its time to reload the document into the program I have to check whether its compressed or not, the code is simply:

```<code>byte[] gzBuffer = System.Convert.FromBase64String(text);
return "1F-8B-08" == BitConverter.ToString(new List<Byte>(gzBuffer).GetRange(4, 3).ToArray());
</code>```

It checks the beginning of the string to see if it has GZips code in it.

Now the thing is, all my tests work. I take a string, compress it, decompress it, and compare it to the original. The problem is when I get the string returned from an ADO Recordset. The string is exactly what was written to the file (with the addition of a "\0" at the end, but I don't think that even does anything, even trimmed off it still throws). I even copy and pasted the entire string into a test method and compress/decompress that. Works fine.

The tests will pass but the code will fail using the exact same string? The only difference is instead of just declaring a regular string and passing it in I'm getting one returned from a recordset.

Any ideas on what am I doing wrong?

答:
Whether null char is allowed or not really depends on base64 codec in question.
Given vagueness of Base64 standard (there is no authoritative exact specification), many implementations would just ignore it as white space. And then others can flag it as a problem. And buggiest ones wouldn't notice and would happily try decoding it... :-/

But it sounds c# implementation does not like it (which is one valid approach) so if removing it helps, that should be done.

One minor additional comment: UTF-8 is not a requirement, ISO-8859-x aka Latin-x, and 7-bit Ascii would work as well. This because Base64 was specifically designed to only use 7-bit subset which works with all 7-bit ascii compatible encodings.

OwnerDisplayName: Brandon

ContentLicense: CC BY-SA 2.5

Body:
I keep getting a Base64 invalid character error even though I shouldn't.

The program takes an XML file and exports it to a document. If the user wants, it will compress the file as well. The compression works fine and returns a Base64 String which is encoded into UTF-8 and written to a file.

When its time to reload the document into the program I have to check whether its compressed or not, the code is simply:

byte[] gzBuffer = System.Convert.FromBase64String(text);
return "1F-8B-08" == BitConverter.ToString(new List<Byte>(gzBuffer).GetRange(4, 3).ToArray());

It checks the beginning of the string to see if it has GZips code in it.

Now the thing is, all my tests work. I take a string, compress it, decompress it, and compare it to the original. The problem is when I get the string returned from an ADO Recordset. The string is exactly what was written to the file (with the addition of a "\0" at the end, but I don't think that even does anything, even trimmed off it still throws). I even copy and pasted the entire string into a test method and compress/decompress that. Works fine.

The tests will pass but the code will fail using the exact same string? The only difference is instead of just declaring a regular string and passing it in I'm getting one returned from a recordset.

Any ideas on what am I doing wrong?

LastEditorDisplayName: Brandon

OwnerDisplayName: StaxMan


问:
Unity Card Hover Animations
Hello everyone I am trying to make a hover animation to my cards. When you hover over cards in your hand I want them to go up but the card is a prefab so when I hover over one (or click on one) they all go up at the same time. This is a small project for me to practice Trading Card Games and here is the animationless link: https://play.unity.com/mg/other/unitycardtaskbuild

If you have time it would be really nice if you connect with me through discord.

答:
```<code> public class MyClass: MonoBehaviour, IPointerEnterHandler,IPointerExitHandler
 {
     public void OnPointerEnter(PointerEventData eventData)
     {
         //Move your card up
     }
     public void OnPointerExit(PointerEventData eventData)
     {
         //Move your card down
     }
 }
</code>```

Try this Out! I've already written it for you!
By the way, I played your card game and it's cool!
(´∇`)

Title: Unity Card Hover Animations

Body:
 public class MyClass: MonoBehaviour, IPointerEnterHandler,IPointerExitHandler
 {
     public void OnPointerEnter(PointerEventData eventData)
     {
         //Move your card up
     }
     public void OnPointerExit(PointerEventData eventData)
     {
         //Move your card down
     }
 }

Try this Out! I've already written it for you!
By the way, I played your card game and it's cool!
(´∇`)


问:
How to make a field (column value) span multiple rows in Excel Templates to be used in Oracle BI Pub Reports?
I am creating an Excel Template for BI Pub Reports,

 Sample XML is generated using Oracle BI Pub Data Model.

 My Data Model is like this :-

My sample XML is here:-

```<code><?xml version="1.0" encoding="UTF-8"?>
<!--Generated by Oracle BI Publisher 12.2.1.4.0 -Dataengine, datamodel:__agars00_Swe_Reports_subaru_mar_dm_xdm -->
-<DATA_DS>
<P_CURRENT_DATE>03-Jan-22</P_CURRENT_DATE>
<P_MESSAGE>(SALES/ADJ)</P_MESSAGE>
<P_R12_END>December 2021</P_R12_END>
<P_R12_BEGIN>January 2021</P_R12_BEGIN>
<P_TERRITORY>TERRITORY 102</P_TERRITORY>
<P_REGION>1</P_REGION>
<P_DEALER_NAME>JIM PATTISON</P_DEALER_NAME>
<P_DEALER_CODE>1007</P_DEALER_CODE>
-<G_1>
<SORTID>3693</SORTID>
<REGION>1</REGION>
<TERRITORY>TERRITORY 102</TERRITORY>
<DEALER_CODE>1007</DEALER_CODE>
<DEALER_NAME>JIM PATTISON</DEALER_NAME>
<SEGMENT>Total Compact Car</SEGMENT>
<SUB_SEGMENT>Corolla</SUB_SEGMENT>
<MTD>0</MTD>
<MLY>0</MLY>
<CURR12>2</CURR12>
<PER_CURR12>0.8</PER_CURR12>
<PREV12>2</PREV12>
<PER_PREV12>0.2</PER_PREV12>
<CYTD>2</CYTD>
<PYTD>2</PYTD>
</G_1>
-<G_1>
<SORTID>3694</SORTID>
<REGION>1</REGION>
<TERRITORY>TERRITORY 102</TERRITORY>
<DEALER_CODE>1007</DEALER_CODE>
<DEALER_NAME>JIM PATTISON</DEALER_NAME>
<SEGMENT>Total Compact Car</SEGMENT>
<SUB_SEGMENT>Cruze</SUB_SEGMENT>
<MTD>0</MTD>
<MLY>0</MLY>
<CURR12>0</CURR12>
<PREV12>0</PREV12>
<PER_PREV12>0.1</PER_PREV12>
<PER_VAR_R12>-10</PER_VAR_R12>
<CYTD>0</CYTD>
<PYTD>1</PYTD>
</G_1>
</DATA_DS>
</code>```

 Expected Output is like this:-

 first column that shows "Total ___ CARS" spans all the rows with same type of cars.

I created a Repeating Group on whole row

 XDO_METADATA sheet looks like this:-

but my output is showing like this:-

 HOW CAN I add spanning of first column values here????

答:
So, I was not able to find a Excel Template solution for this.
I had to alter my generated reports using Python (merging cells by opening Excel apps through scripting)</p>

Body:
I am creating an Excel Template for BI Pub Reports,

 Sample XML is generated using Oracle BI Pub Data Model.

 My Data Model is like this :-

My sample XML is here:-

<?xml version="1.0" encoding="UTF-8"?>

-<DATA_DS>
<P_CURRENT_DATE>03-Jan-22</P_CURRENT_DATE>
<P_MESSAGE>(SALES/ADJ)</P_MESSAGE>
<P_R12_END>December 2021</P_R12_END>
<P_R12_BEGIN>January 2021</P_R12_BEGIN>
<P_TERRITORY>TERRITORY 102</P_TERRITORY>
<P_REGION>1</P_REGION>
<P_DEALER_NAME>JIM PATTISON</P_DEALER_NAME>
<P_DEALER_CODE>1007</P_DEALER_CODE>
-<G_1>
<SORTID>3693</SORTID>
<REGION>1</REGION>
<TERRITORY>TERRITORY 102</TERRITORY>
<DEALER_CODE>1007</DEALER_CODE>
<DEALER_NAME>JIM PATTISON</DEALER_NAME>
<SEGMENT>Total Compact Car</SEGMENT>
<SUB_SEGMENT>Corolla</SUB_SEGMENT>
<MTD>0</MTD>
<MLY>0</MLY>
<CURR12>2</CURR12>
<PER_CURR12>0.8</PER_CURR12>
<PREV12>2</PREV12>
<PER_PREV12>0.2</PER_PREV12>
<CYTD>2</CYTD>
<PYTD>2</PYTD>
</G_1>
-<G_1>
<SORTID>3694</SORTID>
<REGION>1</REGION>
<TERRITORY>TERRITORY 102</TERRITORY>
<DEALER_CODE>1007</DEALER_CODE>
<DEALER_NAME>JIM PATTISON</DEALER_NAME>
<SEGMENT>Total Compact Car</SEGMENT>
<SUB_SEGMENT>Cruze</SUB_SEGMENT>
<MTD>0</MTD>
<MLY>0</MLY>
<CURR12>0</CURR12>
<PREV12>0</PREV12>
<PER_PREV12>0.1</PER_PREV12>
<PER_VAR_R12>-10</PER_VAR_R12>
<CYTD>0</CYTD>
<PYTD>1</PYTD>
</G_1>
</DATA_DS>

 Expected Output is like this:-

 first column that shows "Total ___ CARS" spans all the rows with same type of cars.

I created a Repeating Group on whole row

 XDO_METADATA sheet looks like this:-

but my output is showing like this:-

 HOW CAN I add spanning of first column values here????


问:
Why does my asynchronous function not complete all execution of its code?
I am just starting to learn about asynchronous programming, in particular the async and await syntax and usage of the asyncio module.

My question is regarding the output of the following code:

```<code>import asyncio

async def foo():
    print('start fetching')
    await asyncio.sleep(2)
    print('done fetching')
    return {'data':1}

async def boo():
    for i in range(10):
        print(i)
        await asyncio.sleep(0.25)

async def main():
    task1 = asyncio.create_task(foo())
    task2 = asyncio.create_task(boo())

asyncio.run(main())
</code>```

The output that I get is:

start fetching
0
```

While I understand what each individual part of the code does, I can't understand why only two lines of the code is being outputted. Here is my understanding:

We start with task1 and print start fetching.

Then we hit the await for 2 seconds.

In these two seconds doesn't this give task2 the opportunity to do its execution for 2 seconds, so 0-8 will be printed?

Then I also don't see why we don't continue executing the function foo()? – i.e. print('done fetching')?

答:
You must wait your tasks to finish:

async def main():
    task1 = asyncio.create_task(foo())
    task2 = asyncio.create_task(boo())

    await task1
    await task2
```
<p>Output:</p>
```start fetching
0
1
2
3
4
5
6
7
done fetching
8
9
```
<p>See the official document for more examples.</p>
<hr />
<p>Now let's talk about why it only print one line of each function. The key is any block operation will lead to task rescheduling:</p>
<pre class="lang-py prettyprint-override"><code>import asyncio

async def foo():
    print('start fetching')
    # Do not await anything
    print('done fetching')
    i = 0
    # Compute for a long time, but the task scheduler
    # will not interrupt it.
    while i < 99999999:
        i += 1
    return {'data':1}

async def boo():
    for i in range(10):
        print(i)
        # Do not await anything

async def main():
    task1 = asyncio.create_task(foo())
    task2 = asyncio.create_task(boo())

asyncio.run(main())
</code>```

Output:

```<code>start fetching
done fetching
0
1
2
3
4
5
6
7
8
9
</code>```

As you can see, these tasks completed in sequence.

async def foo():
    print('start fetching')
    # Although it actually not sleep,
    # it still force the scheduler to switch tasks.
    await asyncio.sleep(0)
    print('done fetching')
    return {'data':1}

async def boo():
    for i in range(10):
        print(i)

async def main():
    task1 = asyncio.create_task(foo())
    task2 = asyncio.create_task(boo())
    await asyncio.sleep(0)

asyncio.run(main())
```
<p>Output:</p>
```start fetching
0
1
2
3
4
5
6
7
8
9
done fetching
```

If any task is not completed, while the script terminated, those uncompleted tasks will be discarded.

If you want to dive deeper into the scheduler, maybe you should read the source code of asyncio.

Body:
I am just starting to learn about asynchronous programming, in particular the async and await syntax and usage of the asyncio module.

My question is regarding the output of the following code:

import asyncio

async def foo():
    print('start fetching')
    await asyncio.sleep(2)
    print('done fetching')
    return {'data':1}

async def boo():
    for i in range(10):
        print(i)
        await asyncio.sleep(0.25)

async def main():
    task1 = asyncio.create_task(foo())
    task2 = asyncio.create_task(boo())

asyncio.run(main())

The output that I get is:

start fetching
0

While I understand what each individual part of the code does, I can't understand why only two lines of the code is being outputted. Here is my understanding:

We start with task1 and print start fetching.

Then we hit the await for 2 seconds.

In these two seconds doesn't this give task2 the opportunity to do its execution for 2 seconds, so 0-8 will be printed?

Then I also don't see why we don't continue executing the function foo()? – i.e. print('done fetching')?

Body:
You must wait your tasks to finish:

async def main():
    task1 = asyncio.create_task(foo())
    task2 = asyncio.create_task(boo())

    await task1
    await task2

Output:

start fetching
0
1
2
3
4
5
6
7
done fetching
8
9

See the official document for more examples.

Now let's talk about why it only print one line of each function. The key is any block operation will lead to task rescheduling:

import asyncio

async def foo():
    print('start fetching')
    # Do not await anything
    print('done fetching')
    i = 0
    # Compute for a long time, but the task scheduler
    # will not interrupt it.
    while i < 99999999:
        i += 1
    return {'data':1}

async def boo():
    for i in range(10):
        print(i)
        # Do not await anything

async def main():
    task1 = asyncio.create_task(foo())
    task2 = asyncio.create_task(boo())

asyncio.run(main())

Output:

start fetching
done fetching
0
1
2
3
4
5
6
7
8
9

As you can see, these tasks completed in sequence.

async def foo():
    print('start fetching')
    # Although it actually not sleep,
    # it still force the scheduler to switch tasks.
    await asyncio.sleep(0)
    print('done fetching')
    return {'data':1}

async def boo():
    for i in range(10):
        print(i)

async def main():
    task1 = asyncio.create_task(foo())
    task2 = asyncio.create_task(boo())
    await asyncio.sleep(0)

asyncio.run(main())

Output:

start fetching
0
1
2
3
4
5
6
7
8
9
done fetching

If any task is not completed, while the script terminated, those uncompleted tasks will be discarded.

If you want to dive deeper into the scheduler, maybe you should read the source code of asyncio.


问:
How to create a document term incidence matrix from long format text data?
I've got data that look like this:

ID
word

1
blue

1
red

1
green

1
yellow

2
blue

2
purple

2
orange

2
green

But I want to transform them into a binary incidence matrix denoting whether or not a word appears within a certain document ID. In other words, I'd like to create a matrix that looks like this:

ID
blue
red
green
yellow
purple
orange

1
1
1
1
1
0
0

2
1
0
1
0
1
1

Is there a way to do this with the tm package? I thought maybe using DocumentTermMatrix() would work since I don't think that any words in my corpus have multiple incidences within a single document, but everything I've tried has returned error messages about the incompatibility of the function with object class data.frame

答:
If you want to do this to run a supervised or unsupervised machine learning model, you should directly cast the tidy data frame into a document-feature-matrix (dfm). dfms are a class of sparse matrix that can be effectively used for these tasks. You can use cast_dfm from tidytext for this. But you have to count the occurrence of each word first.

library(tidyverse)
library(tidytext)

df <- data.frame(
  stringsAsFactors = FALSE,
  ID = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L),
  word = c("blue","red", "green","yellow","blue","purple","orange","green")
)

df %>%
  count(ID, word) %>%
  cast_dfm(ID, word, n)
#> Document-feature matrix of: 2 documents, 6 features (33.33% sparse) and 0 docvars.
#>     features
#> docs blue green red yellow orange purple
#>    1    1     1   1      1      0      0
#>    2    1     1   0      0      1      1
```

Created on 2022-02-12 by the reprex package (v2.0.1)

You can convert this object back into a data frame with quanteda::convert(x, to = "data.frame") but it would make more sense to use it directly if you run a classification task.

Body:
If you want to do this to run a supervised or unsupervised machine learning model, you should directly cast the tidy data frame into a document-feature-matrix (dfm). dfms are a class of sparse matrix that can be effectively used for these tasks. You can use cast_dfm from tidytext for this. But you have to count the occurrence of each word first.

library(tidyverse)
library(tidytext)

df <- data.frame(
  stringsAsFactors = FALSE,
  ID = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L),
  word = c("blue","red", "green","yellow","blue","purple","orange","green")
)

df %>%
  count(ID, word) %>%
  cast_dfm(ID, word, n)
#> Document-feature matrix of: 2 documents, 6 features (33.33% sparse) and 0 docvars.
#>     features
#> docs blue green red yellow orange purple
#>    1    1     1   1      1      0      0
#>    2    1     1   0      0      1      1

Created on 2022-02-12 by the reprex package (v2.0.1)

You can convert this object back into a data frame with quanteda::convert(x, to = "data.frame") but it would make more sense to use it directly if you run a classification task.


问:
Cytoscape element is added but not rendered
So I want to render the following Cytoscape element but in the end there is nothing that appears on the screen.

```<code>let cy = cytoscape({
    container: document.getElementById('cy'),
    elements: [ // list of graph elements to start with
        { // node a
            data: { id: 'a' }
        },
        { // node b
            data: { id: 'b' }
        },
        { // edge ab
            data: { id: 'ab', source: 'a', target: 'b' }
        },
        {
            data: { id: 'c' }
        },
        {
            data: {
                id: 'ac', source: 'a', target: 'c',
                'value': 'ceva',
                'value2': 'data(target)',
            }
        }
    ],

    style: [ // the stylesheet for the graph
        {
            selector: 'node',
            style: {
                'background-color': 'red',
                'label': 'data(id)'
            }
        },

        {
            selector: 'edge',
            style: {
                'width': 3,
                'line-color': 'blue',
                'target-arrow-color': '#ccc',
                'target-arrow-shape': 'triangle',
                'curve-style': 'bezier',
            }
        }
    ],

    layout: {
        name: 'grid',
        rows: 1
    }
})
cy.add([
    { group: 'nodes', data: { id: 'n0' }, position: { x: 100, y: 100 } },
    { group: 'nodes', data: { id: 'n1' }, position: { x: 200, y: 200 } },
    { group: 'edges', data: { id: 'e0', source: 'n0', target: 'n1' } }
]);
</code>```

This is the HTML:

```<code><html>
  <head>
    <script src="./script.js"></script>
  </head>
  <body>
    <div id="cy"></div>
    <script src="./cyto.js"></script>
  </body>
</html>
</code>```

What the problem seems to me is the fact that the Cytoscape class ends up having the height = 0. After I modify the class in inspect element and add height = 1000px it works mostly fine.
What could the solution be, I am new to Cytoscape so I think this might be a basic mistake.

答:
I am using cytoscape with this kind of setup:

```<code><div id="cy" style="width: 900px; height: 800px;"></div>
</code>```

where height and width are set at the beginning.

Body:
So I want to render the following Cytoscape element but in the end there is nothing that appears on the screen.

let cy = cytoscape({
    container: document.getElementById('cy'),
    elements: [ // list of graph elements to start with
        { // node a
            data: { id: 'a' }
        },
        { // node b
            data: { id: 'b' }
        },
        { // edge ab
            data: { id: 'ab', source: 'a', target: 'b' }
        },
        {
            data: { id: 'c' }
        },
        {
            data: {
                id: 'ac', source: 'a', target: 'c',
                'value': 'ceva',
                'value2': 'data(target)',
            }
        }
    ],

    style: [ // the stylesheet for the graph
        {
            selector: 'node',
            style: {
                'background-color': 'red',
                'label': 'data(id)'
            }
        },

        {
            selector: 'edge',
            style: {
                'width': 3,
                'line-color': 'blue',
                'target-arrow-color': '#ccc',
                'target-arrow-shape': 'triangle',
                'curve-style': 'bezier',
            }
        }
    ],

    layout: {
        name: 'grid',
        rows: 1
    }
})
cy.add([
    { group: 'nodes', data: { id: 'n0' }, position: { x: 100, y: 100 } },
    { group: 'nodes', data: { id: 'n1' }, position: { x: 200, y: 200 } },
    { group: 'edges', data: { id: 'e0', source: 'n0', target: 'n1' } }
]);

This is the HTML:

What the problem seems to me is the fact that the Cytoscape class ends up having the height = 0. After I modify the class in inspect element and add height = 1000px it works mostly fine.
What could the solution be, I am new to Cytoscape so I think this might be a basic mistake.

Body:
I am using cytoscape with this kind of setup:

<div id="cy" style="width: 900px; height: 800px;"></div>

where height and width are set at the beginning.


问:
Insert Image using variable name in Kotlin
I currently am working on an app that has a list of characters and images associated with each of them.

I want to insert images for all the characters using a for loop without actually hardcoding their image names:

Example:

```<code>var agentsList = listOf(
        "Astra",
        "Breach",
        "Brimstone",
        "Chamber",
        "Cypher",
        "Jett",
        "KAY/O",
        "Killjoy",
        "Neon",
        "Omen",
        "Phoenix",
        "Raze",
        "Reyna",
        "Sage",
        "Skye",
        "Sova",
        "Viper",
        "Yoru"
    )
for (agent in agentsList) {
    dataList.add(DataModel(agent, R.drawable.agent)
}
</code>```

Here , R.drawable.agent is where I want to insert the images , but i want the for loop to do it for me using the string resource in agentsList.

I have saved the image using the same strings as the characters in agentsList, so that won't be an issue.

答:
You can use string name to get drawable resource identifier:</p>
```<code>for (agent in agentsList) {
    val resources: Resources = context.resources
    val resourceId: Int = resources.getIdentifier(agent, "drawable", context.packageName)
    dataList.add(DataModel(agent, resourceId)
}
</code>```

Body:
I currently am working on an app that has a list of characters and images associated with each of them.

I want to insert images for all the characters using a for loop without actually hardcoding their image names:

Example:

var agentsList = listOf(
        "Astra",
        "Breach",
        "Brimstone",
        "Chamber",
        "Cypher",
        "Jett",
        "KAY/O",
        "Killjoy",
        "Neon",
        "Omen",
        "Phoenix",
        "Raze",
        "Reyna",
        "Sage",
        "Skye",
        "Sova",
        "Viper",
        "Yoru"
    )
for (agent in agentsList) {
    dataList.add(DataModel(agent, R.drawable.agent)
}

Here , R.drawable.agent is where I want to insert the images , but i want the for loop to do it for me using the string resource in agentsList.

I have saved the image using the same strings as the characters in agentsList, so that won't be an issue.

Body:
You can use string name to get drawable resource identifier:

for (agent in agentsList) {
    val resources: Resources = context.resources
    val resourceId: Int = resources.getIdentifier(agent, "drawable", context.packageName)
    dataList.add(DataModel(agent, resourceId)
}


问:
Add image to PHP email template
If I add the following line into the template the checkout becomes unavailable.

```<code>"\n<img src="https://example.com/images/girocode.png" alt="GiroCode" />" .
</code>```

How can I make the work in PHP?

答:
you should use \ before "

```<code>"\n<img src=\"https://example.com/images/girocode.png\" alt=\"GiroCode\" />"
</code>```

Title: Add image to PHP email template

Body:
If I add the following line into the template the checkout becomes unavailable.

"\n" .

How can I make the work in PHP?

Body:
you should use \ before "

"\n<img src=\"https://example.com/images/girocode.png\" alt=\"GiroCode\" />"


问:
Scroll position in iOS
In Javascript, I wanted to understand a few things:

Can we both get/set scroll pos for a window?

What is the diff between window scroll pos and for normal element on page?

Can we set scroll pos for any HTML elements or is it only for those with overflow properties?

Is there any difference in these property calc for iPad?

For scrollWidth, does it get affected by vertical scrollbars..If yes, is it the same in all browsers?

答:
Your answers.

$(window).scrollTop(), $(window).scrollTop(100);

window scroll position is the main page's scroll postion(left/top) where as for normal element the scroll position applies when we set overflow:auto to it and then we can get/set the scroll position of it.

We can get the scroll position of any element using $("selector").scrollTop()/scrollLeft() but yes if the overflow is not auto then I think it will always return 0.

For iPad the scrollTop()/scrollLeft() do not work, you have to use window.pageYOffset/window.pageXOffset

JavaScript equivalents, not tested though across browsers

$(window).scrollTop() - document.documentElement.scrollTop/scrollLeft
$("selector").scrollLeft() - document.getElementById("elementId").offsetTop/offsetLeft

Title: Scroll position in iOS


问:
"Unresolved reference: PopupBackgroundView"
I have a problem. After the espresso test recorded, found an error shown "Unresolved reference: PopupBackgroundView"

[Espresson Test code]:

```<code>val materialTextView = onData(anything()).inAdapterView(childAtPosition(withClassName(is("android.widget.PopupWindow$PopupBackgroundView")), 0)).atPosition(4)
materialTextView.perform(click())
</code>```
```<code>androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0-alpha03'
androidTestImplementation 'androidx.test:rules:1.4.0-alpha05'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.5.0-alpha03'
</code>```

答:
The issue here is that the class name that you are seeing is an internal, platform-level class that may vary on different OS builds.

For instance a skinned build made by a manufacturer (think Samsung, Sony, Huawei etc.) might have a modified version of the PopupWindow class that is styled differently or have some extra attributes for configuration associated with it, and could be called something like com.manufacturer.widget.PopupWindow$CustomPopupBackgroundView.

So there wouldn't be a match if you developed the Espresso test on a Pixel device using the stock Android class name, and then ran it on a device with this modified UI class; an instance of the class wouldn't exist in the view hierarchy, and the test could fail dependent on the device it was being run on.

For that reason, platform or system-level UI classes shouldn't be directly referenced in Espresso tests. Instead you can use a root matcher such as isPlatformPopup() when you need Espresso to tap on auto-complete text or other system-owned UI components. That way it'll always find the component that you're looking for regardless which device you run the test on.

So try this code that replaces the withClassName search for the isPlatFormPopup() method instead:

```<code>val materialTextView = onData(anything())
    .inRoot(isPlatformPopup()) // this line is the key part
    .atPosition(4)

materialTextView.perform(click())
</code>```

Body:
I have a problem. After the espresso test recorded, found an error shown "Unresolved reference: PopupBackgroundView"

[Espresson Test code]:

val materialTextView = onData(anything()).inAdapterView(childAtPosition(withClassName(is("android.widget.PopupWindow$PopupBackgroundView")), 0)).atPosition(4)
materialTextView.perform(click())

androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0-alpha03'
androidTestImplementation 'androidx.test:rules:1.4.0-alpha05'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.5.0-alpha03'

Body:
The issue here is that the class name that you are seeing is an internal, platform-level class that may vary on different OS builds.

For instance a skinned build made by a manufacturer (think Samsung, Sony, Huawei etc.) might have a modified version of the PopupWindow class that is styled differently or have some extra attributes for configuration associated with it, and could be called something like com.manufacturer.widget.PopupWindow$CustomPopupBackgroundView.

So there wouldn't be a match if you developed the Espresso test on a Pixel device using the stock Android class name, and then ran it on a device with this modified UI class; an instance of the class wouldn't exist in the view hierarchy, and the test could fail dependent on the device it was being run on.

For that reason, platform or system-level UI classes shouldn't be directly referenced in Espresso tests. Instead you can use a root matcher such as isPlatformPopup() when you need Espresso to tap on auto-complete text or other system-owned UI components. That way it'll always find the component that you're looking for regardless which device you run the test on.

So try this code that replaces the withClassName search for the isPlatFormPopup() method instead:

val materialTextView = onData(anything())
    .inRoot(isPlatformPopup()) // this line is the key part
    .atPosition(4)

materialTextView.perform(click())


问:
How do you uninstall Flutter completely and properly from a Mac?
I need to uninstall Flutter completely from my Mac. However, I cannot find any documentation that can help me with that.</p>

答:
This worked for me actually:</p>
```<code>sudo npm uninstall -g flutter-cli
</code>```

Body:
This worked for me actually:

sudo npm uninstall -g flutter-cli


问:
Try adding an explicit type, or remove implicit-dynamic from your analysis options file
I am pretty new to flutter and am getting frustated at this. How do I get rid of the error?

The code:

```<code>  factory MyAudioList.fromMap(Map<String, dynamic> map) {
    return MyAudioList(
      audios: List<MyAudio>.from(
          map['audios']?.map((x) => MyAudio.fromMap(x as Map<String, dynamic>))
              as Iterable<dynamic>),
    );
  }
</code>```

The error:

答:
Try doing this instead and check if it works:</p>
```<code>factory MyAudioList.fromMap(Map<String, dynamic> map) {
    return MyAudioList(
      audios: List<MyAudio>.from(
          map['audios']?.map((Map<String, dynamic> x) => MyAudio.fromMap(x))
              as Iterable<dynamic>),
    );
  }
</code>```

Body:
I am pretty new to flutter and am getting frustated at this. How do I get rid of the error?

The code:

  factory MyAudioList.fromMap(Map<String, dynamic> map) {
    return MyAudioList(
      audios: List<MyAudio>.from(
          map['audios']?.map((x) => MyAudio.fromMap(x as Map<String, dynamic>))
              as Iterable<dynamic>),
    );
  }

The error:

Body:
Try doing this instead and check if it works:

factory MyAudioList.fromMap(Map<String, dynamic> map) {
    return MyAudioList(
      audios: List<MyAudio>.from(
          map['audios']?.map((Map<String, dynamic> x) => MyAudio.fromMap(x))
              as Iterable<dynamic>),
    );
  }


问:
Android activity Background affects alertDialog
I have a style I created like this:

```<code><style name="myStyle" parent="@android:style/Theme.Dialog">
    <item name="android:textColor">#FFFFFF</item>
    <item name="android:background">#000099</item>
</style>
</code>```

Then I created an xml and an activity, and in the manifest declared this

```<code>                     <activity android:name=".Try"
            android:theme="@style/myStyle" >
    </activity>
</code>```

Then when I start this activity I have an xml with a background color (blue);
THe problem is , when I create an Alert Dialog

```<code>     AlertDialog.Builder dialog = new AlertDialog.Builder....
</code>```

It is also affected by this background (It looks more like a blue rectangle behind it that is bigger then the dialog and is coming out from all 4 sides).
I dont want it to be, I want to use another style for the alert dialog.

How can I disable this?

答:
Are you saying that the background of your activity is too prominent when the dialog pops up? If so, you can blur what's in the background with the following code:

```<code>dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
</code>```

Or are you saying that the background of your activity is being applied to the background of your dialog...?

Body:
I have a style I created like this:

Then I created an xml and an activity, and in the manifest declared this

                     <activity android:name=".Try"
            android:theme="@style/myStyle" >
    </activity>

Then when I start this activity I have an xml with a background color (blue);
THe problem is , when I create an Alert Dialog

     AlertDialog.Builder dialog = new AlertDialog.Builder....

It is also affected by this background (It looks more like a blue rectangle behind it that is bigger then the dialog and is coming out from all 4 sides).
I dont want it to be, I want to use another style for the alert dialog.

How can I disable this?

Body:
Are you saying that the background of your activity is too prominent when the dialog pops up? If so, you can blur what's in the background with the following code:

dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);

Or are you saying that the background of your activity is being applied to the background of your dialog...?


问:
Parse specific value from JSON in SQL Server
I am trying to extract postal_code from Google geocoder JSON (long_name from address_components where types = postal_code, in this case value 1000):

```<code>   "results":[
      {
         "address_components":[
            {
               "long_name":"9",
               "short_name":"9",
               "types":[
                  "street_number"
               ]
            },
            {
               "long_name":"Pod bukvami",
               "short_name":"Pod bukvami",
               "types":[
                  "route"
               ]
            },
            {
               "long_name":"Ljubljana",
               "short_name":"Ljubljana",
               "types":[
                  "postal_town"
               ]
            },
            {
               "long_name":"Ljubljana",
               "short_name":"Ljubljana",
               "types":[
                  "administrative_area_level_1",
                  "political"
               ]
            },
            {
               "long_name":"Slovenia",
               "short_name":"SI",
               "types":[
                  "country",
                  "political"
               ]
            },
            {
               "long_name":"1000",
               "short_name":"1000",
               "types":[
                  "postal_code"
               ]
            }
         ],
         "formatted_address":"Pod bukvami 9, 1000 Ljubljana, Slovenia",
         "geometry":{
            "location":{
               "lat":46.0346449,
               "lng":14.4894346
            },
            "location_type":"ROOFTOP",
            "viewport":{
               "northeast":{
                  "lat":46.035993880291493,
                  "lng":14.4907835802915
               },
               "southwest":{
                  "lat":46.0332959197085,
                  "lng":14.4880856197085
               }
            }
         },
         "place_id":"ChIJG19AZRUtZUcRDQni_pW0iLc",
         "plus_code":{
            "compound_code":"2FMQ+VQ Ljubljana, Slovenia",
            "global_code":"8FRP2FMQ+VQ"
         },
         "types":[
            "establishment",
            "lodging",
            "point_of_interest"
         ]
      }
   ],
   "status":"OK"
}
</code>```

I tried with
JSON_VALUE([GoogleJSON],'$.results[0].address_components[5].long_name') but address_components array doesn't have fixed number of elements. I would like to use something like address_components[types="postal_code"].long_name but not sure if this is possible

Thanks,
Miljan

答:
NOTE: The JSON posted in the question requires surrounding braces {} to make it valid JSON.

Have you read up on OPENJSON (Transact-SQL) yet? It's easy to use it from a cross apply as shown below...

select address.*
from #Example
cross apply openjson(GoogleJSON, N'$.results[0].address_components') with (
  long_name nvarchar(100),
  short_name nvarchar(100),
  types nvarchar(max) as json
) address
where 'postal_code' in (select [value] from openjson(types, '$'));
```

Which returns the result...

long_name
short_name
types

1000
1000
[ "postal_code" ]

Body:
I am trying to extract postal_code from Google geocoder JSON (long_name from address_components where types = postal_code, in this case value 1000):

   "results":[
      {
         "address_components":[
            {
               "long_name":"9",
               "short_name":"9",
               "types":[
                  "street_number"
               ]
            },
            {
               "long_name":"Pod bukvami",
               "short_name":"Pod bukvami",
               "types":[
                  "route"
               ]
            },
            {
               "long_name":"Ljubljana",
               "short_name":"Ljubljana",
               "types":[
                  "postal_town"
               ]
            },
            {
               "long_name":"Ljubljana",
               "short_name":"Ljubljana",
               "types":[
                  "administrative_area_level_1",
                  "political"
               ]
            },
            {
               "long_name":"Slovenia",
               "short_name":"SI",
               "types":[
                  "country",
                  "political"
               ]
            },
            {
               "long_name":"1000",
               "short_name":"1000",
               "types":[
                  "postal_code"
               ]
            }
         ],
         "formatted_address":"Pod bukvami 9, 1000 Ljubljana, Slovenia",
         "geometry":{
            "location":{
               "lat":46.0346449,
               "lng":14.4894346
            },
            "location_type":"ROOFTOP",
            "viewport":{
               "northeast":{
                  "lat":46.035993880291493,
                  "lng":14.4907835802915
               },
               "southwest":{
                  "lat":46.0332959197085,
                  "lng":14.4880856197085
               }
            }
         },
         "place_id":"ChIJG19AZRUtZUcRDQni_pW0iLc",
         "plus_code":{
            "compound_code":"2FMQ+VQ Ljubljana, Slovenia",
            "global_code":"8FRP2FMQ+VQ"
         },
         "types":[
            "establishment",
            "lodging",
            "point_of_interest"
         ]
      }
   ],
   "status":"OK"
}

I tried with
JSON_VALUE([GoogleJSON],'$.results[0].address_components[5].long_name') but address_components array doesn't have fixed number of elements. I would like to use something like address_components[types="postal_code"].long_name but not sure if this is possible

Thanks,
Miljan

Body:
NOTE: The JSON posted in the question requires surrounding braces {} to make it valid JSON.

Have you read up on OPENJSON (Transact-SQL) yet? It's easy to use it from a cross apply as shown below...

select address.*
from #Example
cross apply openjson(GoogleJSON, N'$.results[0].address_components') with (
  long_name nvarchar(100),
  short_name nvarchar(100),
  types nvarchar(max) as json
) address
where 'postal_code' in (select [value] from openjson(types, '$'));

Which returns the result...

long_name
short_name
types

1000
1000
[ "postal_code" ]


问:
How can I use NavigationPage in Maui?
I want to navigate like this in MainPage:

```<code>private async void btnNav_Clicked(object sender, EventArgs e)
{
    await Navigation.PushAsync(new Pages.Nav1Page());
}
</code>```

This does not work. Then I get to know that I need to use NavigationPage to wrap MainPage, like this:

```<code>public MainWindow()
{
    Page = new NavigationPage(new MainPage());
}
</code>```

But NavigationPage does not implement the IPage interface.

答:
Try this:</p>
```<code>public partial class App : Application
{
    public App()
    {
        InitializeComponent();

        MainPage = new NavigationPage();
        MainPage.Navigation.PushAsync(new MainPage());
    }
}
</code>```

Title: How can I use NavigationPage in Maui?

Body:
I want to navigate like this in MainPage:

private async void btnNav_Clicked(object sender, EventArgs e)
{
    await Navigation.PushAsync(new Pages.Nav1Page());
}

This does not work. Then I get to know that I need to use NavigationPage to wrap MainPage, like this:

public MainWindow()
{
    Page = new NavigationPage(new MainPage());
}

But NavigationPage does not implement the IPage interface.

Body:
Try this:

public partial class App : Application
{
    public App()
    {
        InitializeComponent();

        MainPage = new NavigationPage();
        MainPage.Navigation.PushAsync(new MainPage());
    }
}


问:
Python keyboard shortcut for greek letters
I am looking for an alt-code that I can use to insert rho (ρ) into python.

I have tried Alt + 961 which returns ┴ which does not work.
I can however copy a rho symbol from Word and paste into python which does work, but would be better to be able to directly insert it into python.

The reason for not wanting to explore the unicode options for the greek symbol ρ is because I like having my variables as greek letters when coding. I am fully aware that there are formatting options with the print() command to give the ρ symbol, however I would like ρ to be the subject of my equation. Or am I wrong and it can be done with unicode?

Any ideas?

答:
```<code>C1 =d.add(elm.Capacitor().label("C1 1 $\u03C1$F" ))#PICOFARAD
C1 =d.add(elm.Capacitor().label("C1 1 $\u00B5$F" ))#MICROFARAD
</code>```


问:
preg_replace problems
I have a string The Incredible Hulk (2008) and use pattern

```<code>/^\([0-9]{1,4}\)$/
</code>```

to remove (2008). PHP code looks like this:

```<code>$x = trim(preg_replace("/^\([0-9]{1,4}\)$/", "", "The Incredible Hulk (2008)"));
</code>```

And the result is:

```<code>The Incredible Hulk (2008)
</code>```

What am I doing wrong?

答:
^ and $ are mark begin and end of the entire string. Remove both.

```<code>$x = trim(preg_replace("/\([0-9]{4}\)/", "", "The Incredible Hulk (2008)"));
</code>```

Title: preg_replace problems

Body:
I have a string The Incredible Hulk (2008) and use pattern

/^\([0-9]{1,4}\)$/

to remove (2008). PHP code looks like this:

$x = trim(preg_replace("/^\([0-9]{1,4}\)$/", "", "The Incredible Hulk (2008)"));

And the result is:

The Incredible Hulk (2008)

What am I doing wrong?

Body:
^ and $ are mark begin and end of the entire string. Remove both.

$x = trim(preg_replace("/\([0-9]{4}\)/", "", "The Incredible Hulk (2008)"));