问:
Removing part of an array from a multidimensional nested array
I've a four levels of nested array like this:

$array = [
    [
        'website' => [
            'id' => 'one'
        ],
        'children' => [
            [
                'website' => [
                    'id' => 'one.one'
                ],
                'children' => [
                    [
                        'website' => [
                            'id' => 'one.one.one'
                        ],
                        'children' => [
                            [
                                'website' => [
                                    'id' => 'one.one.one.one'
                                ],
                                'children' => []
                            ],
                            [
                                'website' => [
                                    'id' => 'one.one.one.two'
                                ],
                                'children' => []
                            ]
                        ]
                    ],
                    [
                        'website' => [
                            'id' => 'one.one.two'
                        ],
                        'children' => [
                            [
                                'website' => [
                                    'id' => 'one.one.two.one'
                                ],
                                'children' => []
                            ],
                            [
                                'website' => [
                                    'id' => 'one.one.two.two'
                                ],
                                'children' => []
                            ]
                        ]
                    ]
                ]
            ],
            [
                'website' => [
                    'id' => 'one.two'
                ],
                'children' => [
                    [
                        'website' => [
                            'id' => 'one.two.one'
                        ],
                        'children' => [
                            [
                                'website' => [
                                    'id' => 'one.two.one.one'
                                ],
                                'children' => []
                            ],
                            [
                                'website' => [
                                    'id' => 'one.two.one.two'
                                ],
                                'children' => []
                            ]
                        ]
                    ],
                    [
                        'website' => [
                            'id' => 'one.two.two'
                        ],
                        'children' => [
                            [
                                'website' => [
                                    'id' => 'one.two.two.one'
                                ],
                                'children' => []
                            ],
                            [
                                'website' => [
                                    'id' => 'one.two.two.two'
                                ],
                                'children' => []
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ]
];
```

<p>now, I'd like to remove some of the array element based on some rules. For simplicity, let's say, we'd like to remove array elements that has 'id' equals to <code>one.one.two</code> or <code>one.two.one</code>.</p>

<p>I was looking into some answers provided on stackoverflow and was trying to apply them to solve my issue, but didn't go much. The most chalanging thing is to unset part of an array where it's not the farthest point in the array.</p>

<p>I was trying this to note at which level I want to delete the arrays and then trying to unset them using those array index.</p>

<pre class="lang-php prettyprint-override"><code>$pointer = [];
foreach($array as $key => $level1) {
    $level1pointer = $key;
    $pointer[] = markToDelete($level1, $level1pointer);
    foreach($level1['children'] as $key => $level2) {
        $level2pointer = $key;
        $pointer[] = markToDelete($level2, $level1pointer, $level2pointer);
        foreach($level2['children'] as $key => $level3) {
            $level3pointer = $key;
            $pointer[] = markToDelete($level3, $level1pointer, $level2pointer, $level3pointer);
            foreach($level3['children'] as $key => $level4) {
                $level4pointer = $key;
                $pointer[] = markToDelete($level4, $level1pointer, $level2pointer, $level3pointer, $level4pointer);
            }
        }
    }
}

function markToDelete($array, $level1 = null, $level2 = null, $level3 = null, $level4 = null) {
    $exclusionList = [
        'one.one.two',
        'one.two.one'
    ];

    if (!empty($array['website']) && in_array($array['website']['id'], $exclusionList)) {
        print_r('marking for deletion: '. $array['website']['id'] . PHP_EOL);
        return [
            'id' => $array['website']['id'],
            'level1' => $level1,
            'level2' => $level2,
            'level3' => $level3,
            'level4' => $level4
        ];
    }
    return [];
}
</code>```

I was also trying to use Iterator like this:

$it = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($array), \RecursiveIteratorIterator::LEAVES_ONLY);
$newArray = [];
foreach($it as $key => $value) {
    $exclusionList = [
        'one.one.two',
        'one.two.one'
    ];
    if(!in_array($value, $exclusionList)) {
        print_r(sprintf('value: %s is ready to be deleted', $value).PHP_EOL);
        $newArray[] = $value;
    }
}
```

<p>but I need a way to unset the array when looping through the iterator.</p>

<p>I'd like to get an output like this:</p>

<pre class="lang-php prettyprint-override"><code>$array = [
    [
        'website' => [
            'id' => 'one'
        ],
        'children' => [
            [
                'website' => [
                    'id' => 'one.one'
                ],
                'children' => [
                    [
                        'website' => [
                            'id' => 'one.one.one'
                        ],
                        'children' => [
                            [
                                'website' => [
                                    'id' => 'one.one.one.one'
                                ],
                                'children' => []
                            ],
                            [
                                'website' => [
                                    'id' => 'one.one.one.two'
                                ],
                                'children' => []
                            ]
                        ]
                    ],
                ]
            ],
            [
                'website' => [
                    'id' => 'one.two'
                ],
                'children' => [
                    [
                        'website' => [
                            'id' => 'one.two.two'
                        ],
                        'children' => [
                            [
                                'website' => [
                                    'id' => 'one.two.two.one'
                                ],
                                'children' => []
                            ],
                            [
                                'website' => [
                                    'id' => 'one.two.two.two'
                                ],
                                'children' => []
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ]
];
</code>```

I'd really appreciate help on how to resolve this in more efficient way. Thanks.

答:
Here's a recursive function that will do what you want. It traverses the array, looking for children whose website id is in the list of ids to be removed and unsetting them. Note that because of your additional top-level array, you need to iterate the function over those values.

```<code>function delete_entries(&$array, $ids_to_delete) {
    foreach ($array['children'] as $index => &$child) {
        if (in_array($child['website']['id'], $ids_to_delete)) {
            unset($array['children'][$index]);
        }
        delete_entries($child, $ids_to_delete);
    }
}

foreach ($array as &$arr) {
    delete_entries($arr, array('one.one.two', 'one.two.one'));
}

var_export($array);
</code>```

The output is as you desire but too long to reproduce here. See the demo on 3v4l.org

Update

The above code won't delete entries on the top level because the array structure is different from lower levels in the array. That can be dealt with in the outer foreach loop:

```<code>$excluded = array('two', 'one.one.two', 'one.two.one');
foreach ($array as $key => &$arr) {
    if (in_array($arr['website']['id'], $excluded)) {
        unset($array[$key]);
    }
    else {
        delete_entries($arr, $excluded);
    }
}
</code>```

Updated demo

Body:
I've a four levels of nested array like this:

$array = [
    [
        'website' => [
            'id' => 'one'
        ],
        'children' => [
            [
                'website' => [
                    'id' => 'one.one'
                ],
                'children' => [
                    [
                        'website' => [
                            'id' => 'one.one.one'
                        ],
                        'children' => [
                            [
                                'website' => [
                                    'id' => 'one.one.one.one'
                                ],
                                'children' => []
                            ],
                            [
                                'website' => [
                                    'id' => 'one.one.one.two'
                                ],
                                'children' => []
                            ]
                        ]
                    ],
                    [
                        'website' => [
                            'id' => 'one.one.two'
                        ],
                        'children' => [
                            [
                                'website' => [
                                    'id' => 'one.one.two.one'
                                ],
                                'children' => []
                            ],
                            [
                                'website' => [
                                    'id' => 'one.one.two.two'
                                ],
                                'children' => []
                            ]
                        ]
                    ]
                ]
            ],
            [
                'website' => [
                    'id' => 'one.two'
                ],
                'children' => [
                    [
                        'website' => [
                            'id' => 'one.two.one'
                        ],
                        'children' => [
                            [
                                'website' => [
                                    'id' => 'one.two.one.one'
                                ],
                                'children' => []
                            ],
                            [
                                'website' => [
                                    'id' => 'one.two.one.two'
                                ],
                                'children' => []
                            ]
                        ]
                    ],
                    [
                        'website' => [
                            'id' => 'one.two.two'
                        ],
                        'children' => [
                            [
                                'website' => [
                                    'id' => 'one.two.two.one'
                                ],
                                'children' => []
                            ],
                            [
                                'website' => [
                                    'id' => 'one.two.two.two'
                                ],
                                'children' => []
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ]
];

now, I'd like to remove some of the array element based on some rules. For simplicity, let's say, we'd like to remove array elements that has 'id' equals to one.one.two or one.two.one.

I was looking into some answers provided on stackoverflow and was trying to apply them to solve my issue, but didn't go much. The most chalanging thing is to unset part of an array where it's not the farthest point in the array.

I was trying this to note at which level I want to delete the arrays and then trying to unset them using those array index.

$pointer = [];
foreach($array as $key => $level1) {
    $level1pointer = $key;
    $pointer[] = markToDelete($level1, $level1pointer);
    foreach($level1['children'] as $key => $level2) {
        $level2pointer = $key;
        $pointer[] = markToDelete($level2, $level1pointer, $level2pointer);
        foreach($level2['children'] as $key => $level3) {
            $level3pointer = $key;
            $pointer[] = markToDelete($level3, $level1pointer, $level2pointer, $level3pointer);
            foreach($level3['children'] as $key => $level4) {
                $level4pointer = $key;
                $pointer[] = markToDelete($level4, $level1pointer, $level2pointer, $level3pointer, $level4pointer);
            }
        }
    }
}

function markToDelete($array, $level1 = null, $level2 = null, $level3 = null, $level4 = null) {
    $exclusionList = [
        'one.one.two',
        'one.two.one'
    ];

    if (!empty($array['website']) && in_array($array['website']['id'], $exclusionList)) {
        print_r('marking for deletion: '. $array['website']['id'] . PHP_EOL);
        return [
            'id' => $array['website']['id'],
            'level1' => $level1,
            'level2' => $level2,
            'level3' => $level3,
            'level4' => $level4
        ];
    }
    return [];
}

I was also trying to use Iterator like this:

$it = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($array), \RecursiveIteratorIterator::LEAVES_ONLY);
$newArray = [];
foreach($it as $key => $value) {
    $exclusionList = [
        'one.one.two',
        'one.two.one'
    ];
    if(!in_array($value, $exclusionList)) {
        print_r(sprintf('value: %s is ready to be deleted', $value).PHP_EOL);
        $newArray[] = $value;
    }
}

but I need a way to unset the array when looping through the iterator.

I'd like to get an output like this:

$array = [
    [
        'website' => [
            'id' => 'one'
        ],
        'children' => [
            [
                'website' => [
                    'id' => 'one.one'
                ],
                'children' => [
                    [
                        'website' => [
                            'id' => 'one.one.one'
                        ],
                        'children' => [
                            [
                                'website' => [
                                    'id' => 'one.one.one.one'
                                ],
                                'children' => []
                            ],
                            [
                                'website' => [
                                    'id' => 'one.one.one.two'
                                ],
                                'children' => []
                            ]
                        ]
                    ],
                ]
            ],
            [
                'website' => [
                    'id' => 'one.two'
                ],
                'children' => [
                    [
                        'website' => [
                            'id' => 'one.two.two'
                        ],
                        'children' => [
                            [
                                'website' => [
                                    'id' => 'one.two.two.one'
                                ],
                                'children' => []
                            ],
                            [
                                'website' => [
                                    'id' => 'one.two.two.two'
                                ],
                                'children' => []
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ]
];

I'd really appreciate help on how to resolve this in more efficient way. Thanks.

Body:
Here's a recursive function that will do what you want. It traverses the array, looking for children whose website id is in the list of ids to be removed and unsetting them. Note that because of your additional top-level array, you need to iterate the function over those values.

function delete_entries(&$array, $ids_to_delete) {
    foreach ($array['children'] as $index => &$child) {
        if (in_array($child['website']['id'], $ids_to_delete)) {
            unset($array['children'][$index]);
        }
        delete_entries($child, $ids_to_delete);
    }
}

foreach ($array as &$arr) {
    delete_entries($arr, array('one.one.two', 'one.two.one'));
}

var_export($array);

The output is as you desire but too long to reproduce here. See the demo on 3v4l.org

Update

The above code won't delete entries on the top level because the array structure is different from lower levels in the array. That can be dealt with in the outer foreach loop:

$excluded = array('two', 'one.one.two', 'one.two.one');
foreach ($array as $key => &$arr) {
    if (in_array($arr['website']['id'], $excluded)) {
        unset($array[$key]);
    }
    else {
        delete_entries($arr, $excluded);
    }
}

Updated demo


来源: stackexchange

问:
Performance: Loop through ArrayList hundreds of times vs converting Arraylist to HashMap and Back?
I have two large (1000+ object) ArrayLists that I need to compare and manipulate. I essentially need to take a value from ArrayList A, look for a matching object in ArrayList B, then manipulate the object from B. I need to do this in all objects for A. I need to do this frequently in the application. Order is not known and sizes will differ.

```<code>(pseudocode)
ArrayList<myObject> A
ArrayList<myObject> B
</code>```

I could loop through every single item in B looking for the one that matches the entity from A, for each entity in A. That just seems so inefficient.

```<code>(pseudocode)
for (each object in A){loop through all of B and find it}
</code>```

Would it be worth converting B to a HashMap (using the specific value I am comparing as the key, and the object as the value), then searching B that way, then converting that temporary HashMap back to an ArrayList when I'm done processing?

```<code>(pseudocode)
convert B to HashMap<myObject.myValue,myObject> C
for (each object in A){look up the value in C}
convert C back to an ArrayList
</code>```

Is this a good idea? Or is this premature/unnecessary optimization? Thank you.

(Background: Data comes to me from the service as an ArrayList - and the frontend needs an ArrayList for the view layer. I'm trying to make this middle tier processing more efficient - but the entry and exit objects must be ArrayList (or some other list) )

答:
Yes, for large numbers, a HashMap is beneficial.

Your initial algorithm will take a long time, looping through both lists in nested for loops.  This is an O(n2) algorithm.  Even assuming 1000 items each in A and B, and assuming a cost of 1 for comparing two individual items, one from A and one from B, you're looking at 500k comparisons (avoiding comparing each item twice).  Doing this frequently will cause slow performance.

Assuming you have a good hash code algorithm for your objects, looking up a value from a HashMap is O(1) access.  You'll still spend O(n) time constructing it, but that's nothing compared to O(n2) if you have a large number of items.

Construct your HashMap "C" once using data from "B" and use it many times, as long as B's information hasn't changed.  If you "need to do this frequently", then the performance will be even better because the HashMap is already built -- just reuse it.

If you need to maintain the order, store the B list index as the value in the hash map.

You don't need to be "converting that temporary hashmap back to an arraylist", because creating the HashMap "C" doesn't destroy the original list "B".  One thing to be careful of is if the objects in the list B change, forcing updates to the HashMap to keep consistent.  Another thing to watch is your memory usage for very large lists -- can you keep the objects, the list, and the hashmap in memory?

Your pseudocode:

```<code>for each index in B:
    get object b
    put in hash map C values (b, index)

for each a in A:
    if found in hash map C: do something with found object
</code>```

For smaller numbers, the O(n2) performance times will be small enough that building the HashMap won't be worth it.  That is a decision you'll need to make -- you would need to decide when the lists are large enough that building a HashMap and using it is worth the HashMap construction cost.

ContentLicense: CC BY-SA 4.0

Body:
I have two large (1000+ object) ArrayLists that I need to compare and manipulate. I essentially need to take a value from ArrayList A, look for a matching object in ArrayList B, then manipulate the object from B. I need to do this in all objects for A. I need to do this frequently in the application. Order is not known and sizes will differ.

(pseudocode)
ArrayList<myObject> A
ArrayList<myObject> B

I could loop through every single item in B looking for the one that matches the entity from A, for each entity in A. That just seems so inefficient.

(pseudocode)
for (each object in A){loop through all of B and find it}

Would it be worth converting B to a HashMap (using the specific value I am comparing as the key, and the object as the value), then searching B that way, then converting that temporary HashMap back to an ArrayList when I'm done processing?

(pseudocode)
convert B to HashMap<myObject.myValue,myObject> C
for (each object in A){look up the value in C}
convert C back to an ArrayList

Is this a good idea? Or is this premature/unnecessary optimization? Thank you.

(Background: Data comes to me from the service as an ArrayList - and the frontend needs an ArrayList for the view layer. I'm trying to make this middle tier processing more efficient - but the entry and exit objects must be ArrayList (or some other list) )

Body:
Yes, for large numbers, a HashMap is beneficial.

Your initial algorithm will take a long time, looping through both lists in nested for loops.  This is an O(n2) algorithm.  Even assuming 1000 items each in A and B, and assuming a cost of 1 for comparing two individual items, one from A and one from B, you're looking at 500k comparisons (avoiding comparing each item twice).  Doing this frequently will cause slow performance.

Assuming you have a good hash code algorithm for your objects, looking up a value from a HashMap is O(1) access.  You'll still spend O(n) time constructing it, but that's nothing compared to O(n2) if you have a large number of items.

Construct your HashMap "C" once using data from "B" and use it many times, as long as B's information hasn't changed.  If you "need to do this frequently", then the performance will be even better because the HashMap is already built -- just reuse it.

If you need to maintain the order, store the B list index as the value in the hash map.

You don't need to be "converting that temporary hashmap back to an arraylist", because creating the HashMap "C" doesn't destroy the original list "B".  One thing to be careful of is if the objects in the list B change, forcing updates to the HashMap to keep consistent.  Another thing to watch is your memory usage for very large lists -- can you keep the objects, the list, and the hashmap in memory?

Your pseudocode:

for each index in B:
    get object b
    put in hash map C values (b, index)

for each a in A:
    if found in hash map C: do something with found object

For smaller numbers, the O(n2) performance times will be small enough that building the HashMap won't be worth it.  That is a decision you'll need to make -- you would need to decide when the lists are large enough that building a HashMap and using it is worth the HashMap construction cost.


问:
What are the valid characters that can show up in a URL host?
I'm writing some code that processes URLs, and I want to make sure i'm not leaving some strange case out...

Are there any valid characters for a host other than: A-Z, 0-9, "-" and "."?

(This includes anything that can be in subdomains, etc. Esentially, anything between :// and the first /)

Thanks!

答:
Valid URL host include ascii letters, numbers, the dot ( . ) and the hyphen ( - ) with max length 255 with dot separated labels with max length 63.  The hyphen can delimit alphanumeric sequences e.g. one-two.net but cannot appear at the beginning or end of a dot separated label e.g. -one.two.com, one.two.com- or one-.two.com are invalid host.

See https://www.rfc-editor.org/rfc/rfc1123#page-79 and  Assumptions part 1 of https://www.rfc-editor.org/rfc/rfc952

Also this is a link to an online regex tool to validate URL host which worked as of 5/28/2019 https://www.regextester.com/23

Also when validating a host referencing https://www.rfc-editor.org/rfc/rfc1123#page-13 you should check the host syntactically for a dotted-decimal number before looking it up in the DNS.

ContentLicense: CC BY-SA 2.5


问:
how to get the text content of an element with no ID in javascript
I want to get a particular text content of the heading element which does not have any ID associated with it. What javascript code should I use to get the content 'I only want this one'.

```<code>var elements = document.querySelectorAll('.one span');
console.log(elements[0].text);
</code>```

This code is not giving the desired output

```<code><h5 class="one two three four">
<span class="s1 s2">I don't want this</span>
I only want this one</h5>
</code>```

I expect the output to be 'I only want this one', but I am getting undefined...

答:
You're looking to select the text node, which is not an element, so you can't select it immediately with querySelectorAll (or querySelector) - so, first select the parent (the .one), then navigate to its last child:

const parent = document.querySelector('.one');
const textNode = parent.lastChild;
console.log(textNode.textContent);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h5 class="one two three four">
  <span class="s1 s2">I don't want this</span>
I only want this one</h5></code>```

Note that if you just want the first element which matches a particular selector string, it's more appropriate to use querySelector (which returns that element), rather than querySelectorAll (which returns a collection, from which you must proceed to select the first element in it).

Body:
I want to get a particular text content of the heading element which does not have any ID associated with it. What javascript code should I use to get the content 'I only want this one'.

var elements = document.querySelectorAll('.one span');
console.log(elements[0].text);

This code is not giving the desired output

I don't want this
I only want this one

I expect the output to be 'I only want this one', but I am getting undefined...

Body:
You're looking to select the text node, which is not an element, so you can't select it immediately with querySelectorAll (or querySelector) - so, first select the parent (the .one), then navigate to its last child:

const parent = document.querySelector('.one');
const textNode = parent.lastChild;
console.log(textNode.textContent);

<h5 class="one two three four">
  <span class="s1 s2">I don't want this</span>
I only want this one</h5>

Note that if you just want the first element which matches a particular selector string, it's more appropriate to use querySelector (which returns that element), rather than querySelectorAll (which returns a collection, from which you must proceed to select the first element in it).


问:
Visual Studio 2017 debug inspection not working anymore
I used to be able to inspect the MenuItems property of my UWP NavigationView, but all of a sudden Visual Studio is telling me to enable native code debugging. What setting have I changed that caused this and how do I get it back? Super annoying!

Also, I've already tried resetting my Visual Studio settings, loaded symbols, and enabled symbol cache.

答: Check that you are still in debug mode and haven't changed the project to release, or any of the dependent projects to release.  Worth eliminating the obvious.</p>


问:
Fetching data from Greenplum table in the order of 600 million in Apache NiFi is giving GC overhead limit exceeded
I am trying to fetch data from Greenplum table using Apache NiFi - QueryDatabaseTableRecord. I am seeing GC overhead limit exceeded error and the NiFi webpage becomes unresponsive.

I have set the 'Fetch Size' property to 10000 but it seems the property is not being used in this case.

Other settings:

Database Type : Generic

Max Rows Per Flow File : 1000000

Output Batch Size : 2

jvm min/max memory allocation is 4g/8g

Is there an alternative to avoid the GC errors for this task ?

答:
this is a clear case of the "Fetch Size" parameter not being used, see processor info on this.
  Try to test the jdbc setFetchsize on its own to see if it works.</p>


问:
How can i pass iterator of one map function to another function as argument
I have 2 map function in my file. I want the iterator variable of the second map function to be passed as an argument of another function on every button click. Fairly new to react so do not know what should i do to make it correct

```<code>return (
<Table className={classes.table} aria-labelledby="tableTitle">
        <EnhancedTableHead />

        <TableBody>
          {dataList.map((item, item_idx) => {

return (
                <TableRow
                  hover
                  tabIndex={-1}
                  key={item.id}
                >
                  <TableCell padding="checkbox">
                  </TableCell>
                  <TableCell  padding="none">
                      {item.dataName}--{item.datatId}
                  </TableCell>
                  <TableCell padding="none"  ><SwitchButton/></TableCell>
                  <TableCell    >

{
  this.state.user.map((ab, ab_idx) =>
  <li className = "display">

{isSwitchOn === false ?  <input  type = 'search' placeholder = "id"  id="name" name = "name"  onChange={(e) => this.handleidChange(e,ab_idx)}/>: " All"}
{isSwitchOn === false ? <a href="javascript:void(0)" className = "removeIcon" style={{display:(this.state.user.length > 1 )? "inline" : "none"}} onClick={() => {this.removeItem(this.state,ab_idx)}}   >Remove</a> : "" }

</li>
     )}

</TableCell>
                  <TableCell  padding="none">
                   <Button className="user-edit-btn" style={{display:(isSwitchOn === false) ? "block" : "none", textTransform: 'capitalize',}}  variant="contained" onClick={() => {this.insertTextBox(item)}}  >
                  Add User
                  </Button>
                </TableCell>
                </TableRow>
              );

            })}

          {(
            <TableRow style={{ height: 49 }}>
              <TableCell colSpan={6} />
            </TableRow>
          )}
        </TableBody>
      </Table>
)
</code>```

I want "ab" to be passed as an argument of the function insertTextBox(item) whenever I click on ADD USER Button. While doing that gives me an error "Error: Adjacent JSX elements must be wrapped in an enclosing tag.
Did you want Fragment??"

答:
You need to bind handleidChange in  your constructor like this:

this.handleidChange = this.handleidChange.bind(this)

Then your handler should be like this:

```<code>handleidChange(ab_idx, e){
   //do smth
}
</code>```

Then pass the handler this way:

```<code><input  type = 'search' placeholder = "id"  id="name" name = "name"
onChange={this.handleidChange.bind(this, ab_idx)}/>`
</code>```

Body:
I have 2 map function in my file. I want the iterator variable of the second map function to be passed as an argument of another function on every button click. Fairly new to react so do not know what should i do to make it correct

return (

        <EnhancedTableHead />

        <TableBody>
          {dataList.map((item, item_idx) => {

return (
                <TableRow
                  hover
                  tabIndex={-1}
                  key={item.id}
                >
                  <TableCell padding="checkbox">
                  </TableCell>
                  <TableCell  padding="none">
                      {item.dataName}--{item.datatId}
                  </TableCell>
                  <TableCell padding="none"  ><SwitchButton/></TableCell>
                  <TableCell    >

{
  this.state.user.map((ab, ab_idx) =>

{isSwitchOn === false ?  <input  type = 'search' placeholder = "id"  id="name" name = "name"  onChange={(e) => this.handleidChange(e,ab_idx)}/>: " All"}
{isSwitchOn === false ?  1 )? "inline" : "none"}} onClick={() => {this.removeItem(this.state,ab_idx)}}   >Remove : "" }

     )}

</TableCell>
                  <TableCell  padding="none">
                   <Button className="user-edit-btn" style={{display:(isSwitchOn === false) ? "block" : "none", textTransform: 'capitalize',}}  variant="contained" onClick={() => {this.insertTextBox(item)}}  >
                  Add User
                  </Button>
                </TableCell>
                </TableRow>
              );

            })}

          {(
            <TableRow style={{ height: 49 }}>
              <TableCell colSpan={6} />
            </TableRow>
          )}
        </TableBody>

)

I want "ab" to be passed as an argument of the function insertTextBox(item) whenever I click on ADD USER Button. While doing that gives me an error "Error: Adjacent JSX elements must be wrapped in an enclosing tag.
Did you want Fragment??"

Body:
You need to bind handleidChange in  your constructor like this:

this.handleidChange = this.handleidChange.bind(this)

Then your handler should be like this:

handleidChange(ab_idx, e){
   //do smth
}

Then pass the handler this way:

<input  type = 'search' placeholder = "id"  id="name" name = "name"
onChange={this.handleidChange.bind(this, ab_idx)}/>`


问:
Convert UIView to UIImage to save as binary data in Core Data
I am trying to save a UIView as a UIImage to save in the Core Data database. My code is causing a compile error at self.canVasView.image stating:

Value of type 'UIView' has no member 'image'.

I think part of this code works in Swift 4 but it is not working in Swift 5.

```<code>var canVasView = UIView()

@objc func hhh() {
    let photo = self.canVasView.image
    let data = UIImagePNGRepresentation(photo!)

    if cdHandler.saveObject(pic:  data!){
    }
}
</code>```

答:
You need to use a specific subclass of UIView.

Try using:

```<code>var canVasView = UIImageView()
</code>```

Of course, you need to actually set the .image property to some UIImage in order for the call to UIImagePNGRepresentation to actually work.

Body:
I am trying to save a UIView as a UIImage to save in the Core Data database. My code is causing a compile error at self.canVasView.image stating:

Value of type 'UIView' has no member 'image'.

I think part of this code works in Swift 4 but it is not working in Swift 5.

var canVasView = UIView()

@objc func hhh() {
    let photo = self.canVasView.image
    let data = UIImagePNGRepresentation(photo!)

    if cdHandler.saveObject(pic:  data!){
    }
}

Body:
You need to use a specific subclass of UIView.

Try using:

var canVasView = UIImageView()

Of course, you need to actually set the .image property to some UIImage in order for the call to UIImagePNGRepresentation to actually work.


问:
PHP Problem with array_count_values
I need to get one time occurence on my array, with my code I get only first result here is my example code:

```<code>$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
    if($arrs[$arr[$i]]==1)
    {
        //do something...in this example i expect to receive b c and d
    }
}
</code>```

Thanks in advance

ciao h

答:
```<code>$arr=array("a","a","b","c","d");
$result = array();
$doubles = array();
while( !empty( $arr ) ) {
    $value = array_pop( $arr );
    if( !in_array( $value, $arr )
            && !in_array( $value, $doubles ) ) {
        $result[] = $value;
    }
    else {
        $doubles[] = $value;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP Problem with array_count_values

Body:
I need to get one time occurence on my array, with my code I get only first result here is my example code:

$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
    if($arrs[$arr[$i]]==1)
    {
        //do something...in this example i expect to receive b c and d
    }
}

Thanks in advance

ciao h


问:
How do I count the number of records that have one or more associated object?
I have a Property model that has_many :photos. I want to count the number of properties that have one or more photo.

How do I do that?

I have tried the simple:

```<code>> Property.where('properties.photos.count > ?', 0).count

   (3.1ms)  SELECT COUNT(*) FROM "properties" WHERE (properties.photos.count > 1)
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....
                                                  ^
: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos.count > 0)
from /ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....
</code>```

to:

```<code>> Property.joins(:photos).where('photos.count > ?', 0).count

   (3.7ms)  SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
: SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
</code>```

to the more advanced:

```<code>>Property.includes(:photos).group(['property.id', 'photos.id']).order('COUNT(photos.id) DESC').count

(0.6ms)  SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...
                                                             ^
: SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...
</code>```

and a few other variations, and they all produce similar errors.

What am I doing wrong?

Note: All I want is the count of properties that have photos.count > 0. I don't want a hash of all the properties and the count of photos. In other words, if there are 5000 properties in my db, I want to build a scope that returns just the properties that actually have photos.

答:
Give this a go:

```<code>class Property < ApplicationRecord
  has_many :photos

  def self.with_photos
    self.all.reject { |p| p.photos.empty? }
  end
end

Property.with_photos.count
</code>```

Source

More Efficient (Rails 4+):

```<code>Property.joins(:photos).uniq.count
</code>```

Source

More Efficient (Rails 5.1+):

```<code>Property.joins(:photos).distinct.count
</code>```

Source

Body:
I have a Property model that has_many :photos. I want to count the number of properties that have one or more photo.

How do I do that?

I have tried the simple:

> Property.where('properties.photos.count > ?', 0).count

   (3.1ms)  SELECT COUNT(*) FROM "properties" WHERE (properties.photos.count > 1)
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....
                                                  ^
: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos.count > 0)
from /ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....

to:

> Property.joins(:photos).where('photos.count > ?', 0).count

   (3.7ms)  SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
: SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...

to the more advanced:

>Property.includes(:photos).group(['property.id', 'photos.id']).order('COUNT(photos.id) DESC').count

(0.6ms)  SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...
                                                             ^
: SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...

and a few other variations, and they all produce similar errors.

What am I doing wrong?

Note: All I want is the count of properties that have photos.count > 0. I don't want a hash of all the properties and the count of photos. In other words, if there are 5000 properties in my db, I want to build a scope that returns just the properties that actually have photos.

Body:
Give this a go:

class Property < ApplicationRecord
  has_many :photos

  def self.with_photos
    self.all.reject { |p| p.photos.empty? }
  end
end

Property.with_photos.count

Source

More Efficient (Rails 4+):

Property.joins(:photos).uniq.count

Source

More Efficient (Rails 5.1+):

Property.joins(:photos).distinct.count

Source


问:
automated django receive hook on server: respond to collectstatic with "yes"
I'm using a Github post-recieve hook to run a bash file that pulls both my repos.

```<code>#!/bin/sh
cd ~/public_html/repo_static
env -i /usr/bin/git pull origin master
cd ~/django-code/repo_django
env -i /usr/bin/git pull origin master
</code>```

I also want to collectstatic on the django repo. How do I automate the "yes" response to that?

I can't use Fabric because unfortunately the team chose to work with Python 2.4 for the time being. Is there a way to automate collectstatic without Fabric?

答:
If you'd like to specify the default answer, you could also just pipe it into the command:

$ echo yes | python manage.py collectstatic
```
<p>or</p>
<pre class="lang-sh prettyprint-override"><code>$ echo no | python manage.py collectstatic
</code>```

Body:
I'm using a Github post-recieve hook to run a bash file that pulls both my repos.

#!/bin/sh
cd ~/public_html/repo_static
env -i /usr/bin/git pull origin master
cd ~/django-code/repo_django
env -i /usr/bin/git pull origin master

I also want to collectstatic on the django repo. How do I automate the "yes" response to that?

I can't use Fabric because unfortunately the team chose to work with Python 2.4 for the time being. Is there a way to automate collectstatic without Fabric?

Body:
If you'd like to specify the default answer, you could also just pipe it into the command:

$ echo yes | python manage.py collectstatic

or

$ echo no | python manage.py collectstatic


问:
'flutter' is not recognized in windows cmd prompt with elevated permissions
Flutter path is correct but still unable to be recognized by the windows command prompt. Looked everywhere asked anyone who used flutter still unable to figure out the problem.

Tried suggestions made on other questions similar to this still no luck and followed the tutorials on installing flutter did not work.

答:
The command prompt you're using appears to be using elevated permissions and therefore will have the "system" environment variables but not your user ones necessarily. Try with a non-elevated command prompt... which you should be using anyways. Only use an elevated command prompt when absolutely needed as otherwise you could delete important things by accident. Also, you can run echo %PATH% to see what is actually in the path in the command prompt you're using.

If you want to use flutter across multiple users or need to use an elevated command prompt for some reason, add the path to flutter/bin to the system environment variables instead.


问:
How to add a known type to a List<T>?
The overall goal here is like this:  We have a lot of CSV files of various names and format stored in Azure blob storage.  We need to convert them to lists.

I have an interface:

```<code>public interface IGpasData
{
    List<T> ConvertToList<T>(StreamReader reader);
}
</code>```

And then here's an example of a class that Implements it:

```<code>public class GpasTableOfContent : IGpasData
{
    public string TocProp0 { get; set; }
    public string TocProp1 { get; set; }
    public string TocProp2 { get; set; }

    public List<T> ConvertToList<T>(StreamReader reader)
    {
        List<T> dataList = new List<T>();
        while (!reader.EndOfStream)
        {
            var lineItem = reader.ReadLine();
            GpasTableOfContent dataItem = new GpasTableOfContent
            {
                TocProp0 = lineItem.Split(',')[0],
                TocProp1 = lineItem.Split(',')[1],
                Type = lineItem.Split(',')[2]
            };
            dataList.Add(dataItem);
        }
        return dataList;
    }
}
</code>```

To keep going with the example of the class above, there is a file called ToC.csv.  In a class that is designed to convert THAT file into a list, I make this call:

```<code>List<GpasTableOfContent> gpasToCList = ConvertCloudFileToList<GpasTableOfContent>("ToC.csv", "MyModel");
</code>```

Some other possible examples:

```<code>List<GpasFoo> gpasFooList = ConvertCloudFileToList<GpasFoo>("foo.csv", "MyModel");

List<GpasBar> gpasBarList = ConvertCloudFileToList<GpasBar>("bar.csv", "MyModel");
</code>```

Here's ConvertCloudFileToList:

```<code>private List<T> ConvertCloudFileToList<T>(string fileName, string modelName)
    {
        // Get the .csv file from the InProgress Directory
        string filePath = $"{modelName}/{fileName}";
        CloudFile cloudFile = _inProgressDir.GetFileReference(filePath);

        List<T> dataList = new List<T>();

        // Does the file exist?
        if (!cloudFile.Exists())
            return dataList;

        using (StreamReader reader = new StreamReader(cloudFile.OpenRead()))
        {
            IGpasData gpasData = (IGpasData)Activator.CreateInstance<T>();
            dataList = gpasData.ConvertToList<T>(reader);
        }

        return dataList;
    }
</code>```

And that brings us back to ConvertToList.  The problem is here:

```<code>dataList.Add(dataItem);
</code>```

Can not convert 'GpasFoo' to 'T'

Not sure how to work around this.

答:
Any object that is an IGpasData is expected to be able to produce a List of any given type when provided with a StreamReader. GpasTableOfContent does not fulfill this requirement, it can only produce a list of its own type.

However it doesn't seem reasonable to have one type of GpasData be responsible for converting everything so I'd suggest moving the Type argument from the ConvertToList method into the interface. This way subclasses will only be responsible for converting lists of a particular type.

```<code>public interface IGpasData<T>
{
    List<T> ConvertToList(StreamReader reader);
}

public class GpasTableOfContent : IGpasData<GpasTableOfContent>
{
    //...

    public List<GpasTableOfContent> ConvertToList(StreamReader reader)
    {
        //...
    }
}
</code>```

On a side note, creating an empty table of contents and then using it to read from a stream and produce a list of the real table of contents seems very clunky to me. In my opinion, the behaviour of creating these content objects should be moved into its own class.

Title: How to add a known type to a List<T>?

Body:
The overall goal here is like this:  We have a lot of CSV files of various names and format stored in Azure blob storage.  We need to convert them to lists.

I have an interface:

public interface IGpasData
{
    List<T> ConvertToList<T>(StreamReader reader);
}

And then here's an example of a class that Implements it:

public class GpasTableOfContent : IGpasData
{
    public string TocProp0 { get; set; }
    public string TocProp1 { get; set; }
    public string TocProp2 { get; set; }

    public List<T> ConvertToList<T>(StreamReader reader)
    {
        List<T> dataList = new List<T>();
        while (!reader.EndOfStream)
        {
            var lineItem = reader.ReadLine();
            GpasTableOfContent dataItem = new GpasTableOfContent
            {
                TocProp0 = lineItem.Split(',')[0],
                TocProp1 = lineItem.Split(',')[1],
                Type = lineItem.Split(',')[2]
            };
            dataList.Add(dataItem);
        }
        return dataList;
    }
}

To keep going with the example of the class above, there is a file called ToC.csv.  In a class that is designed to convert THAT file into a list, I make this call:

List<GpasTableOfContent> gpasToCList = ConvertCloudFileToList<GpasTableOfContent>("ToC.csv", "MyModel");

Some other possible examples:

List<GpasFoo> gpasFooList = ConvertCloudFileToList<GpasFoo>("foo.csv", "MyModel");

List<GpasBar> gpasBarList = ConvertCloudFileToList<GpasBar>("bar.csv", "MyModel");

Here's ConvertCloudFileToList:

private List<T> ConvertCloudFileToList<T>(string fileName, string modelName)
    {
        // Get the .csv file from the InProgress Directory
        string filePath = $"{modelName}/{fileName}";
        CloudFile cloudFile = _inProgressDir.GetFileReference(filePath);

        List<T> dataList = new List<T>();

        // Does the file exist?
        if (!cloudFile.Exists())
            return dataList;

        using (StreamReader reader = new StreamReader(cloudFile.OpenRead()))
        {
            IGpasData gpasData = (IGpasData)Activator.CreateInstance<T>();
            dataList = gpasData.ConvertToList<T>(reader);
        }

        return dataList;
    }

And that brings us back to ConvertToList.  The problem is here:

dataList.Add(dataItem);

Can not convert 'GpasFoo' to 'T'

Not sure how to work around this.

Body:
Any object that is an IGpasData is expected to be able to produce a List of any given type when provided with a StreamReader. GpasTableOfContent does not fulfill this requirement, it can only produce a list of its own type.

However it doesn't seem reasonable to have one type of GpasData be responsible for converting everything so I'd suggest moving the Type argument from the ConvertToList method into the interface. This way subclasses will only be responsible for converting lists of a particular type.

public interface IGpasData<T>
{
    List<T> ConvertToList(StreamReader reader);
}

public class GpasTableOfContent : IGpasData<GpasTableOfContent>
{
    //...

    public List<GpasTableOfContent> ConvertToList(StreamReader reader)
    {
        //...
    }
}

On a side note, creating an empty table of contents and then using it to read from a stream and produce a list of the real table of contents seems very clunky to me. In my opinion, the behaviour of creating these content objects should be moved into its own class.


问:
Data ended at 64512 characters - MSSQL // PHP // OPENSuSE // APACHE2
I am connecting to an mssql db on a Windows Server using the FREETDS driver for Linux via PHP.

The web server running the application in running OPENSuSE, Apache2 with PHP, FreeTDS drivers to connect to the Windows box, which it does fine.

I can execute the stored procedure and view the data that it produces, but the outputted data for each array value seems to stop at 64512 bytes (checked using strlen in PHP) - is this a problem on the PHP side or the MS side? Does anyone know how I can fix it?

答:
Have you checked your config file and increased the text size?  See the FAQ

```<code>1> set textsize 10000
2> go
</code>```

See also the text size option in freetds.conf

Body:
Have you checked your config file and increased the text size?  See the FAQ

1> set textsize 10000
2> go

See also the text size option in freetds.conf


答:
.sort mutates the original array, so when you have

```<code>array1.map(arr =>
</code>```

the arr there refers to the existing sub-array - if you call .sort on it, you'll change that sub-array.

Make a copy of the array first instead:

```<code>const sortedRows = array1.map(arr => arr.slice().sort((a, b) => a - b))
</code>```

let array1 = [[5, 3, 4, 6, 7, 8, 9, 1, 2],
             [6, 7, 2, 1, 9, 5, 3, 4, 8],
             [1, 9, 8, 3, 4, 2, 5, 6, 7],
             [8, 5, 9, 7, 6, 1, 4, 2, 3],
             [4, 2, 6, 8, 5, 3, 7, 9, 1],
             [7, 1, 3, 9, 2, 4, 8, 5, 6],
             [9, 6, 1, 5, 3, 7, 2, 8, 4],
             [2, 8, 7, 4, 1, 9, 6, 3, 5],
             [3, 4, 5, 2, 8, 6, 1, 7, 9]];

const sortedRows = array1.map(arr => arr.slice().sort((a, b) => a - b));

document.write(array1.join('
'));
document.write('

' + sortedRows.join('
'));```

Title: Sorting within .map affects the original array instead of returning new array

Body:
I have a 2d array of numbers: array1. I would like to map over each array within array1 and sort the numbers in each array and return them to a new array: sortedRows. I know that mapping over an array returns a new array, however when I sort each internal array during the mapping process, it sorts all numbers within array1 as well as sortedRows.

I've already tried separately mapping array1 to rows and then map/sorting to sortedRows and I've tried copying with the spread operator (rows = [...array1]). Both attempts get the same result below.

let array1 = [[5, 3, 4, 6, 7, 8, 9, 1, 2],
             [6, 7, 2, 1, 9, 5, 3, 4, 8],
             [1, 9, 8, 3, 4, 2, 5, 6, 7],
             [8, 5, 9, 7, 6, 1, 4, 2, 3],
             [4, 2, 6, 8, 5, 3, 7, 9, 1],
             [7, 1, 3, 9, 2, 4, 8, 5, 6],
             [9, 6, 1, 5, 3, 7, 2, 8, 4],
             [2, 8, 7, 4, 1, 9, 6, 3, 5],
             [3, 4, 5, 2, 8, 6, 1, 7, 9]]

let sortedRows = array1.map(arr => arr.sort((a, b) => a - b))

console.log(array1)
console.log(sortedRows)
// expected

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

//actual

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

Body:
.sort mutates the original array, so when you have

array1.map(arr =>

the arr there refers to the existing sub-array - if you call .sort on it, you'll change that sub-array.

Make a copy of the array first instead:

const sortedRows = array1.map(arr => arr.slice().sort((a, b) => a - b))

let array1 = [[5, 3, 4, 6, 7, 8, 9, 1, 2],
             [6, 7, 2, 1, 9, 5, 3, 4, 8],
             [1, 9, 8, 3, 4, 2, 5, 6, 7],
             [8, 5, 9, 7, 6, 1, 4, 2, 3],
             [4, 2, 6, 8, 5, 3, 7, 9, 1],
             [7, 1, 3, 9, 2, 4, 8, 5, 6],
             [9, 6, 1, 5, 3, 7, 2, 8, 4],
             [2, 8, 7, 4, 1, 9, 6, 3, 5],
             [3, 4, 5, 2, 8, 6, 1, 7, 9]];

const sortedRows = array1.map(arr => arr.slice().sort((a, b) => a - b));

document.write(array1.join('<br>'));
document.write('<br><br><br>' + sortedRows.join('<br>'));


问:
Create DOM ID with php variables using php foreach loop

Background

I am embedding tweets with Twitter's Javascript factory function. Documentation here.

This Twitter's Javascript embed function:

```<code>    twttr.widgets.createTweet(
      '20',
      document.getElementById('container'),
      {
        theme: 'dark';
      }
    );
</code>```

Documentation states that an element with DOM ID of 'container' is needed in the document.

```<code>    <div id="container"></div>
</code>```

What I'm doing with this function

The example above provided by Twitter's documentation embeds a tweet that has the id "20".  On my page I am embedding the first x amount of tweets about a specific topic using the id's provided in a JSON response from a searchTweets query. The response is stored in $string as json_decoded string.

My problem:

I need to loop through the elements in the JSON response to get the id's of the tweets to put in the twttrwidgets.createTweet function.

I am hardcoding the createTweet function four times currently - the only dynamic bit is creating the elements and DOM ID's to pass in to each of the functions.

Attempt 1: Foreach loop create  and increment the ID's

```<code>    <?php

    $i = 1;
    foreach ($string as $tweets)
    {
    //echo '<div id="tweet'.$i'" tweetID'.$i'="'$tweets['id']'"></div>';
    ?>

      <div id="tweet.<?php echo $i?>" tweetID.<?php echo $i?>="<?php echo         $tweets['id']?>"></div>
    <?php
    //  echo "<div id='tweet' tweetID='1130852255945486337'></div>"
      $i++;
    }
     ?>
</code>```

Note I have confirmed that $tweets['id'] gives the id's in the json response as I have tested by simply printing out all $tweets['id'] to the page

The goal is for that loop  to create something like this

```<code>    <div id="tweet1" tweetID1="123abc"></div>
    <div id="tweet2" tweetID2="123abc"></div>
    <div id="tweet3" tweetID3="123abc"></div>
    <div id="tweet4" tweetID4="123abc"></div>
</code>```

I understand the way I currently have the loop, it would create as many div's as there were elements in the JSON - that is okay with me for now.

With that I would create the tweets with the follwing code.

```<code>    <script>

    window.onload = (function(){

    var tweet1 = document.getElementById("tweet1");
    var id1 = tweet1.getAttribute("tweetID1");

    var tweet2 = document.getElementById("tweet2");
    var id2 = tweet2.getAttribute("tweetID2");

    var tweet3 = document.getElementById('tweet3');
    var id3 = tweet3.getAttribute("tweetID3");

    var tweet4 = document.getElementById("tweet4");
    var id4 = tweet4.getAttribute("tweetID4");

    twttr.widgets.createTweet(
      id1, tweet1,
      {
        conversation : 'none',    // or all
        cards        : 'hidden',  // or visible
        linkColor    : '#cc0000', // default is blue
        theme        : 'light',    // or dark
        align        : 'center'
      })
    .then (function (el) {
      el.contentDocument.querySelector(".footer").style.display = "none";
    });

  //3 more blocks just like twttr.widgets.createTweet(){...} with correct params
</code>```

This did not work and I can't figure out why.  This code works if I hard code in 4 of the id's like I mention in the goal of the loop. Here it is again.

```<code>    <div id="tweet1" tweetID1="123abc"></div>
    <div id="tweet2" tweetID2="123abc"></div>
    <div id="tweet3" tweetID3="123abc"></div>
    <div id="tweet4" tweetID4="123abc"></div>
</code>```

Here is my entire php script. Note this does not include the APIwrapper file included in the beginning and my tokens and keys have been redacted.

```<code>    <?php

    //echo "<h2>Simple Twitter API Test</h2>";

    require_once('TwitterAPIExchange.php');

    /** Set access tokens here - see: https://dev.twitter.com/apps/ **/
    $settings = array(
        'oauth_access_token' => "",
        'oauth_access_token_secret' => "",
        'consumer_key' => "",
        'consumer_secret' => ""
    );

    $url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
    $requestMethod = "GET";
    if (isset($_GET['user']))  {$user = preg_replace("/[^A-Za-z0-9_]/", '', $_GET['user']);}  else {$user  = "iagdotme";}
    if (isset($_GET['count']) && is_numeric($_GET['count'])) {$count = $_GET['count'];} else {$count = 20;}
    $getfield = "?screen_name=$user&count=$count";
    $twitter = new TwitterAPIExchange($settings);
    $string = json_decode($twitter->setGetfield($getfield)
    ->buildOauth($url, $requestMethod)
    ->performRequest(),$assoc = TRUE);
    if(array_key_exists("errors", $string)) {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();}

     ?>

    <?php

    $i = 1;
    foreach ($string as $tweets)
    {
      echo '<div id="tweet'.$i'" tweetID'.$i'="'$tweets['id']'"></div>';
    //  echo "<div id='tweet' tweetID='1130852255945486337'></div>"
      $i++;
    }
     ?>

    <html><body>

    <script sync src="https://platform.twitter.com/widgets.js"></script>

    <script>

      window.onload = (function(){

        var tweet1 = document.getElementById("tweet1");
        var id1 = tweet1.getAttribute("tweetID1");

        var tweet2 = document.getElementById("tweet2");
        var id2 = tweet2.getAttribute("tweetID2");

        var tweet3 = document.getElementById('tweet3');
        var id3 = tweet3.getAttribute("tweetID3");

        var tweet4 = document.getElementById("tweet4");
        var id4 = tweet4.getAttribute("tweetID4");

        twttr.widgets.createTweet(
          id1, tweet1,
          {
            conversation : 'none',    // or all
            cards        : 'hidden',  // or visible
            linkColor    : '#cc0000', // default is blue
            theme        : 'light',    // or dark
            align        : 'center'
          })
        .then (function (el) {
          el.contentDocument.querySelector(".footer").style.display = "none";
        });

        twttr.widgets.createTweet(
          id2, tweet2,
          {
            conversation : 'none',    // or all
            cards        : 'hidden',  // or visible
            linkColor    : '#cc0000', // default is blue
            theme        : 'light',    // or dark
            align        : 'center'
          })
        .then (function (el) {
          el.contentDocument.querySelector(".footer").style.display = "none";
        });

        twttr.widgets.createTweet(
          id3, tweet3,
          {
            conversation : 'none',    // or all
            cards        : 'hidden',  // or visible
            linkColor    : '#cc0000', // default is blue
            theme        : 'light',    // or dark
            align        : 'center'
          })
        .then (function (el) {
          el.contentDocument.querySelector(".footer").style.display = "none";
        });

        twttr.widgets.createTweet(
          id4, tweet4,
          {
            conversation : 'none',    // or all
            cards        : 'hidden',  // or visible
            linkColor    : '#cc0000', // default is blue
            theme        : 'light',    // or dark
            align        : 'center'
          })
        .then (function (el) {
          el.contentDocument.querySelector(".footer").style.display = "none";
        });

      });

    </script>
    </body></html>
</code>```

I believe the problem is in creating the

 elements dynamically, but I cannot seem to understand why at this point.  Am I doing this correctly? I'm sure there is a much more efficient way of doing this, but this seems like it should be working.

My issue is unique to the possible duplicate provided because the issue is not with attaching an event to an ID, rather the actual creation of the ID itself, and my problem is specifically in php.

答:
You missed some concat operators in this line.

```<code>// What you have
echo '<div id="tweet'.$i'" tweetID'.$i'="'$tweets['id']'"></div>';

// Correct
echo '<div id="tweet'.$i.'" tweetID'.$i.'="'.$tweets['id'].'"></div>';
</code>```

Also note Chay22's comment about your output being outside the html tags. Everything else is fine.

Body:
Background

I am embedding tweets with Twitter's Javascript factory function. Documentation here.

This Twitter's Javascript embed function:

    twttr.widgets.createTweet(
      '20',
      document.getElementById('container'),
      {
        theme: 'dark';
      }
    );

Documentation states that an element with DOM ID of 'container' is needed in the document.

What I'm doing with this function

The example above provided by Twitter's documentation embeds a tweet that has the id "20".  On my page I am embedding the first x amount of tweets about a specific topic using the id's provided in a JSON response from a searchTweets query. The response is stored in $string as json_decoded string.

My problem:

I need to loop through the elements in the JSON response to get the id's of the tweets to put in the twttrwidgets.createTweet function.

I am hardcoding the createTweet function four times currently - the only dynamic bit is creating the elements and DOM ID's to pass in to each of the functions.

Attempt 1: Foreach loop create  and increment the ID's

    <?php

    $i = 1;
    foreach ($string as $tweets)
    {
    //echo '

';
    ?>

      <div id="tweet.<?php echo $i?>" tweetID.<?php echo $i?>="<?php echo         $tweets['id']?>">

    <?php
    //  echo "

"
      $i++;
    }
     ?>

Note I have confirmed that $tweets['id'] gives the id's in the json response as I have tested by simply printing out all $tweets['id'] to the page

The goal is for that loop  to create something like this

I understand the way I currently have the loop, it would create as many div's as there were elements in the JSON - that is okay with me for now.

With that I would create the tweets with the follwing code.

I believe the problem is in creating the

 elements dynamically, but I cannot seem to understand why at this point.  Am I doing this correctly? I'm sure there is a much more efficient way of doing this, but this seems like it should be working.

My issue is unique to the possible duplicate provided because the issue is not with attaching an event to an ID, rather the actual creation of the ID itself, and my problem is specifically in php.

Body:
You missed some concat operators in this line.

// What you have
echo '<div id="tweet'.$i'" tweetID'.$i'="'$tweets['id']'"></div>';

// Correct
echo '<div id="tweet'.$i.'" tweetID'.$i.'="'.$tweets['id'].'"></div>';

Also note Chay22's comment about your output being outside the html tags. Everything else is fine.


问:
Matrix multiplication translation from Matlab to Numpy
I'm trying to multiply some arrays together but can't seem to figure out how to do it. I'm translating some linear algebra code from MatLab and can't seem to get it to work the same in Numpy due to Matlab using column-major indexing and Python using row-major indexing.

I've managed to get the matrices to multiply, but I've not managed to get the same result as the one in Matlab.

I have three arrays:

```<code>a.shape = 40x40 in Python, 40x40 in Matlab, zeroes array
b.shape = 40x21 in Python, 21x40 in Matlab, array with < 1 float values
c.shape = 31x40 in Python, 40x31 in Matlab, array with < 1 float values
</code>```

The math I'm trying to copy from Matlab is:

    D = b*(a*c);
    disp(size(D));  % Size of D is 21x31
```

<p>When I try and do the same with NumPy:</p>

<pre class="lang-py prettyprint-override"><code>D = b @ (a @ c)
</code>```

It obviously doesn't work since c is 31x40 and can't multiply with A (40x40).

I've managed to get the multiplication to actually work by using:

D = np.transpose(np.transpose(b) @ (a @ np.transpose(c)))
```

but the resulting D in Numpy is different from the one in Matlab, although the dimensions are correct (31x21).

If anyone has any ideas how to do this or even if it's not possible please let me know!

答:
nope just run it with random numbers
differences are limited to rounding errors

quick simple example to check correct matrix sizes:

```<code>import numpy as np
np.__version__
#'1.16.3'
a = np.ones([40,40])
b = np.ones([21,40])
c = np.ones([40,31])
#%%
a_mult_c = a @ c
a_mult_c.shape()
# (40, 31)
#%%
D = b @ a_mult_c
D.shape
# (21, 31)
</code>```

for a detailed random number example load an run these numbers

https://jsonblob.com/c240c380-81a2-11e9-8287-ef9cd282f8ed

assuming you copy, paste and save it to 'matrixmult.json'
matlab:

```<code>fid = fopen('matrixmult.json', 'r');
values = jsondecode(fread(fid, '*char')'));
fclose(fid);
</code>```

python:

```<code>import numpy as np
np.__version__
# '1.16.3'
import json
with open('matrixmult.json', 'r') as f:  # py > 3.6
    values = json.load(f)
a = np.asarray(values['a'])
b = np.asarray(values['b'])
c = np.asarray(values['c'])

D = b @ (a @ c)
D == np.asarray(values['D'])
</code>```

Body:
I'm trying to multiply some arrays together but can't seem to figure out how to do it. I'm translating some linear algebra code from MatLab and can't seem to get it to work the same in Numpy due to Matlab using column-major indexing and Python using row-major indexing.

I've managed to get the matrices to multiply, but I've not managed to get the same result as the one in Matlab.

I have three arrays:

a.shape = 40x40 in Python, 40x40 in Matlab, zeroes array
b.shape = 40x21 in Python, 21x40 in Matlab, array with < 1 float values
c.shape = 31x40 in Python, 40x31 in Matlab, array with < 1 float values

The math I'm trying to copy from Matlab is:

    D = b*(a*c);
    disp(size(D));  % Size of D is 21x31

When I try and do the same with NumPy:

D = b @ (a @ c)

It obviously doesn't work since c is 31x40 and can't multiply with A (40x40).

I've managed to get the multiplication to actually work by using:

D = np.transpose(np.transpose(b) @ (a @ np.transpose(c)))

but the resulting D in Numpy is different from the one in Matlab, although the dimensions are correct (31x21).

If anyone has any ideas how to do this or even if it's not possible please let me know!

Body:
nope just run it with random numbers
differences are limited to rounding errors

quick simple example to check correct matrix sizes:

import numpy as np
np.__version__
#'1.16.3'
a = np.ones([40,40])
b = np.ones([21,40])
c = np.ones([40,31])
#%%
a_mult_c = a @ c
a_mult_c.shape()
# (40, 31)
#%%
D = b @ a_mult_c
D.shape
# (21, 31)

for a detailed random number example load an run these numbers

https://jsonblob.com/c240c380-81a2-11e9-8287-ef9cd282f8ed

assuming you copy, paste and save it to 'matrixmult.json'
matlab:

fid = fopen('matrixmult.json', 'r');
values = jsondecode(fread(fid, '*char')'));
fclose(fid);

python:

import numpy as np
np.__version__
# '1.16.3'
import json
with open('matrixmult.json', 'r') as f:  # py > 3.6
    values = json.load(f)
a = np.asarray(values['a'])
b = np.asarray(values['b'])
c = np.asarray(values['c'])

D = b @ (a @ c)
D == np.asarray(values['D'])


问:
Convert string decimal numbers in column to float in a Pandas DataFrame
I have a dataset like this (with many more columns):

```<code>      FLAG__DC SEXECOND CRM_TAUX
0            N        M      0,9
1            N        M      0,9
2            N        M      1,2
3            O        M        1
4            N        M        1
5            N        M      0,9
6            O        M        1
7            N        M      0,9
</code>```

I want to convert the column CRM_TAUX to Float... Please help!

I have tried this but doesn't work:

```<code>df['CRM_TAUX'] = df.CRM_TAUX.replace(',','.')
df['CRM_TAUX'] = df.CRM_TAUX.apply(pd.to_numeric)
</code>```

This is the error I get (and many more):

```<code>Unable to parse string "1,2" at position 0
</code>```

Thanks in advance!

答:
Use str.replace

```<code>df.CRM_TAUX.str.replace(',' , '.')

Out[2246]:
0    0.9
1    0.9
2    1.2
3      1
4      1
5    0.9
6      1
7    0.9
Name: CRM_TAUX, dtype: object
</code>```

Next, call pd.to_numeric  on it should work

```<code>s = df.CRM_TAUX.str.replace(',' , '.')
df['CRM_TAUX'] = pd.to_numeric(s)

Out[2250]:
  FLAG__DC SEXECOND  CRM_TAUX
0        N        M       0.9
1        N        M       0.9
2        N        M       1.2
3        O        M       1.0
4        N        M       1.0
5        N        M       0.9
6        O        M       1.0
7        N        M       0.9
</code>```

Body:
I have a dataset like this (with many more columns):

      FLAG__DC SEXECOND CRM_TAUX
0            N        M      0,9
1            N        M      0,9
2            N        M      1,2
3            O        M        1
4            N        M        1
5            N        M      0,9
6            O        M        1
7            N        M      0,9

I want to convert the column CRM_TAUX to Float... Please help!

I have tried this but doesn't work:

df['CRM_TAUX'] = df.CRM_TAUX.replace(',','.')
df['CRM_TAUX'] = df.CRM_TAUX.apply(pd.to_numeric)

This is the error I get (and many more):

Unable to parse string "1,2" at position 0

Thanks in advance!

Body:
Use str.replace

df.CRM_TAUX.str.replace(',' , '.')

Out[2246]:
0    0.9
1    0.9
2    1.2
3      1
4      1
5    0.9
6      1
7    0.9
Name: CRM_TAUX, dtype: object

Next, call pd.to_numeric  on it should work

s = df.CRM_TAUX.str.replace(',' , '.')
df['CRM_TAUX'] = pd.to_numeric(s)

Out[2250]:
  FLAG__DC SEXECOND  CRM_TAUX
0        N        M       0.9
1        N        M       0.9
2        N        M       1.2
3        O        M       1.0
4        N        M       1.0
5        N        M       0.9
6        O        M       1.0
7        N        M       0.9


问:
How to pass the values from one scenario to another scenario in gatling?
I have some end to end flow where I have to run a service and pass values to the next scenario. I can print the values inside the scenarios but not able to use them to next scenarios.

I tried to save the values using SaveAs

```<code>val scn_Token1 ={ scenario("Token1")
    .exec(actionBuilder = http("Token1")
      .post("/getToken")
      .body(StringBody(bdy_Token)).asJson
      .check(status.is(200))
      .check(jsonPath("$.Token").exists)
      .check(jsonPath("$..Token")
        .find
        .saveAs("Token")
      )
      .check(jsonPath("$..id")
        .find
        .saveAs("mid")
      )
      .check(jsonPath("$..otp")
        .find
        .saveAs("otp")
      )
    )pause(tnk_token milliseconds)
  }

  val scn_Auth ={ scenario("Authentication")
    .exec(actionBuilder = http("Authentication")
      .post(authServiceUrl)
      .header("Token", "${Token}")
      .header("id", "${id}")
      .header("otp", "${otp}")
      .body(StringBody(bdy_Auth)).asJson
      .check(status.is(200)))
      .pause(tnk_Auth milliseconds)
  }

  setUp(
   scn_Token1.inject(nothingFor(dly_token_first seconds),rampUsers(ucnt_token_first) during (ramp_token_first seconds)).protocols(httpConfToken),
  scn_Auth.inject(nothingFor(dly_Auth seconds),rampUsers(ucnt_Auth) during (ramp_Auth seconds)).protocols(httpConf)
  ).maxDuration(test_duration minutes)
</code>```

I am getting error like

'httpRequest-2' failed to execute: No attribute named 'id' is defined

'httpRequest-2' failed to execute: No attribute named 'Token' is defined

I also tried having wait time for second scenario in a way it will execute after scenario 1 completes. But still it doesn't get the values.

Please note that I don't want the to merge token and Auth in single scenario as it has different configuration. values should be passed from one scenario to another. Please let me know what is going wrong here?

答:
Gatling can't pass data between users - if you need to execute scn_Token before each scn_Auth request to set a session parameter, just include it in scn_Token.

Redefine scn_Auth to be

```<code>  val scn_Auth ={ scenario("Authentication")
.exec(scn_Token1)
.exec(actionBuilder = http("Authentication")
  .post(authServiceUrl)
  .header("Token", "${Token}")
  .header("id", "${id}")
  .header("otp", "${otp}")
  .body(StringBody(bdy_Auth)).asJson
  .check(status.is(200)))
  .pause(tnk_Auth milliseconds)
}
</code>```

and then only inject users for scn_Auth

Body:
I have some end to end flow where I have to run a service and pass values to the next scenario. I can print the values inside the scenarios but not able to use them to next scenarios.

I tried to save the values using SaveAs

val scn_Token1 ={ scenario("Token1")
    .exec(actionBuilder = http("Token1")
      .post("/getToken")
      .body(StringBody(bdy_Token)).asJson
      .check(status.is(200))
      .check(jsonPath("$.Token").exists)
      .check(jsonPath("$..Token")
        .find
        .saveAs("Token")
      )
      .check(jsonPath("$..id")
        .find
        .saveAs("mid")
      )
      .check(jsonPath("$..otp")
        .find
        .saveAs("otp")
      )
    )pause(tnk_token milliseconds)
  }

  val scn_Auth ={ scenario("Authentication")
    .exec(actionBuilder = http("Authentication")
      .post(authServiceUrl)
      .header("Token", "${Token}")
      .header("id", "${id}")
      .header("otp", "${otp}")
      .body(StringBody(bdy_Auth)).asJson
      .check(status.is(200)))
      .pause(tnk_Auth milliseconds)
  }

  setUp(
   scn_Token1.inject(nothingFor(dly_token_first seconds),rampUsers(ucnt_token_first) during (ramp_token_first seconds)).protocols(httpConfToken),
  scn_Auth.inject(nothingFor(dly_Auth seconds),rampUsers(ucnt_Auth) during (ramp_Auth seconds)).protocols(httpConf)
  ).maxDuration(test_duration minutes)

I am getting error like

'httpRequest-2' failed to execute: No attribute named 'id' is defined

'httpRequest-2' failed to execute: No attribute named 'Token' is defined

I also tried having wait time for second scenario in a way it will execute after scenario 1 completes. But still it doesn't get the values.

Please note that I don't want the to merge token and Auth in single scenario as it has different configuration. values should be passed from one scenario to another. Please let me know what is going wrong here?

Body:
Gatling can't pass data between users - if you need to execute scn_Token before each scn_Auth request to set a session parameter, just include it in scn_Token.

Redefine scn_Auth to be

  val scn_Auth ={ scenario("Authentication")
.exec(scn_Token1)
.exec(actionBuilder = http("Authentication")
  .post(authServiceUrl)
  .header("Token", "${Token}")
  .header("id", "${id}")
  .header("otp", "${otp}")
  .body(StringBody(bdy_Auth)).asJson
  .check(status.is(200)))
  .pause(tnk_Auth milliseconds)
}

and then only inject users for scn_Auth


问:
F# Moq returns "Invalid setup on a static member"

in the repository interface file

```<code>type public IAccountRepository =
    abstract member Find: email:string -> firstname:string -> lastname:string -> Account
</code>```

in the test file

```<code>open Moq
let mutable accountRepository = Mock<IAccountRepository>(MockBehavior.Strict)
accountRepository.Setup( fun rep -> rep.Find "aaa" "bbb" "ccc" ).Returns(account) |> ignore
</code>```

accountRepository.Setup at runtime raises this error:

    System.NotSupportedException : Invalid setup on a static member: rep =>
    FSharpFunc.InvokeFast
    (FuncConvert.ToFSharpFunc

Note. I DON'T want to change my method into
 this:

abstract member Find: email:string * firstname:string * lastname:string

Note 2 [added]

I don't want to use an Object Expression like this:

```<code>let accountRepository_2 = {
    new IAccountRepository with
        member __.Find a b c = account   // <--- this is the only mock I need
        member __.Create x = ()
        member __.Delete x = ()
        member __.FindByMobile x = account
        member __.FindByWallet x y = account
        member __.Read x = account
    }
</code>```

is not a viable solution: I have 3 repositories and 2 other providers to inject... and I don't think is clean at all for this case.

What is that error?

Any idea of how to mock that method ?

[Update]

I updated Moq from 4.10.1 to 4.11.0. The error is changed:

```<code>System.NotSupportedException : Unsupported expression: ... =>
FSharpFunc<string, string>.InvokeFast<string, Account>(...
</code>```

I'm using NSubstitute:

```<code>let accountRepository = Substitute.For<IAccountRepository>()
(accountRepository.Find "aaa" "bbb" "ccc").Returns(account) |> ignore
</code>```

and it works.

答:
I would not expect that there is a way to get this to work with Moq. The Moq library assumes that code follows usual C# coding practices and the way F# compiles methods with multiple parameters in a curried form is just not the way C# would ever define it.

When you write the following in F#:

```<code>accountRepository.Setup(fun rep ->
  rep.Find "aaa" "bbb" "ccc")
</code>```

Moq actually sees something that looks more like:

```<code>accountRepository.Setup(fun rep ->
  rep.Find("aaa").Invoke("bbb").Invoke("ccc"))
</code>```

Actually, it is even worse than this, because F# does an optimization when the compiler can statically determine the number of parameters and collapses some of the calls into InvokeFast call:

```<code>accountRepository.Setup(fun rep ->
  rep.Find("aaa").InvokeFast("bbb", "ccc"))
</code>```

A tool that does not know about this has no way of figuring out that this actually means calling Find with three arguments.

I think the best option would be to change the method signature (despite the fact that you explicitly said you did not want to do this). Alternatively, you could add a lightweitght wrapper for testing purposes. Yet another option would be to try the F# mocking library Foq and see if that handles this case better.

Body:
in the repository interface file

type public IAccountRepository =
    abstract member Find: email:string -> firstname:string -> lastname:string -> Account

in the test file

open Moq
let mutable accountRepository = Mock<IAccountRepository>(MockBehavior.Strict)
accountRepository.Setup( fun rep -> rep.Find "aaa" "bbb" "ccc" ).Returns(account) |> ignore

accountRepository.Setup at runtime raises this error:

    System.NotSupportedException : Invalid setup on a static member: rep =>
    FSharpFunc.InvokeFast
    (FuncConvert.ToFSharpFunc

Note. I DON'T want to change my method into
 this:

abstract member Find: email:string * firstname:string * lastname:string

Note 2 [added]

I don't want to use an Object Expression like this:

let accountRepository_2 = {
    new IAccountRepository with
        member __.Find a b c = account   // <--- this is the only mock I need
        member __.Create x = ()
        member __.Delete x = ()
        member __.FindByMobile x = account
        member __.FindByWallet x y = account
        member __.Read x = account
    }

is not a viable solution: I have 3 repositories and 2 other providers to inject... and I don't think is clean at all for this case.

What is that error?

Any idea of how to mock that method ?

[Update]

I updated Moq from 4.10.1 to 4.11.0. The error is changed:

System.NotSupportedException : Unsupported expression: ... =>
FSharpFunc<string, string>.InvokeFast<string, Account>(...

I'm using NSubstitute:

let accountRepository = Substitute.For<IAccountRepository>()
(accountRepository.Find "aaa" "bbb" "ccc").Returns(account) |> ignore

and it works.

Body:
I would not expect that there is a way to get this to work with Moq. The Moq library assumes that code follows usual C# coding practices and the way F# compiles methods with multiple parameters in a curried form is just not the way C# would ever define it.

When you write the following in F#:

accountRepository.Setup(fun rep ->
  rep.Find "aaa" "bbb" "ccc")

Moq actually sees something that looks more like:

accountRepository.Setup(fun rep ->
  rep.Find("aaa").Invoke("bbb").Invoke("ccc"))

Actually, it is even worse than this, because F# does an optimization when the compiler can statically determine the number of parameters and collapses some of the calls into InvokeFast call:

accountRepository.Setup(fun rep ->
  rep.Find("aaa").InvokeFast("bbb", "ccc"))

A tool that does not know about this has no way of figuring out that this actually means calling Find with three arguments.

I think the best option would be to change the method signature (despite the fact that you explicitly said you did not want to do this). Alternatively, you could add a lightweitght wrapper for testing purposes. Yet another option would be to try the F# mocking library Foq and see if that handles this case better.


问:
Issue when updating XML to varchar SQL column
I am updating some XML via code in C# and when I insert it into my database (varchar column) I am seeing a extra ?. I think this has to do with the Encoding.UTF8 I am doing. The ? is NOT there all the way through the process of calling SaveChanges() in EF core.

The database column in varchar and cannot be changed due to the way it was set up etc.

I'm not sure how I should convert the xml back to string after saving it from the dashboard (which is dev express)

```<code>      internal static async Task<string> ConvertXmlToNewConnectionStrings(string xml, List<ConnectionSourceViewModel> connectionSourceViews, int currentUserId)
        {
            var connectionStringOptions = await GetConnectionStringOptions(currentUserId).ConfigureAwait(false);

            System.Xml.Linq.XDocument doc;
            using (StringReader s = new StringReader(xml))
            {
                doc = System.Xml.Linq.XDocument.Load(s);
            }

            Dashboard d = new Dashboard();
            d.LoadFromXDocument(doc);
            var sqlDataSources = d.DataSources.OfType<DashboardSqlDataSource>().ToList();

            foreach (var item in sqlDataSources)
            {
                // We do not want the properties in the data source anymore... this includes user name and password etc... the new way dev ex went with this functionality
                item.ConnectionParameters = null;

                // get the selected connection string from the end user
                var connectionStringId = connectionSourceViews.Where(x => x.SqlDataSourceComponentName == item.ComponentName).Select(x => x.SelectedConnectionStringId).FirstOrDefault();

                if (string.IsNullOrWhiteSpace(connectionStringId) == false)
                {
                    item.ConnectionName = connectionStringOptions.Where(x => x.Value == connectionStringId).Select(x => x.Text).FirstOrDefault();
                }
            }

            MemoryStream ms = new MemoryStream();
            d.SaveToXml(ms);
            byte[] array = ms.ToArray();
            ms.Close();
            xml = Encoding.UTF8.GetString(array, 0, array.Length);

            return xml;
        }
</code>```

I'm expecting the ? is not be added to the XML in the database column of varchar after saving it via EF Core

Image of ? at start:
https://ibb.co/LZ2QVtr

答:
I ended up removing the code that does a MemoryStream() and went to saving the document back to the XDocument().

```<code>doc = d.SaveToXDocument();
</code>```

Now everything works fine and no question mark (?) is put in the database!

Body:
I am updating some XML via code in C# and when I insert it into my database (varchar column) I am seeing a extra ?. I think this has to do with the Encoding.UTF8 I am doing. The ? is NOT there all the way through the process of calling SaveChanges() in EF core.

The database column in varchar and cannot be changed due to the way it was set up etc.

I'm not sure how I should convert the xml back to string after saving it from the dashboard (which is dev express)

      internal static async Task<string> ConvertXmlToNewConnectionStrings(string xml, List<ConnectionSourceViewModel> connectionSourceViews, int currentUserId)
        {
            var connectionStringOptions = await GetConnectionStringOptions(currentUserId).ConfigureAwait(false);

            System.Xml.Linq.XDocument doc;
            using (StringReader s = new StringReader(xml))
            {
                doc = System.Xml.Linq.XDocument.Load(s);
            }

            Dashboard d = new Dashboard();
            d.LoadFromXDocument(doc);
            var sqlDataSources = d.DataSources.OfType<DashboardSqlDataSource>().ToList();

            foreach (var item in sqlDataSources)
            {
                // We do not want the properties in the data source anymore... this includes user name and password etc... the new way dev ex went with this functionality
                item.ConnectionParameters = null;

                // get the selected connection string from the end user
                var connectionStringId = connectionSourceViews.Where(x => x.SqlDataSourceComponentName == item.ComponentName).Select(x => x.SelectedConnectionStringId).FirstOrDefault();

                if (string.IsNullOrWhiteSpace(connectionStringId) == false)
                {
                    item.ConnectionName = connectionStringOptions.Where(x => x.Value == connectionStringId).Select(x => x.Text).FirstOrDefault();
                }
            }

            MemoryStream ms = new MemoryStream();
            d.SaveToXml(ms);
            byte[] array = ms.ToArray();
            ms.Close();
            xml = Encoding.UTF8.GetString(array, 0, array.Length);

            return xml;
        }

I'm expecting the ? is not be added to the XML in the database column of varchar after saving it via EF Core

Image of ? at start:
https://ibb.co/LZ2QVtr

Body:
I ended up removing the code that does a MemoryStream() and went to saving the document back to the XDocument().

doc = d.SaveToXDocument();

Now everything works fine and no question mark (?) is put in the database!