问:
Can't print correctly the size of a mongo query
I'm currently trying to print the content of a mongo query by casting it to a list and then trying to access to the length of that list, I'm using the following code:

```<code>from pymongo import MongoClient
from elasticsearch import Elasticsearch
from datetime import datetime
from dateutil.parser import parse
from pprint import pprint

client = MongoClient('...')
db_profile = client['...-profiles']

collection_profile = db_profile['profiles']

# print(collection_profile.count())

querydate = datetime(2020, 1, 1)
year = querydate.year
month = querydate.month
yesterday = querydate.day
dateStr = str(year) + "-" + str(month) + "-" + str(yesterday)
date = parse(dateStr)

result = collection_profile.find({'createdAt': {'$gte': date}})
pprint(list(result)) # Here I got the data correctly
print(len(list(result))) # Here I got 0 as result
</code>```

If I switch the position of the last 2 lines, I got the correct size, but then an empty list.
What could be wrong? Is there a better method to access to the content of a query using pymongo?

答:
Because the find function is an iterator, you can only go through it once.  After your first pprint(list(result)) the result iterator has reached the end of the query. From then on it won't return any more data.

You would need to store the first list conversion in a variable in order to access the content again:

```<code>resultList = list(result)
pprint(resultList)     # will use list that is now in memory
print(len(resultList)) # this will work
</code>```

If you have a very large result set, this may cause a memory overflow or performance degradation.  Mongo can return the count using the collection's count() function to which you can pass the same query object.

Body:
I'm currently trying to print the content of a mongo query by casting it to a list and then trying to access to the length of that list, I'm using the following code:

from pymongo import MongoClient
from elasticsearch import Elasticsearch
from datetime import datetime
from dateutil.parser import parse
from pprint import pprint

client = MongoClient('...')
db_profile = client['...-profiles']

collection_profile = db_profile['profiles']

# print(collection_profile.count())

querydate = datetime(2020, 1, 1)
year = querydate.year
month = querydate.month
yesterday = querydate.day
dateStr = str(year) + "-" + str(month) + "-" + str(yesterday)
date = parse(dateStr)

result = collection_profile.find({'createdAt': {'$gte': date}})
pprint(list(result)) # Here I got the data correctly
print(len(list(result))) # Here I got 0 as result

If I switch the position of the last 2 lines, I got the correct size, but then an empty list.
What could be wrong? Is there a better method to access to the content of a query using pymongo?

Body:
Because the find function is an iterator, you can only go through it once.  After your first pprint(list(result)) the result iterator has reached the end of the query. From then on it won't return any more data.

You would need to store the first list conversion in a variable in order to access the content again:

resultList = list(result)
pprint(resultList)     # will use list that is now in memory
print(len(resultList)) # this will work

If you have a very large result set, this may cause a memory overflow or performance degradation.  Mongo can return the count using the collection's count() function to which you can pass the same query object.


来源: stackexchange

问:
get only changed objects from observed array with rxjs
I have an array of objects (not primitives) called "streaks" on my state tree and I want to observe only the changes to that array, not simply emit the entire array every time it changes.  When I try this using pairwise() I get two identical arrays every time, even though I thought pairwise() would join the previous version and the current version.  Why is pairwise() sending two identical arrays?  NOTE streaks[1] and streaks[0] are identical, so _.differenceBy() isn't finding any changes because the two arrays are the same.

```<code>import {from} from "rxjs";
import {map, pairwise} from "rxjs/operators";
import * as _ from 'lodash';

  const state$ = from(store);
  const streaks$ = state$.pipe(
      map(state => state.streaks),
      // distinctUntilChanged(), <-- i've tried this and nothing is output at all
      pairwise(),
      map(streaks => {
        let diff = _.differenceBy(streaks[0], streaks[1], _.isEqual);
        console.log('diff', diff); //<-- this is an empty array
        return diff;
      })
  );

  streaks$.subscribe((streaksArray) => {
    console.log('STREAKS$ 0', streaksArray); //<-- this is never even hit
  } );
</code>```

答:
I solved this issue by creating an distinctUntilChangedArray operator that uses a self written compareArray function

Create compare array function

```<code>const compareArray<T> = (first: T[], second: T[], comparator=: (obj: T, obj2: T) => boolean): boolean {
  return (first.length === 0 && second.length === 0)
    || (first.length === second.length && first.every((value, index) => {
         return comparator
           ? comparator(value, second[index])
           : JSON.stringify(value) === JSON.stringify(second[index]);
    }))
}

</code>```

Maybe you find a better array comparator. This is just my personal implementation of it

Create distinctUntilChangedArray operator

```<code>
const distinctUntilChangedArray<T> = (comparator?: (prev: T, curr: T) => boolean): MonoTypeOperatorFunction<T[]> {
  return distinctUntilChanged((prev: T[], curr: T[]) => {
    return compareArray(first, second, comparator);
  }
}
</code>```

Final usage

```<code>interface nonPrimitive {
  id: number;
  name: string;
}

const nonPrimitiveComparator = (prev: nonPrimitive, curr: nonPrimitive): boolean => {
  return prev.id === curr.id && prev.name === curr.name;
}

const source$: Observable<nonPrimitive>;

const distinctedSource$ = source$.pipe(
  distinctUntilChangedArray(nonPrimitiveComparator)
);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an array of objects (not primitives) called "streaks" on my state tree and I want to observe only the changes to that array, not simply emit the entire array every time it changes.  When I try this using pairwise() I get two identical arrays every time, even though I thought pairwise() would join the previous version and the current version.  Why is pairwise() sending two identical arrays?  NOTE streaks[1] and streaks[0] are identical, so _.differenceBy() isn't finding any changes because the two arrays are the same.

import {from} from "rxjs";
import {map, pairwise} from "rxjs/operators";
import * as _ from 'lodash';

  const state$ = from(store);
  const streaks$ = state$.pipe(
      map(state => state.streaks),
      // distinctUntilChanged(), <-- i've tried this and nothing is output at all
      pairwise(),
      map(streaks => {
        let diff = _.differenceBy(streaks[0], streaks[1], _.isEqual);
        console.log('diff', diff); //<-- this is an empty array
        return diff;
      })
  );

  streaks$.subscribe((streaksArray) => {
    console.log('STREAKS$ 0', streaksArray); //<-- this is never even hit
  } );

Body:
I solved this issue by creating an distinctUntilChangedArray operator that uses a self written compareArray function

Create compare array function

const compareArray<T> = (first: T[], second: T[], comparator=: (obj: T, obj2: T) => boolean): boolean {
  return (first.length === 0 && second.length === 0)
    || (first.length === second.length && first.every((value, index) => {
         return comparator
           ? comparator(value, second[index])
           : JSON.stringify(value) === JSON.stringify(second[index]);
    }))
}

Maybe you find a better array comparator. This is just my personal implementation of it

Create distinctUntilChangedArray operator

const distinctUntilChangedArray<T> = (comparator?: (prev: T, curr: T) => boolean): MonoTypeOperatorFunction<T[]> {
  return distinctUntilChanged((prev: T[], curr: T[]) => {
    return compareArray(first, second, comparator);
  }
}

Final usage

interface nonPrimitive {
  id: number;
  name: string;
}

const nonPrimitiveComparator = (prev: nonPrimitive, curr: nonPrimitive): boolean => {
  return prev.id === curr.id && prev.name === curr.name;
}

const source$: Observable<nonPrimitive>;

const distinctedSource$ = source$.pipe(
  distinctUntilChangedArray(nonPrimitiveComparator)
);


问:
Linear algebra in keras layer
I'm trying to implement the scipy.lingalg.null_space module as a Lambda layer in keras.
My input is in the form of batches of numpy arrays of shape (5,5), but a simple

```<code>def ns(x_array):
    x_array = np.array(x_array)
    return null_space(x_array)

null = keras.layers.Lambda(lambda x: ns(x) )(input)
</code>```

yields the error message:

```<code>
~/miniconda3/lib/python3.7/site-packages/scipy/linalg/decomp_svd.py in null_space(A, rcond)
    382
    383     """
--> 384     u, s, vh = svd(A, full_matrices=True)
    385     M, N = u.shape[0], vh.shape[1]
    386     if rcond is None:

~/miniconda3/lib/python3.7/site-packages/scipy/linalg/decomp_svd.py in svd(a, full_matrices, compute_uv, overwrite_a, check_finite, lapack_driver)
    107
    108     """
--> 109     a1 = _asarray_validated(a, check_finite=check_finite)
    110     if len(a1.shape) != 2:
    111         raise ValueError('expected matrix')

~/miniconda3/lib/python3.7/site-packages/scipy/_lib/_util.py in _asarray_validated(a, check_finite, sparse_ok, objects_ok, mask_ok, as_inexact)
    240     if not objects_ok:
    241         if a.dtype is np.dtype('O'):
--> 242             raise ValueError('object arrays are not supported')
    243     if as_inexact:
    244         if not np.issubdtype(a.dtype, np.inexact):

ValueError: object arrays are not supported
</code>```

I think I have to force the input to null_space  to be a 2-dimensional array (rather than the 3-dimensional shape of each batch) but I'm not sure how to do this.

答:
You can re-implement the null_space with keras/tensorflow. Refer to the scipy source https://github.com/scipy/scipy/blob/v1.4.1/scipy/linalg/decomp_svd.py#L333-L391

The implementation looks straightforward. You will have to use svd, though, so you can use tf.linalg.svd.

Edit: I typically don't do this, but I was curious, so here is a tensorflow implementation of null_space. The outputs are close to but not exactly equal to those of scipy.

import numpy as np
import tensorflow as tf

float32_eps = np.finfo(np.float32).eps

def tf_null_space(A, rcond=None):
    s, u, vh = tf.linalg.svd(A, full_matrices=True)
    vh = tf.transpose(vh)
    M, N = u.shape[0], vh.shape[1]
    if rcond is None:
        rcond = float32_eps * max(M, N)
    tol = tf.reduce_max(s) * rcond
    num = tf.reduce_sum(tf.cast(s > tol, tf.int32))
    Q = tf.math.conj(tf.transpose(vh[num:, :]))
    return Q
```

Title: Linear algebra in keras layer

Body:
I'm trying to implement the scipy.lingalg.null_space module as a Lambda layer in keras.
My input is in the form of batches of numpy arrays of shape (5,5), but a simple

def ns(x_array):
    x_array = np.array(x_array)
    return null_space(x_array)

null = keras.layers.Lambda(lambda x: ns(x) )(input)

yields the error message:

~/miniconda3/lib/python3.7/site-packages/scipy/linalg/decomp_svd.py in null_space(A, rcond)
    382
    383     """
--> 384     u, s, vh = svd(A, full_matrices=True)
    385     M, N = u.shape[0], vh.shape[1]
    386     if rcond is None:

~/miniconda3/lib/python3.7/site-packages/scipy/linalg/decomp_svd.py in svd(a, full_matrices, compute_uv, overwrite_a, check_finite, lapack_driver)
    107
    108     """
--> 109     a1 = _asarray_validated(a, check_finite=check_finite)
    110     if len(a1.shape) != 2:
    111         raise ValueError('expected matrix')

~/miniconda3/lib/python3.7/site-packages/scipy/_lib/_util.py in _asarray_validated(a, check_finite, sparse_ok, objects_ok, mask_ok, as_inexact)
    240     if not objects_ok:
    241         if a.dtype is np.dtype('O'):
--> 242             raise ValueError('object arrays are not supported')
    243     if as_inexact:
    244         if not np.issubdtype(a.dtype, np.inexact):

ValueError: object arrays are not supported

I think I have to force the input to null_space  to be a 2-dimensional array (rather than the 3-dimensional shape of each batch) but I'm not sure how to do this.


问:
Discord.js var with username outputs "undefined"
```<code>if (message.reactions.size) {
    let reaction = message.reactions.find(r => r._emoji.name == '');
    if (reaction) {
    var winnaar = reaction.users.random;

  }
}
</code>```

So this is for a discord.js giveaway bot, and what its meant to do is store a random users name who reacted in the "winnaar" (winner in dutch) variable. But when I make the bot send a message containing ${winnaar} it outputs "Undifined". I am quite new to Discord js and I would appreciate any help.

答:
Look at this link Discord random

Here you can see that random is function, try with random(1)

Body:
if (message.reactions.size) {
    let reaction = message.reactions.find(r => r._emoji.name == '');
    if (reaction) {
    var winnaar = reaction.users.random;

  }
}

So this is for a discord.js giveaway bot, and what its meant to do is store a random users name who reacted in the "winnaar" (winner in dutch) variable. But when I make the bot send a message containing ${winnaar} it outputs "Undifined". I am quite new to Discord js and I would appreciate any help.


问:
Creating Private API
I am trying to create a very simple api gateway in aws. This api doesn't need any authentication.

The problem is I have depoloyed the app in ec2 instance and when I access the application's api with IP on the browser, it returns the output in JSON format.

For. Eg.

on Chrome/Curl - http:/10.x.x.x:9090/service/test

But when I do http integration in API gateway with same url as endpoint, and hit test it gives me "500 internal server error". I have already tried the following -

Create an API as private one.

Enable resource policy with VPC endpoint

There is no authentication required to access API(I am able to see it in chrome)

But still I get the problem. Any insight or help is greatly appreciated.

Thanks.

答:
500 Internal Server errors should be checked in the execution CloudWatch logs of the API. These errors indicate -

The API either failed to hit the integration (Lambda, HTTP etc.) or

The integration request returned an unsuccessful response.

The response received by the integration was not supported by the API (in case of proxy integrations)

Some examples of 5XX errors that can be seen in the logs which generate 500 Internal Server on the client-side:

502 Malformed Proxy - With a proxy integration, the response sent from the backend was not in the expected format.

504 Endpoint timed-out - The API failed to receive a response back in 29 seconds from the integration.

502 Bad Gateway -  usually for an incompatible output returned from a Lambda proxy integration backend and occasionally for out-of-order invocations due to heavy loads.

To enable CloudWatch executions logs, follow the steps here.

Read more about handling 5XX errors in API Gateway here.

Title: Creating Private API


问:
Find between two string date ranges in spring mongodb
I have Document Person like

```<code>{
  "_id": {
    "$oid": "5e44659dcd"
  },
  "record": {
    "Date_Of_Birth": "9/25/2018"
  },
  "_class": "com.example.entities.Birth"
}
</code>```

Record is of type object, Date_Of_Birth is of type String but Date has been stored in it and I want to execute query to use $gte and $lte operations on that. I am using spring data mongodb. It seems first I have to use $dateFromString to convert it to date, But this seems to be aggregation which I don't think I require.

Below is the code which I have created so far

```<code>Pageable pageable = PageRequest.of(page, size);
Query query = new Query(
        Criteria
                .where("record.Date_Of_Birth").gte(DateOperators.dateFromString(startDate).withFormat("mm/dd/yyyy"))
                .andOperator(Criteria.where("record.Date_Of_Birth").lte(DateOperators.dateFromString(endDate).withFormat("mm/dd/yyyy"))
)).with(pageable);
</code>```

which generates this query

```<code>{ "record.Date_Of_Birth" : { "$gte" : { "value" : { "dateString" : "9/25/2018", "format" : "mm/dd/yyyy"}}}, "$and" : [{ "record.Date_Of_Birth" : { "$lte" : { "value" : { "dateString" : "9/25/2018", "format" : "mm/dd/yyyy"}}}}]}
</code>```

and is not working at all. Any idea?

答:
$expr permits using aggregation operators inside the query.  This will permit you to convert the stored value to a date so you can do an apples to apples comparison.</p>

```<code>db.collection.find({
  $expr: {
    $gte: [
      {$dateFromString: {
           dateString: "$record.Date_Of_Birth",
           format: "%m/%d/%Y",
           timeZone: "EST5EDT"}},
      {$dateFromString: {
           dateString: "9/25/2018",
           format: "%m/%d/%Y",
           timeZone: "EST5EDT"}}
    ]
  }
})
</code>```

Body:
I have Document Person like

{
  "_id": {
    "$oid": "5e44659dcd"
  },
  "record": {
    "Date_Of_Birth": "9/25/2018"
  },
  "_class": "com.example.entities.Birth"
}

Record is of type object, Date_Of_Birth is of type String but Date has been stored in it and I want to execute query to use $gte and $lte operations on that. I am using spring data mongodb. It seems first I have to use $dateFromString to convert it to date, But this seems to be aggregation which I don't think I require.

Below is the code which I have created so far

Pageable pageable = PageRequest.of(page, size);
Query query = new Query(
        Criteria
                .where("record.Date_Of_Birth").gte(DateOperators.dateFromString(startDate).withFormat("mm/dd/yyyy"))
                .andOperator(Criteria.where("record.Date_Of_Birth").lte(DateOperators.dateFromString(endDate).withFormat("mm/dd/yyyy"))
)).with(pageable);

which generates this query

{ "record.Date_Of_Birth" : { "$gte" : { "value" : { "dateString" : "9/25/2018", "format" : "mm/dd/yyyy"}}}, "$and" : [{ "record.Date_Of_Birth" : { "$lte" : { "value" : { "dateString" : "9/25/2018", "format" : "mm/dd/yyyy"}}}}]}

and is not working at all. Any idea?

Body:
$expr permits using aggregation operators inside the query.  This will permit you to convert the stored value to a date so you can do an apples to apples comparison.

db.collection.find({
  $expr: {
    $gte: [
      {$dateFromString: {
           dateString: "$record.Date_Of_Birth",
           format: "%m/%d/%Y",
           timeZone: "EST5EDT"}},
      {$dateFromString: {
           dateString: "9/25/2018",
           format: "%m/%d/%Y",
           timeZone: "EST5EDT"}}
    ]
  }
})


问:
how to divide a list into 3 lists based on id's in java
I have some data stored in a list. Now I have to divide this list into 3 lists based on the id.

Can anyone please help me do this in java?

I have a list like [{partyRoleId: 1, partyId:001, name:keer},{prtyRoleId: 1, partyId: 002, name:swathi},{partyRoleId: 1, partyId:003, name:ashok},{partyRoleId: 2, partyId:004, name:nag},{partyRoleId: 2, partyId:005, name:meg},{partyRoleId: 3, partyId:006, name:praveen},{partyRoleId: 3, partyId:007, name:jay}],

this is the list which i have , now can u notice that partyRoleId is different of some group of people , i have to list group of people who have partyRoleId as 1 is one list partyRoleId as 2 in another list and partyRoleId as 3 in other list ....
basically i need 3 list from one list

答:
Use a stream operation for this.

```<code>    List<Person> data = Arrays.asList(
            new Person(1, "001", "keer"),
            new Person(1, "002", "swath"),
            new Person(1, "003", "ashok"),
            new Person(2, "004", "nag"),
            new Person(2, "005", "meg"),
            new Person(3, "006", "praveen"),
            new Person(3, "007", "jay"));

    Map<Integer, List<Person>> threeLists
            = data.stream().collect(Collectors.groupingBy(Person::getPartyRoleId));
</code>```

Now we’ve got a map of three lists. We can take out each individual list like this:

```<code>    List<Person> personsWithPartyRoleId1 = threeLists.get(1);
    System.out.println("Persons with partyRoleId 1: " + personsWithPartyRoleId1);
</code>```

```<code>Persons with partyRoleId 1: [{ 1, 001, keer }, { 1, 002, swath }, { 1, 003, ashok }]
</code>```

Similarly for the two other lists, of course. Or we can iterate all three lists in the map:

```<code>    threeLists.forEach((pri, list) -> System.out.println(
            "Persons with partyRoleId " + pri + ": " + list));
</code>```

```<code>Persons with partyRoleId 1: [{ 1, 001, keer }, { 1, 002, swath }, { 1, 003, ashok }]
Persons with partyRoleId 2: [{ 2, 004, nag }, { 2, 005, meg }]
Persons with partyRoleId 3: [{ 3, 006, praveen }, { 3, 007, jay }]
</code>```

Body:
Use a stream operation for this.

    List<Person> data = Arrays.asList(
            new Person(1, "001", "keer"),
            new Person(1, "002", "swath"),
            new Person(1, "003", "ashok"),
            new Person(2, "004", "nag"),
            new Person(2, "005", "meg"),
            new Person(3, "006", "praveen"),
            new Person(3, "007", "jay"));

    Map<Integer, List<Person>> threeLists
            = data.stream().collect(Collectors.groupingBy(Person::getPartyRoleId));

Now we’ve got a map of three lists. We can take out each individual list like this:

    List<Person> personsWithPartyRoleId1 = threeLists.get(1);
    System.out.println("Persons with partyRoleId 1: " + personsWithPartyRoleId1);

Persons with partyRoleId 1: [{ 1, 001, keer }, { 1, 002, swath }, { 1, 003, ashok }]

Similarly for the two other lists, of course. Or we can iterate all three lists in the map:

    threeLists.forEach((pri, list) -> System.out.println(
            "Persons with partyRoleId " + pri + ": " + list));

Persons with partyRoleId 1: [{ 1, 001, keer }, { 1, 002, swath }, { 1, 003, ashok }]
Persons with partyRoleId 2: [{ 2, 004, nag }, { 2, 005, meg }]
Persons with partyRoleId 3: [{ 3, 006, praveen }, { 3, 007, jay }]


问:
updating dataframe column in Scala
Given dataframe with columns A, B, and C, created with a "val x = ", I want to update a column like this:

```<code>x.withColumn("A", when ($"B" === "apple", "fruit").otherwise(col("C")))
</code>```

This doesn't actually change x, which I believe is expected. Most people I think would create a new dataframe:

```<code>val y = x.withColumn("A", when ($"B" === "apple", "fruit").otherwise(col("B")))
</code>```

And y has the update. But how do you change x with creating a new dataframe? I realize val x is immutable, but even when I declare "var x", it's the same behavior. It doesn't actually save the change.

Is that the Scala best practice, to always create a new DF?

答:
As per Spark Architecture DataFrame is built on top of RDDs which are immutable in nature, Hence Dataframes are also immutable in nature.

The withColumn or any other operation for that matter, on DataFrames, will generate a new data frame instead of updating the existing data frame.

```<code>val y = x.withColumn("A", when ($"B" === "apple", "fruit").otherwise(col("B")))
</code>```

You are just storing the result in val y.

Title: updating dataframe column in Scala

Body:
Given dataframe with columns A, B, and C, created with a "val x = ", I want to update a column like this:

x.withColumn("A", when ($"B" === "apple", "fruit").otherwise(col("C")))

This doesn't actually change x, which I believe is expected. Most people I think would create a new dataframe:

val y = x.withColumn("A", when ($"B" === "apple", "fruit").otherwise(col("B")))

And y has the update. But how do you change x with creating a new dataframe? I realize val x is immutable, but even when I declare "var x", it's the same behavior. It doesn't actually save the change.

Is that the Scala best practice, to always create a new DF?

Body:
As per Spark Architecture DataFrame is built on top of RDDs which are immutable in nature, Hence Dataframes are also immutable in nature.

The withColumn or any other operation for that matter, on DataFrames, will generate a new data frame instead of updating the existing data frame.

val y = x.withColumn("A", when ($"B" === "apple", "fruit").otherwise(col("B")))

You are just storing the result in val y.


问:
Could "content" of AttributedString can be saved in file?
I am doing some research on how to "draw"
some attributed text on Graphics2D.

So, i am interested is it possible to save
content of AttributedString in some format ?

I know it could be Java serialized,
but, i don't need that solution here.

Also, if somebody knows some example which shows
how to edit AttributedString ?

Here is some Java code, just to get idea:

```<code>public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

AttributedString as new AttributedString( "Lorem ipsum dolor sit amet..." );
Font font1 = new Font( "SansSerif" , Font.PLAIN , 20 );
as.addAttribute( TextAttribute.FONT       , font1       );
as.addAttribute( TextAttribute.FOREGROUND , Color.black );
as.addAttribute( TextAttribute.FOREGROUND , Color.blue , 4 , 9 );

AttributedCharacterIterator aci = as.getIterator();
FontRenderContext           frc = g2.getFontRenderContext();
LineBreakMeasurer           lbm = new LineBreakMeasurer( aci , frc );

TextLayout  textLayout = lbm.nextLayout( wrappingWidth );

int x = 50 , y = 50 ;
textLayout.draw( g2 , x , y );

}
</code>```

Thanx for any help or advice :)

答:
Obviously, the simplest method is java serialization, otherwise you will need to handle all the possible text attributes.
If you want an example, here is a report generator that I have written and that make extensive use of AttributedString. Hope it will help:
http://www.perry.ch/mo/pureport.zip</p>

OwnerDisplayName: Darko

ContentLicense: CC BY-SA 2.5

Body:
I am doing some research on how to "draw"
some attributed text on Graphics2D.

So, i am interested is it possible to save
content of AttributedString in some format ?

I know it could be Java serialized,
but, i don't need that solution here.

Also, if somebody knows some example which shows
how to edit AttributedString ?

Here is some Java code, just to get idea:

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

AttributedString as new AttributedString( "Lorem ipsum dolor sit amet..." );
Font font1 = new Font( "SansSerif" , Font.PLAIN , 20 );
as.addAttribute( TextAttribute.FONT       , font1       );
as.addAttribute( TextAttribute.FOREGROUND , Color.black );
as.addAttribute( TextAttribute.FOREGROUND , Color.blue , 4 , 9 );

AttributedCharacterIterator aci = as.getIterator();
FontRenderContext           frc = g2.getFontRenderContext();
LineBreakMeasurer           lbm = new LineBreakMeasurer( aci , frc );

TextLayout  textLayout = lbm.nextLayout( wrappingWidth );

int x = 50 , y = 50 ;
textLayout.draw( g2 , x , y );

}

Thanx for any help or advice :)

OwnerDisplayName: Maurice Perry


问:
Why should I avoid creating a MutableTuple<T1,T2,TEtc> class in C#?
I am a big fan of .NET 4.0's Tuple classes.

All the items in the Tuples are immutable.  There are clearly cases where this is beneficial (most obviously when Tuples are used to represent an ad hoc ValueType for which there is no declaration).

However, I have some use cases where I could see the benefit to a Tuple's items having setters (with the exception of the TRest Type parameter in the Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>).  Given that I have access to the source and to Matt Ellis's article on "Building Tuple", it seems like it would be pretty simple to implement such a MutableTuple<T1,T2,TEtc>.

There was clearly a decision by Microsoft to make the Tuple immutable.  Is there a reason that I am overlooking that I shouldn't create an alternate implementation with mutable non-tuple items?

答:
I created a read/write version for Afterthought.  However, based on API feedback from the community I elected to change the API to make it unnecessary.  However, my initial need was similar to yours, having strongly-typed parameter values for methods, and wanting Tuple-like behavior that was read/write and also .NET 3.5 compatible.  Here is my implementation, minus support for TRest:

```<code>/// <summary>
/// Abstract base class for generic <see cref="Parameter<T1>"/> family of classes
/// that represent parameters passed to constructors and methods.
/// </summary>
/// <remarks>
/// This class was created due to a desire to support .NET 3.5, which does not
/// include the <see cref="Tuple"/> class providing similar capabilities
/// </remarks>
public abstract class Parameter
{}

public class Parameter<T1> : Parameter
{
    public Parameter(T1 param1)
    {
        this.Param1 = param1;
    }

    public T1 Param1 { get; set; }
}

public class Parameter<T1, T2> : Parameter<T1>
{
    public Parameter(T1 param1, T2 param2)
        : base(param1)
    {
        this.Param2 = param2;
    }

    public T2 Param2 { get; set; }
}

public class Parameter<T1, T2, T3> : Parameter<T1, T2>
{
    public Parameter(T1 param1, T2 param2, T3 param3)
        : base(param1, param2)
    {
        this.Param3 = param3;
    }

    public T3 Param3 { get; set; }
}

public class Parameter<T1, T2, T3, T4> : Parameter<T1, T2, T3>
{
    public Parameter(T1 param1, T2 param2, T3 param3, T4 param4)
        : base(param1, param2, param3)
    {
        this.Param4 = param4;
    }

    public T4 Param4 { get; set; }
}

public class Parameter<T1, T2, T3, T4, T5> : Parameter<T1, T2, T3, T4>
{
    public Parameter(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5)
        : base(param1, param2, param3, param4)
    {
        this.Param5 = param5;
    }

    public T5 Param5 { get; set; }
}

public class Parameter<T1, T2, T3, T4, T5, T6> : Parameter<T1, T2, T3, T4, T5>
{
    public Parameter(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6)
        : base(param1, param2, param3, param4, param5)
    {
        this.Param6 = param6;
    }

    public T6 Param6 { get; set; }
}

public class Parameter<T1, T2, T3, T4, T5, T6, T7> : Parameter<T1, T2, T3, T4, T5, T6>
{
    public Parameter(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7)
        : base(param1, param2, param3, param4, param5, param6)
    {
        this.Param7 = param7;
    }

    public T7 Param7 { get; set; }
}

public class Parameter<T1, T2, T3, T4, T5, T6, T7, T8> : Parameter<T1, T2, T3, T4, T5, T6, T7>
{
    public Parameter(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8)
        : base(param1, param2, param3, param4, param5, param6, param7)
    {
        this.Param8 = param8;
    }

    public T8 Param8 { get; set; }
}
</code>```

I agree that it is nicer having Param1 than Item1 as it makes the usage more understandable.  I was fortunately able to move to ref-based delegates for the one scenario where I needed read/write behavior.  In my case I had to avoid introducing any classes into the solution.  Hope this helps!

ContentLicense: CC BY-SA 3.0

Body:
I created a read/write version for Afterthought.  However, based on API feedback from the community I elected to change the API to make it unnecessary.  However, my initial need was similar to yours, having strongly-typed parameter values for methods, and wanting Tuple-like behavior that was read/write and also .NET 3.5 compatible.  Here is my implementation, minus support for TRest:

/// <summary>
/// Abstract base class for generic <see cref="Parameter<T1>"/> family of classes
/// that represent parameters passed to constructors and methods.
/// </summary>
/// <remarks>
/// This class was created due to a desire to support .NET 3.5, which does not
/// include the <see cref="Tuple"/> class providing similar capabilities
/// </remarks>
public abstract class Parameter
{}

public class Parameter<T1> : Parameter
{
    public Parameter(T1 param1)
    {
        this.Param1 = param1;
    }

    public T1 Param1 { get; set; }
}

public class Parameter<T1, T2> : Parameter<T1>
{
    public Parameter(T1 param1, T2 param2)
        : base(param1)
    {
        this.Param2 = param2;
    }

    public T2 Param2 { get; set; }
}

public class Parameter<T1, T2, T3> : Parameter<T1, T2>
{
    public Parameter(T1 param1, T2 param2, T3 param3)
        : base(param1, param2)
    {
        this.Param3 = param3;
    }

    public T3 Param3 { get; set; }
}

public class Parameter<T1, T2, T3, T4> : Parameter<T1, T2, T3>
{
    public Parameter(T1 param1, T2 param2, T3 param3, T4 param4)
        : base(param1, param2, param3)
    {
        this.Param4 = param4;
    }

    public T4 Param4 { get; set; }
}

public class Parameter<T1, T2, T3, T4, T5> : Parameter<T1, T2, T3, T4>
{
    public Parameter(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5)
        : base(param1, param2, param3, param4)
    {
        this.Param5 = param5;
    }

    public T5 Param5 { get; set; }
}

public class Parameter<T1, T2, T3, T4, T5, T6> : Parameter<T1, T2, T3, T4, T5>
{
    public Parameter(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6)
        : base(param1, param2, param3, param4, param5)
    {
        this.Param6 = param6;
    }

    public T6 Param6 { get; set; }
}

public class Parameter<T1, T2, T3, T4, T5, T6, T7> : Parameter<T1, T2, T3, T4, T5, T6>
{
    public Parameter(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7)
        : base(param1, param2, param3, param4, param5, param6)
    {
        this.Param7 = param7;
    }

    public T7 Param7 { get; set; }
}

public class Parameter<T1, T2, T3, T4, T5, T6, T7, T8> : Parameter<T1, T2, T3, T4, T5, T6, T7>
{
    public Parameter(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8)
        : base(param1, param2, param3, param4, param5, param6, param7)
    {
        this.Param8 = param8;
    }

    public T8 Param8 { get; set; }
}

I agree that it is nicer having Param1 than Item1 as it makes the usage more understandable.  I was fortunately able to move to ref-based delegates for the one scenario where I needed read/write behavior.  In my case I had to avoid introducing any classes into the solution.  Hope this helps!


问:
Flatten multi-dimensional array to array with dot notation in Laravel
I am looking for a way to flatten this array:

```<code>$array = ['parent' => ['childA' => "value", 'childB' => "value"]];
</code>```

to:

```<code>$array = ['parent.childA' => "value", 'parent.childB' => "value"];
</code>```

Is there an elegant way to do this in Laravel? For example with Laravel Collections.

答:
For Laravel 5.7 and newer:

take a look at Arr::dot()

For Laravel 5.6 and older:

array_dot is the way to go (see Alexeys answer)

Body:
I am looking for a way to flatten this array:

$array = ['parent' => ['childA' => "value", 'childB' => "value"]];

to:

$array = ['parent.childA' => "value", 'parent.childB' => "value"];

Is there an elegant way to do this in Laravel? For example with Laravel Collections.


问:
Continuous deployment branch wise using Spinnaker
I'm using Jenkins multibranch pipeline for CI process and for CD using Spinnaker.

I've gone through almost all documents, support channels etc. from spinnaker for "how to create spinnaker multibranch pipeline similarly as jenkins" but didn't find anywhere.

After integrating jenkins to spinnaker, in drop down list of jenkins jobs in spinnaker pipeline configuration, it shows all multibranch jobs separately. Hence for each branch I'd need to go to spinnaker and create pipeline manually.

To solve this, I'm thinking this solution: while running jenkins multibranch pipeline job > create spinnaker pipeline(if not exist) using spin cli with required parameters(branch, version, trigger using jenkins of this running branch job etc) > and trigger the same created spinnaker pipeline after jenkins job executed.

Please advise if there is any other better way to accomplish this.

Thanks.

答:
I am not super familiar with the multibranch plugin, but you can make this simpler by doing [ triggers ] -> [ pipeline stage calling the same pipeline ] rather than calling the entire pipeline via the spin-cli.

Alternatively, if the list of jobs generated is small or well known, you could just update the list of triggers for the same pipeline programmatically as part of your release process.

i.e, in your jenkins job

add this job to list of triggers

run rest of jenkins job

job finishes, spinnaker pipeline triggers


问:
Show total number of rows in SQLite table
I am building a local database with this :

```<code>var db = openDatabase('LIST','1.0','database', 2*1024*1024);

db.transaction(function (tx) {
  tx.executeSql('CREATE TABLE IF NOT EXISTS entry (ID INTEGER PRIMARY KEY ASC, first TEXT, last TEXT, email TEXT, phone TEXT, contest TEXT, added_on DATETIME)');
});

db.transaction(function(tx){
  tx.executeSql('INSERT INTO entry (first, last, email, phone, contest, added_on) VALUES (?,?,?,?,?,?)',
  [vFirst, vLast, vEmail, vPhone, vContest, addedOn]);
});
</code>```

How would I populate a div with count of total rows in the database? I guess I would use something like SELECT COUNT(*) FROM entry .. but I am unclear on how to write this or print the output on the page.

If I was using local storage I see I could do something as simple as var length = window.localStorage.length; but I can not figure out how to do something similar with SQL.

答:
If you want to count all rows from entry table, then SELECT COUNT(*) FROM entry
If you want to know count of rows in database, then UNION queries from different tables and sum using SUM()

EDIT:

```<code>db.transaction(function(tx) {
   tx.executeSql("SELECT COUNT(*) FROM entry", [],
      function(tx, result) {
         //console.log(result.rows);
         console.log(result.rows.item(0)["count(*)"]);

         // do the html stuff to push this value to div
      },
      function(tx, error){
         // error occured
      }
   );
});
</code>```

Body:
I am building a local database with this :

var db = openDatabase('LIST','1.0','database', 2*1024*1024);

db.transaction(function (tx) {
  tx.executeSql('CREATE TABLE IF NOT EXISTS entry (ID INTEGER PRIMARY KEY ASC, first TEXT, last TEXT, email TEXT, phone TEXT, contest TEXT, added_on DATETIME)');
});

db.transaction(function(tx){
  tx.executeSql('INSERT INTO entry (first, last, email, phone, contest, added_on) VALUES (?,?,?,?,?,?)',
  [vFirst, vLast, vEmail, vPhone, vContest, addedOn]);
});

How would I populate a div with count of total rows in the database? I guess I would use something like SELECT COUNT(*) FROM entry .. but I am unclear on how to write this or print the output on the page.

If I was using local storage I see I could do something as simple as var length = window.localStorage.length; but I can not figure out how to do something similar with SQL.

Body:
If you want to count all rows from entry table, then SELECT COUNT(*) FROM entry
If you want to know count of rows in database, then UNION queries from different tables and sum using SUM()

EDIT:

db.transaction(function(tx) {
   tx.executeSql("SELECT COUNT(*) FROM entry", [],
      function(tx, result) {
         //console.log(result.rows);
         console.log(result.rows.item(0)["count(*)"]);

         // do the html stuff to push this value to div
      },
      function(tx, error){
         // error occured
      }
   );
});


问:
Testing and density plot across multiple columns
I have a list of restaurants and their star rating:

```<code>Restaurant     Question               1.star  2.stars ...etc

McDonalds      How was the food?      5       6       ...
McDonalds      How were the drinks?   3       4
McDonalds      How were the workers?  2       7
Burger_King    How was the food?      4       11
Burger_King    How were the drinks?   9       3
Burger_King    How were the workers?  12      1
</code>```

1. How do I perform a t-test to determine whether people only use the 1-star and 5-star ratings?

2. How do I graph a density distribution of the star ratings?

3. In general, how do you graph across multiple columns, e.g. col_1 has value, col_2 has frequency?

tribble for convenience:

```<code>tribble(
  ~restaurant, ~question,  ~one_star, ~two_star, ~three_star, ~four_star, ~five_star, ~average,

  "McDonalds", "How was the food?",  5, 6, 8, 2, 9, (5*1 + 6*2 + 8*3 + 2*4 + 5*9)/(5 + 6 + 8 + 2 + 9),
  "McDonalds", "How were the drinks?",  9, 8, 7, 5, 1, (9*1 + 8*2 + 7*3 + 5*4 + 5*1)/(9 + 8 + 7 + 5 + 1),
  "McDonalds", "How were the drinks?",  9, 8, 7, 5, 1, (9*1 + 8*2 + 7*3 + 5*4 + 5*1)/(9 + 8 + 7 + 5 + 1),
  "BurgerKing", "How was the food?",  2, 6, 8, 2, 9, (2*1 + 6*2 + 8*3 + 2*4 + 5*9)/(2 + 6 + 8 + 2 + 9),
  "BurgerKing", "How were the drinks?",  1, 4, 8, 5, 1, (1*1 + 4*2 + 8*3 + 5*4 + 5*1)/(1 + 4 + 8 + 5 + 1),
  "BurgerKing", "How were the drinks?",  4, 7, 2, 5, 1, (4*1 + 7*2 + 2*3 + 5*4 + 5*1)/(4 + 7 + 2 + 5 + 1)
)
</code>```

Edit: As requested, here is my attempt:

```<code>#Note: this only works because it truncates the rest of the dataframe. Unaware of alternatives
#Step 1: Transform from wide to long
ratingdf <-
  df %>%
  select(one_star:five_star) %>%
  pivot_longer(one_star:five_star, names_to = "rating")

#Step 2: Collapse values into total frequency
ratingdf <-
  ratingdf %>%
  group_by(rating) %>%
  summarize(sum(value))

#Graph using ggplot
ratingdf %>%
  ggplot(aes(x = rating, y = `sum(value)`)) +
  geom_histogram(stat = "identity")
</code>```

When I tried to use geom_density() on this, it does not show anything because the frequencies instead of the columns are given.

答:
Preparation

```<code>library(tidyverse)

df <- tribble(
    ~restaurant, ~question,  ~one_star, ~two_star, ~three_star, ~four_star, ~five_star, ~average,

    "McDonalds", "How was the food?",  5, 6, 8, 2, 9, (5*1 + 6*2 + 8*3 + 2*4 + 5*9)/(5 + 6 + 8 + 2 + 9),
    "McDonalds", "How were the drinks?",  9, 8, 7, 5, 1, (9*1 + 8*2 + 7*3 + 5*4 + 5*1)/(9 + 8 + 7 + 5 + 1),
    "McDonalds", "How were the drinks?",  9, 8, 7, 5, 1, (9*1 + 8*2 + 7*3 + 5*4 + 5*1)/(9 + 8 + 7 + 5 + 1),
    "BurgerKing", "How was the food?",  2, 6, 8, 2, 9, (2*1 + 6*2 + 8*3 + 2*4 + 5*9)/(2 + 6 + 8 + 2 + 9),
    "BurgerKing", "How were the drinks?",  1, 4, 8, 5, 1, (1*1 + 4*2 + 8*3 + 5*4 + 5*1)/(1 + 4 + 8 + 5 + 1),
    "BurgerKing", "How were the drinks?",  4, 7, 2, 5, 1, (4*1 + 7*2 + 2*3 + 5*4 + 5*1)/(4 + 7 + 2 + 5 + 1)
)

df <- df %>%
    pivot_longer(cols = ends_with("_star")
                 , names_to = "stars")
</code>```

Question 1

```<code>oneORfive <- df %>%
    mutate(oneORfive = as.numeric(stars == "one_star" | stars == "five_star")) %>%
    pull(oneORfive)

occurences <- df %>%
    pull(value)

allVotes_oneORfive <- unlist(map2(oneORfive, occurences, rep_len))
t.test(allVotes_oneORfive)
</code>```

I doubt that a t-test is the right thing to do here, but I won't argue, since this is not a statistics forum.

Question 2

A density plot does not make sense here, because it's not a continuous scale. Also, the levels are not equi-distant (IMO) - otherwise you wouldn't have to ask question 1. Either way, maybe the following histogram can help you as well:

```<code>df %>%
    mutate(stars = factor(stars, levels = c("one_star", "two_star", "three_star", "four_star", "five_star"))) %>%
    ggplot(aes(stars, value)) +
    geom_bar(stat = "identity") +
    facet_grid(restaurant ~ question)
</code>```

Question 3
I don't get this one. Maybe it makes sense to open a separate question about it.

Body:
I have a list of restaurants and their star rating:

Restaurant     Question               1.star  2.stars ...etc

McDonalds      How was the food?      5       6       ...
McDonalds      How were the drinks?   3       4
McDonalds      How were the workers?  2       7
Burger_King    How was the food?      4       11
Burger_King    How were the drinks?   9       3
Burger_King    How were the workers?  12      1

1. How do I perform a t-test to determine whether people only use the 1-star and 5-star ratings?

2. How do I graph a density distribution of the star ratings?

3. In general, how do you graph across multiple columns, e.g. col_1 has value, col_2 has frequency?

tribble for convenience:

tribble(
  ~restaurant, ~question,  ~one_star, ~two_star, ~three_star, ~four_star, ~five_star, ~average,

  "McDonalds", "How was the food?",  5, 6, 8, 2, 9, (5*1 + 6*2 + 8*3 + 2*4 + 5*9)/(5 + 6 + 8 + 2 + 9),
  "McDonalds", "How were the drinks?",  9, 8, 7, 5, 1, (9*1 + 8*2 + 7*3 + 5*4 + 5*1)/(9 + 8 + 7 + 5 + 1),
  "McDonalds", "How were the drinks?",  9, 8, 7, 5, 1, (9*1 + 8*2 + 7*3 + 5*4 + 5*1)/(9 + 8 + 7 + 5 + 1),
  "BurgerKing", "How was the food?",  2, 6, 8, 2, 9, (2*1 + 6*2 + 8*3 + 2*4 + 5*9)/(2 + 6 + 8 + 2 + 9),
  "BurgerKing", "How were the drinks?",  1, 4, 8, 5, 1, (1*1 + 4*2 + 8*3 + 5*4 + 5*1)/(1 + 4 + 8 + 5 + 1),
  "BurgerKing", "How were the drinks?",  4, 7, 2, 5, 1, (4*1 + 7*2 + 2*3 + 5*4 + 5*1)/(4 + 7 + 2 + 5 + 1)
)

Edit: As requested, here is my attempt:

#Note: this only works because it truncates the rest of the dataframe. Unaware of alternatives
#Step 1: Transform from wide to long
ratingdf <-
  df %>%
  select(one_star:five_star) %>%
  pivot_longer(one_star:five_star, names_to = "rating")

#Step 2: Collapse values into total frequency
ratingdf <-
  ratingdf %>%
  group_by(rating) %>%
  summarize(sum(value))

#Graph using ggplot
ratingdf %>%
  ggplot(aes(x = rating, y = `sum(value)`)) +
  geom_histogram(stat = "identity")

When I tried to use geom_density() on this, it does not show anything because the frequencies instead of the columns are given.

Body:
Preparation

library(tidyverse)

df <- tribble(
    ~restaurant, ~question,  ~one_star, ~two_star, ~three_star, ~four_star, ~five_star, ~average,

    "McDonalds", "How was the food?",  5, 6, 8, 2, 9, (5*1 + 6*2 + 8*3 + 2*4 + 5*9)/(5 + 6 + 8 + 2 + 9),
    "McDonalds", "How were the drinks?",  9, 8, 7, 5, 1, (9*1 + 8*2 + 7*3 + 5*4 + 5*1)/(9 + 8 + 7 + 5 + 1),
    "McDonalds", "How were the drinks?",  9, 8, 7, 5, 1, (9*1 + 8*2 + 7*3 + 5*4 + 5*1)/(9 + 8 + 7 + 5 + 1),
    "BurgerKing", "How was the food?",  2, 6, 8, 2, 9, (2*1 + 6*2 + 8*3 + 2*4 + 5*9)/(2 + 6 + 8 + 2 + 9),
    "BurgerKing", "How were the drinks?",  1, 4, 8, 5, 1, (1*1 + 4*2 + 8*3 + 5*4 + 5*1)/(1 + 4 + 8 + 5 + 1),
    "BurgerKing", "How were the drinks?",  4, 7, 2, 5, 1, (4*1 + 7*2 + 2*3 + 5*4 + 5*1)/(4 + 7 + 2 + 5 + 1)
)

df <- df %>%
    pivot_longer(cols = ends_with("_star")
                 , names_to = "stars")

Question 1

oneORfive <- df %>%
    mutate(oneORfive = as.numeric(stars == "one_star" | stars == "five_star")) %>%
    pull(oneORfive)

occurences <- df %>%
    pull(value)

allVotes_oneORfive <- unlist(map2(oneORfive, occurences, rep_len))
t.test(allVotes_oneORfive)

I doubt that a t-test is the right thing to do here, but I won't argue, since this is not a statistics forum.

Question 2

A density plot does not make sense here, because it's not a continuous scale. Also, the levels are not equi-distant (IMO) - otherwise you wouldn't have to ask question 1. Either way, maybe the following histogram can help you as well:

df %>%
    mutate(stars = factor(stars, levels = c("one_star", "two_star", "three_star", "four_star", "five_star"))) %>%
    ggplot(aes(stars, value)) +
    geom_bar(stat = "identity") +
    facet_grid(restaurant ~ question)

Question 3
I don't get this one. Maybe it makes sense to open a separate question about it.


问:
Powershell Script "$_.FullName" not working - Sending files via "Copy-VMFile"
I'm trying to use a script I found on the internet to copy all files in a directory but I can't get it to work. Can anybody help debug? I'm guessing the script was used to transfer windows/windows but I need windows --> Linux.

https://www.powershellmagazine.com/2013/12/17/pstip-copying-folders-using-copy-vmfile-cmdlet-in-windows-server-2012-r2-hyper-v/

```<code>Get-ChildItem C:\tmp -Recurse -File | % { Copy-VMFile -Name "OpenProject8.3" -SourcePath $_.FullName -DestinationPath "/tmp/" -FileSource Host }
</code>```

The issue seems to be related to the sourcepath, but im not 100%.

```<code>Copy-VMFile : Failed to initiate copying files to the guest.
Failed to copy the source file 'C:\tmp\svn-repositories-20200212010002.tar.gz' to the destination '/tmp/' in the guest.
At line:1 char:43
+ ... -File | % { Copy-VMFile -Name "OpenProject8.3" -SourcePath $_.FullNam ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Copy-VMFile], VirtualizationException
    + FullyQualifiedErrorId : OperationFailed,Microsoft.HyperV.PowerShell.Commands.CopyVMFile
</code>```

答: Well.... I feel stupid! The issue was that earlier testing the x-fer had succeeded and then when the file exists, Copy-VMFile won't overwrite the file (even though it uses root account...) and gives a non-descriptive error! The code above works fine as is.</p>

Body:
I'm trying to use a script I found on the internet to copy all files in a directory but I can't get it to work. Can anybody help debug? I'm guessing the script was used to transfer windows/windows but I need windows --> Linux.

https://www.powershellmagazine.com/2013/12/17/pstip-copying-folders-using-copy-vmfile-cmdlet-in-windows-server-2012-r2-hyper-v/

Get-ChildItem C:\tmp -Recurse -File | % { Copy-VMFile -Name "OpenProject8.3" -SourcePath $_.FullName -DestinationPath "/tmp/" -FileSource Host }

The issue seems to be related to the sourcepath, but im not 100%.

Copy-VMFile : Failed to initiate copying files to the guest.
Failed to copy the source file 'C:\tmp\svn-repositories-20200212010002.tar.gz' to the destination '/tmp/' in the guest.
At line:1 char:43
+ ... -File | % { Copy-VMFile -Name "OpenProject8.3" -SourcePath $_.FullNam ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Copy-VMFile], VirtualizationException
    + FullyQualifiedErrorId : OperationFailed,Microsoft.HyperV.PowerShell.Commands.CopyVMFile


问:
Calculate sum of each form row after cloning
I am trying to calculate the sum of each row after I am dynamically create these by using clone() in jQuery.

At the moment it just sums the very first row and not the second/third etc. Below is the div I am cloning. Any help would be highly appreciated. Many Thanks

  <select style="margin-top:5px; margin-bottom:5px;" id="jobnumbers" asp-for="JobNumber" type="" class="col-md-1 formfield">
    <option selected value="">...Project...</option>
    <option>101</option>
    <option>1223</option>
    <option>0098</option>
  </select>
  <select style="margin-top:5px; margin-bottom:5px;" id="mode" asp-for="Mode" type="" class="col-md-1 formfield">
    <option selected value="">...Mode...</option>
    <option>Test 1</option>
    <option>Test 2</option>
    <option>Test 3</option>
  </select>
  <select style="margin-top:5px; margin-bottom:5px;" id="cetegories" asp-for="Mode" type="" class="col-md-1 formfield">
    <option selected value="">...Category...</option>
    <option>Non Project</option>
    <option>Project Related</option>
  </select>
  <select style="margin-top:5px; margin-bottom:5px;" id="group" asp-for="Group" type="" class="col-md-1 formfield">
    <option selected value="">...Broad Group...</option>
    <option>Project design/set up</option>
    <option>Holiday/Bank Holiday</option>
  </select>

    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek1" name="DaysofWeek1" for='1' value="" asp-for="Monday" onblur="CalculateEachRowTotal(); CalculateTotalsForWeek();" class="form-control formfield DaysofWeek1" />

    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek2" name="DaysofWeek2" for='1' value="" asp-for="Tuesday" onblur="CalculateEachRowTotal(); CalculateTotalsForWeek();" class="form-control formfield DaysofWeek2" />

    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek3" name="DaysofWeek3" for='1' value="" asp-for="Wednesday" onblur="CalculateEachRowTotal(); CalculateTotalsForWeek();" class="form-control formfield DaysofWeek3" />

    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek4" name="DaysofWeek4" for='1' asp-for="Thursday" onblur="CalculateEachRowTotal(); CalculateTotalsForWeek();" class="form-control formfield DaysofWeek4" />

    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek5" name="DaysofWeek5" for='1' asp-for="Friday" onblur="CalculateEachRowTotal(); CalculateTotalsForWeek();" class="form-control formfield DaysofWeek5" />

    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek6" name="DaysofWeek6" for='1' asp-for="Saturday" onblur="CalculateEachRowTotal(); CalculateTotalsForWeek();" class="form-control formfield DaysofWeek6" />

    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek7" name="DaysofWeek7" for='1' asp-for="Sunday" onblur="CalculateEachRowTotal(); CalculateTotalsForWeek();" class="form-control formfield DaysofWeek7" />

    @Html.TextBoxFor(m => m.Total, new { @class = "form-control formfield rowTotal", @readonly = "readonly", @maxlength = "2" })

```

<p>Js that I current have is, please note I am just trying to find a solution first and will clean up a lot of this code :)</p>

```$('.itemRow').each(function (i) {
    DaysofWeek1 = $(this).find("input[name='DaysofWeek1']").val() === '' ? 0 : $("#DaysofWeek1").val();
    DaysofWeek2 = $(this).find("input[name='DaysofWeek2']").val() === '' ? 0 : $("#DaysofWeek2").val();
    DaysofWeek3 = $(this).find("input[name='DaysofWeek3']").val() === '' ? 0 : $("#DaysofWeek3").val();
    DaysofWeek4 = $(this).find("input[name='DaysofWeek4']").val() === '' ? 0 : $("#DaysofWeek4").val();
    DaysofWeek5 = $(this).find("input[name='DaysofWeek5']").val() === '' ? 0 : $("#DaysofWeek5").val();
    DaysofWeek6 = $(this).find("input[name='DaysofWeek6']").val() === '' ? 0 : $("#DaysofWeek6").val();
    DaysofWeek7 = $(this).find("input[name='DaysofWeek7']").val() === '' ? 0 : $("#DaysofWeek7").val();

    TotalAmount =
        parseInt(DaysofWeek1) +
        parseInt(DaysofWeek2) +
        parseInt(DaysofWeek3) +
        parseInt(DaysofWeek4) +
        parseInt(DaysofWeek5) +
        parseInt(DaysofWeek6) +
        parseInt(DaysofWeek7);

    if (TotalAmount === 0) {
        TotalAmount = 0;
        $(this).find(".rowTotal").val(TotalAmount);
    }
    else {
        $(this).find(".rowTotal").val(TotalAmount);
    }
});
```

答:
This answer treats a part of your code. The code counts the total of Weekdays in the current Row and in the update, the Global Total sum of all days in every row.
And to avoid mentioning those inputs one by one, it's a better to make them share a classname like here ".day" or a common custom data attribute like data-filter="day".

To handle dynamically added (non-DOm) rows, we always select their parent container.

```<code>$('.container').on('blur','.day',function(){
</code>```

And later when I pass the current element as Argument in Sum($(this));, I again need to explain where is the parent container.
It's like saying : I'm a lost clone if you want to count me with my siblings! I need to know where I'm I? Let me find my parents an I'd tell you where my siblings are located! Otherwise you will count my cousins with us... Because we all look the same :)

```<code>thisObj.parent().parent().find('input.day').each(function (i) {
</code>```

You can adapt your HTML code to use this and you can keep your other JS functions too. But if they handle cloned elements/sub-elements they better follow the same approach.

var i=0;
  var model = $('.itemRow');
  var frame = $('.container');
  function duplicate(){
  i++;
    var clone=model.clone();
    clone.find('.day,.rowTotal').val('');
    clone.attr("id","itemRow"+i);
    clone.appendTo(frame);
  }
$('#addRow').on('click',function(){
  duplicate();
});

function Sum(thisObj){
TotalAmount=0;
thisObj.parent().parent().find('input.day').each(function (i) {
    TotalAmount+=parseInt($(this).val()) || 0;
});

thisObj.parent().parent().find(".rowTotal").val(TotalAmount);

}

function SumAll(){
  total=0;
  $(".container .day").each(function(){
      total+=parseInt($(this).val()) || 0;
  });
  $(".allDaysTotal").text(total);
}

$('.container').on('blur','.day',function(){
Sum($(this));
SumAll();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <button id="addRow">Add Row</button>
<div class="container">
<div class="allDaysTotal"></div>
<div id="itemRow" class="row itemRow">
  <select style="margin-top:5px; margin-bottom:5px;" id="jobnumbers" asp-for="JobNumber" type="" class="col-md-1 formfield">
    <option selected value="">...Project...</option>
    <option>101</option>
    <option>1223</option>
    <option>0098</option>
  </select>
  <select style="margin-top:5px; margin-bottom:5px;" id="mode" asp-for="Mode" type="" class="col-md-1 formfield">
    <option selected value="">...Mode...</option>
    <option>Test 1</option>
    <option>Test 2</option>
    <option>Test 3</option>
  </select>
  <select style="margin-top:5px; margin-bottom:5px;" id="cetegories" asp-for="Mode" type="" class="col-md-1 formfield">
    <option selected value="">...Category...</option>
    <option>Non Project</option>
    <option>Project Related</option>
  </select>
  <select style="margin-top:5px; margin-bottom:5px;" id="group" asp-for="Group" type="" class="col-md-1 formfield">
    <option selected value="">...Broad Group...</option>
    <option>Project design/set up</option>
    <option>Holiday/Bank Holiday</option>
  </select>
  <div class="col-md-1" style="margin-top:5px; margin-bottom:5px;">
    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek1" name="DaysofWeek1" for='1' value="" asp-for="Monday"  class="form-control formfield DaysofWeek1 day" />
  </div>
  <div class="col-md-1" style="margin-top:5px; margin-bottom:5px;">
    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek2" name="DaysofWeek2" for='1' value="" asp-for="Tuesday"  class="form-control formfield DaysofWeek2 day" />
  </div>
  <div class="col-md-1" style="margin-top:5px; margin-bottom:5px;">
    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek3" name="DaysofWeek3" for='1' value="" asp-for="Wednesday"  class="form-control formfield DaysofWeek3 day" />
  </div>
  <div class="col-md-1" style="margin-top:5px; margin-bottom:5px;">
    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek4" name="DaysofWeek4" for='1' asp-for="Thursday"  class="form-control formfield DaysofWeek4 day" />
  </div>
  <div class="col-md-1" style="margin-top:5px; margin-bottom:5px;">
    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek5" name="DaysofWeek5" for='1' asp-for="Friday"  class="form-control formfield DaysofWeek5 day" />
  </div>
  <div class="col-md-1" style="margin-top:5px; margin-bottom:5px;">
    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek6" name="DaysofWeek6" for='1' asp-for="Saturday"  class="form-control formfield DaysofWeek6 day" />
  </div>
  <div class="col-md-1" style="margin-top:5px; margin-bottom:5px;">
    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek7" name="DaysofWeek7" for='1' asp-for="Sunday"  class="form-control formfield DaysofWeek7 day" />
  </div>
  <div class="col-md-1 formfield">
    RowTotal:
    <input value="" class="rowTotal"/>
  </div>
</div>

</div></code>```

Body:
I am trying to calculate the sum of each row after I am dynamically create these by using clone() in jQuery.

At the moment it just sums the very first row and not the second/third etc. Below is the div I am cloning. Any help would be highly appreciated. Many Thanks

  <select style="margin-top:5px; margin-bottom:5px;" id="jobnumbers" asp-for="JobNumber" type="" class="col-md-1 formfield">
    <option selected value="">...Project...</option>
    <option>101</option>
    <option>1223</option>
    <option>0098</option>
  </select>
  <select style="margin-top:5px; margin-bottom:5px;" id="mode" asp-for="Mode" type="" class="col-md-1 formfield">
    <option selected value="">...Mode...</option>
    <option>Test 1</option>
    <option>Test 2</option>
    <option>Test 3</option>
  </select>
  <select style="margin-top:5px; margin-bottom:5px;" id="cetegories" asp-for="Mode" type="" class="col-md-1 formfield">
    <option selected value="">...Category...</option>
    <option>Non Project</option>
    <option>Project Related</option>
  </select>
  <select style="margin-top:5px; margin-bottom:5px;" id="group" asp-for="Group" type="" class="col-md-1 formfield">
    <option selected value="">...Broad Group...</option>
    <option>Project design/set up</option>
    <option>Holiday/Bank Holiday</option>
  </select>

    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek1" name="DaysofWeek1" for='1' value="" asp-for="Monday" onblur="CalculateEachRowTotal(); CalculateTotalsForWeek();" class="form-control formfield DaysofWeek1" />

    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek2" name="DaysofWeek2" for='1' value="" asp-for="Tuesday" onblur="CalculateEachRowTotal(); CalculateTotalsForWeek();" class="form-control formfield DaysofWeek2" />

    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek3" name="DaysofWeek3" for='1' value="" asp-for="Wednesday" onblur="CalculateEachRowTotal(); CalculateTotalsForWeek();" class="form-control formfield DaysofWeek3" />

    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek4" name="DaysofWeek4" for='1' asp-for="Thursday" onblur="CalculateEachRowTotal(); CalculateTotalsForWeek();" class="form-control formfield DaysofWeek4" />

    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek5" name="DaysofWeek5" for='1' asp-for="Friday" onblur="CalculateEachRowTotal(); CalculateTotalsForWeek();" class="form-control formfield DaysofWeek5" />

    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek6" name="DaysofWeek6" for='1' asp-for="Saturday" onblur="CalculateEachRowTotal(); CalculateTotalsForWeek();" class="form-control formfield DaysofWeek6" />

    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek7" name="DaysofWeek7" for='1' asp-for="Sunday" onblur="CalculateEachRowTotal(); CalculateTotalsForWeek();" class="form-control formfield DaysofWeek7" />

    @Html.TextBoxFor(m => m.Total, new { @class = "form-control formfield rowTotal", @readonly = "readonly", @maxlength = "2" })

Js that I current have is, please note I am just trying to find a solution first and will clean up a lot of this code :)

$('.itemRow').each(function (i) {
    DaysofWeek1 = $(this).find("input[name='DaysofWeek1']").val() === '' ? 0 : $("#DaysofWeek1").val();
    DaysofWeek2 = $(this).find("input[name='DaysofWeek2']").val() === '' ? 0 : $("#DaysofWeek2").val();
    DaysofWeek3 = $(this).find("input[name='DaysofWeek3']").val() === '' ? 0 : $("#DaysofWeek3").val();
    DaysofWeek4 = $(this).find("input[name='DaysofWeek4']").val() === '' ? 0 : $("#DaysofWeek4").val();
    DaysofWeek5 = $(this).find("input[name='DaysofWeek5']").val() === '' ? 0 : $("#DaysofWeek5").val();
    DaysofWeek6 = $(this).find("input[name='DaysofWeek6']").val() === '' ? 0 : $("#DaysofWeek6").val();
    DaysofWeek7 = $(this).find("input[name='DaysofWeek7']").val() === '' ? 0 : $("#DaysofWeek7").val();

    TotalAmount =
        parseInt(DaysofWeek1) +
        parseInt(DaysofWeek2) +
        parseInt(DaysofWeek3) +
        parseInt(DaysofWeek4) +
        parseInt(DaysofWeek5) +
        parseInt(DaysofWeek6) +
        parseInt(DaysofWeek7);

    if (TotalAmount === 0) {
        TotalAmount = 0;
        $(this).find(".rowTotal").val(TotalAmount);
    }
    else {
        $(this).find(".rowTotal").val(TotalAmount);
    }
});

Body:
This answer treats a part of your code. The code counts the total of Weekdays in the current Row and in the update, the Global Total sum of all days in every row.
And to avoid mentioning those inputs one by one, it's a better to make them share a classname like here ".day" or a common custom data attribute like data-filter="day".

To handle dynamically added (non-DOm) rows, we always select their parent container.

$('.container').on('blur','.day',function(){

And later when I pass the current element as Argument in Sum($(this));, I again need to explain where is the parent container.
It's like saying : I'm a lost clone if you want to count me with my siblings! I need to know where I'm I? Let me find my parents an I'd tell you where my siblings are located! Otherwise you will count my cousins with us... Because we all look the same :)

thisObj.parent().parent().find('input.day').each(function (i) {

You can adapt your HTML code to use this and you can keep your other JS functions too. But if they handle cloned elements/sub-elements they better follow the same approach.

var i=0;
  var model = $('.itemRow');
  var frame = $('.container');
  function duplicate(){
  i++;
    var clone=model.clone();
    clone.find('.day,.rowTotal').val('');
    clone.attr("id","itemRow"+i);
    clone.appendTo(frame);
  }
$('#addRow').on('click',function(){
  duplicate();
});

function Sum(thisObj){
TotalAmount=0;
thisObj.parent().parent().find('input.day').each(function (i) {
    TotalAmount+=parseInt($(this).val()) || 0;
});

thisObj.parent().parent().find(".rowTotal").val(TotalAmount);

}

function SumAll(){
  total=0;
  $(".container .day").each(function(){
      total+=parseInt($(this).val()) || 0;
  });
  $(".allDaysTotal").text(total);
}

$('.container').on('blur','.day',function(){
Sum($(this));
SumAll();
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <button id="addRow">Add Row</button>
<div class="container">
<div class="allDaysTotal"></div>
<div id="itemRow" class="row itemRow">
  <select style="margin-top:5px; margin-bottom:5px;" id="jobnumbers" asp-for="JobNumber" type="" class="col-md-1 formfield">
    <option selected value="">...Project...</option>
    <option>101</option>
    <option>1223</option>
    <option>0098</option>
  </select>
  <select style="margin-top:5px; margin-bottom:5px;" id="mode" asp-for="Mode" type="" class="col-md-1 formfield">
    <option selected value="">...Mode...</option>
    <option>Test 1</option>
    <option>Test 2</option>
    <option>Test 3</option>
  </select>
  <select style="margin-top:5px; margin-bottom:5px;" id="cetegories" asp-for="Mode" type="" class="col-md-1 formfield">
    <option selected value="">...Category...</option>
    <option>Non Project</option>
    <option>Project Related</option>
  </select>
  <select style="margin-top:5px; margin-bottom:5px;" id="group" asp-for="Group" type="" class="col-md-1 formfield">
    <option selected value="">...Broad Group...</option>
    <option>Project design/set up</option>
    <option>Holiday/Bank Holiday</option>
  </select>
  <div class="col-md-1" style="margin-top:5px; margin-bottom:5px;">
    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek1" name="DaysofWeek1" for='1' value="" asp-for="Monday"  class="form-control formfield DaysofWeek1 day" />
  </div>
  <div class="col-md-1" style="margin-top:5px; margin-bottom:5px;">
    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek2" name="DaysofWeek2" for='1' value="" asp-for="Tuesday"  class="form-control formfield DaysofWeek2 day" />
  </div>
  <div class="col-md-1" style="margin-top:5px; margin-bottom:5px;">
    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek3" name="DaysofWeek3" for='1' value="" asp-for="Wednesday"  class="form-control formfield DaysofWeek3 day" />
  </div>
  <div class="col-md-1" style="margin-top:5px; margin-bottom:5px;">
    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek4" name="DaysofWeek4" for='1' asp-for="Thursday"  class="form-control formfield DaysofWeek4 day" />
  </div>
  <div class="col-md-1" style="margin-top:5px; margin-bottom:5px;">
    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek5" name="DaysofWeek5" for='1' asp-for="Friday"  class="form-control formfield DaysofWeek5 day" />
  </div>
  <div class="col-md-1" style="margin-top:5px; margin-bottom:5px;">
    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek6" name="DaysofWeek6" for='1' asp-for="Saturday"  class="form-control formfield DaysofWeek6 day" />
  </div>
  <div class="col-md-1" style="margin-top:5px; margin-bottom:5px;">
    <input id="hdtext1" name="hdtext1" class="form-control" type="hidden" />
    <input id="DaysofWeek7" name="DaysofWeek7" for='1' asp-for="Sunday"  class="form-control formfield DaysofWeek7 day" />
  </div>
  <div class="col-md-1 formfield">
    RowTotal:
    <input value="" class="rowTotal"/>
  </div>
</div>

</div>


问:
Why "hash /bin/ls" does nothing?
Writing the command hash with some relative or an absolute path, whether to a file, directory or a to nowhere, it seems to do nothing.

```<code>$> hash /bin/ls
prints nothing ***

$> hash /path/to/nowhere
prints nothing ***

$> hash ../same/as/above
same thing ***
</code>```

Why is that?

答:
hash does a command search and remembers the resolved location. Part of command search is skipping it when there's a slash in the name*. Therefore, hash foo/bar does nothing.

Relevant POSIX spec:

hash:

The hash utility shall affect the way the current shell environment remembers the locations of utilities found as described in Command Search and Execution. [...] It shall add utility locations to its list of remembered locations

Command Search and Execution:

If the command name contains at least one <slash>, the shell shall execute the utility in a separate utility environment with actions equivalent to calling the execl() function

[...]

Once a utility [invoked without a slash] has been searched for and found (either as a result of this specific search or as part of an unspecified shell start-up activity), an implementation may remember its location and need not search for the utility again

* This is incidentally why you execute a script in the current dir with ./myfile: it's the shortest way to make the filename contain a slash.

Title: Why "hash /bin/ls" does nothing?

Body:
Writing the command hash with some relative or an absolute path, whether to a file, directory or a to nowhere, it seems to do nothing.

$> hash /bin/ls
prints nothing ***

$> hash /path/to/nowhere
prints nothing ***

$> hash ../same/as/above
same thing ***

Why is that?


问:
.py to .exe file conversion issue
I'm trying to convert a simple python code (any sample code) into an executable file but on opening the application all I can see is a blank black screen.

I am using:

Python 3.7

PyInstaller 3.6

One file output

I am able to convert the file to .exe using auto-py-to-exe but I don't see any output when I try to run the application.

答:
In general there are some different ways so you can try the below and see if the issue is solved.

auto-py-to-exe is "A .py to .exe converter using a simple graphical interface built using Eel and PyInstaller in Python.". You can find a quick guide here

PyInstaller "freezes (packages) Python applications into stand-alone executables, under Windows, GNU/Linux, Mac OS X, FreeBSD, Solaris and AIX." You can find more usage info here (also pointed out by @nakE)

py2exe "is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.".You can find more usage info here (also as pointed out by @Kompocik)

If it is not solved then I am pretty confident that there is an issue with the executed code per se and not the conversion.

Can you please share your code so we can have a look?

Title: .py to .exe file conversion issue


问:
How to execute tshark in python for every file in a folder
I have About 100 .pcap files which i want to analyze. I would like to use tshark for this. My idea is to use a python script to automate this task. It has to run the following command for every .pcap file in my Folder:

```<code>tshark -r filename1.pcap -q -z io,stat,1 >> outfile1.txt
</code>```

So for every filename.pcap I want to have an outfile.txt.

Here is my Approach:

```<code>import os
inputdir = "C:/testfolder"
command = "tshark -r *.pcap -q -z io,stat,1 >> outfile.txt"
for pcapFilename in os.listdir(inputdir):
       if not pcapFilename.endswith(".pcap"):
          continue
       os.system(command)
</code>```

I know this does not work. But at the moment i am a bit stuck.

答:
solved Problem by myself.

```<code>`@echo off
    set cap_files="*.pcap"
    set cap_folder="c:\testfolder\"
    set tshark_cmd="c:\Program Files\Wireshark\tshark"
    echo. > %outfile%
    for /r %cap_folder% %%f in (%cap_files%) do (
    echo Processing File: %%f %tshark_cmd% -r %%f -q -z io,stat,1 >> %%f.txt )
    echo.`
</code>```

Thanks for your help. Yes python does not make so much sense here but I like to practice coding.

Body:
I have About 100 .pcap files which i want to analyze. I would like to use tshark for this. My idea is to use a python script to automate this task. It has to run the following command for every .pcap file in my Folder:

tshark -r filename1.pcap -q -z io,stat,1 >> outfile1.txt

So for every filename.pcap I want to have an outfile.txt.

Here is my Approach:

import os
inputdir = "C:/testfolder"
command = "tshark -r *.pcap -q -z io,stat,1 >> outfile.txt"
for pcapFilename in os.listdir(inputdir):
       if not pcapFilename.endswith(".pcap"):
          continue
       os.system(command)

I know this does not work. But at the moment i am a bit stuck.

Body:
solved Problem by myself.

`@echo off
    set cap_files="*.pcap"
    set cap_folder="c:\testfolder\"
    set tshark_cmd="c:\Program Files\Wireshark\tshark"
    echo. > %outfile%
    for /r %cap_folder% %%f in (%cap_files%) do (
    echo Processing File: %%f %tshark_cmd% -r %%f -q -z io,stat,1 >> %%f.txt )
    echo.`

Thanks for your help. Yes python does not make so much sense here but I like to practice coding.


问:
How do I throttle appengine-mapreduce on AppEngine?
http://code.google.com/p/appengine-mapreduce/ mentions that it can control the speed of execution, but I can't figure out how. It would make sense to create a task queue for a mapper job and control the speed from there, but I don't see how to specify which queue to use.

答:
I don't use the Java version myself, but the Python version has a processing_rate param that you pass to the mapper spec.

A quick search in the Java source reveals a MAPPER_INPUT_PROCESSING_RATE_KEY config key, which hopefully points you in the right direction.


问:
Can I populate a pd.dataframe with keys that match a value that's already in the dataframe?
I have a dictionary
my_dict={'google':'googletotcom',"kroger":"krogerdotcom","ucla":"unidotcom","IG":"picturedotcom","walmart":"walmartdotcom", "fb':"fbdotcom","ucla":"unidotcom" }

and a dataframe

```<code>dataframe=pd.DataFrame({'NAMES' : ['google', 'fb', 'ucla','ikea', 'wiki'], 'LINKS' : ["","","","",""]})
</code>```

```<code>
NAMES     Link
google
fb
ucla
ikea
wiki
IG
</code>```

I want to populate the dataframe so that it checks if the key of the dictionary matches a value in the dataframe, then populate that specific link to the value of its key. As you can see, some values included in the dataframe are not in the dictionary and vice-versa.

I have tried this:

for key,value in my_dict.items():
    if key in craft:
        CraftBeverage["Website"]=dict1[key]

```

<p>but it populated the links colum with the last link in the dictionary.</p>

<p>But I want to have something like this: </p>

```NAMES      Link
google     googletotcom
fb         fbdotcom
ucla       unidotcom
ikea
wiki
IG         picturedotcom

```

答:
You can use the map function, which will map the keys' values as a series given a column of keys:

dataframe['LINKS'] = dataframe["NAMES"].map(my_dict)

output:

```<code>    NAMES               LINKS
0  google        googletotcom
1      fb            fbdotcom
2    ucla           unidotcom
3    ikea                 NaN
4    wiki                 NaN
</code>```

Body:
I have a dictionary
my_dict={'google':'googletotcom',"kroger":"krogerdotcom","ucla":"unidotcom","IG":"picturedotcom","walmart":"walmartdotcom", "fb':"fbdotcom","ucla":"unidotcom" }

and a dataframe

dataframe=pd.DataFrame({'NAMES' : ['google', 'fb', 'ucla','ikea', 'wiki'], 'LINKS' : ["","","","",""]})

NAMES     Link
google
fb
ucla
ikea
wiki
IG

I want to populate the dataframe so that it checks if the key of the dictionary matches a value in the dataframe, then populate that specific link to the value of its key. As you can see, some values included in the dataframe are not in the dictionary and vice-versa.

I have tried this:

for key,value in my_dict.items():
    if key in craft:
        CraftBeverage["Website"]=dict1[key]

but it populated the links colum with the last link in the dictionary.

But I want to have something like this:

NAMES      Link
google     googletotcom
fb         fbdotcom
ucla       unidotcom
ikea
wiki
IG         picturedotcom

Body:
You can use the map function, which will map the keys' values as a series given a column of keys:

dataframe['LINKS'] = dataframe["NAMES"].map(my_dict)

output:

    NAMES               LINKS
0  google        googletotcom
1      fb            fbdotcom
2    ucla           unidotcom
3    ikea                 NaN
4    wiki                 NaN


问:
How to run multiple tests with pytest with a qualifier test
I have a directory of pytest test files, and there is a qualifier test that needs to be tested and if it fails then stop executing any further tests but if it passed then execute all tests whether any passes or fails.
I have a directory with following structure :

```<code>tests/
test_qualifier.py
test_one.py
test_two.py
...
</code>```

Now when I run the tests using pytest test/ -x it runs all the tests given that it stops at the first failure.
I want pytest to run test_qualifier.py and if it fails then stop further execution but if it passes then do not stop whether or not any test fails.

答:
You can use pytest-depends plugin. Mark other tests as a dependant on test_qualifier.

From the plugin page:

This pytest plugin allows you to declare dependencies between pytest tests, where dependent tests will not run if the tests they depend on did not succeed.

Of course, tests should be self contained whenever possible, but that doesn't mean this doesn't have good uses.

This can be useful for when the failing of a test means that another test cannot possibly succeed either, especially with slower tests. This isn't a dependency in the sense of test A sets up stuff for test B, but more in the sense of if test A failed there's no reason to bother with test B either.

Code sample:

```<code>BUILD_PATH = 'build'

def test_build_exists():
    assert os.path.exists(BUILD_PATH)

@pytest.depends(on=['test_build_exists'])
def test_build_version():
    result = subprocess.run([BUILD_PATH, '--version', stdout=subprocess.PIPE)
    assert result.returncode == 0
    assert '1.2.3' in result.stdout
</code>```

You can achieve the same by writing your own pytest plugin using pytest hooks.

Body:
I have a directory of pytest test files, and there is a qualifier test that needs to be tested and if it fails then stop executing any further tests but if it passed then execute all tests whether any passes or fails.
I have a directory with following structure :

tests/
test_qualifier.py
test_one.py
test_two.py
...

Now when I run the tests using pytest test/ -x it runs all the tests given that it stops at the first failure.
I want pytest to run test_qualifier.py and if it fails then stop further execution but if it passes then do not stop whether or not any test fails.

Body:
You can use pytest-depends plugin. Mark other tests as a dependant on test_qualifier.

From the plugin page:

This pytest plugin allows you to declare dependencies between pytest tests, where dependent tests will not run if the tests they depend on did not succeed.

Of course, tests should be self contained whenever possible, but that doesn't mean this doesn't have good uses.

This can be useful for when the failing of a test means that another test cannot possibly succeed either, especially with slower tests. This isn't a dependency in the sense of test A sets up stuff for test B, but more in the sense of if test A failed there's no reason to bother with test B either.

Code sample:

BUILD_PATH = 'build'

def test_build_exists():
    assert os.path.exists(BUILD_PATH)

@pytest.depends(on=['test_build_exists'])
def test_build_version():
    result = subprocess.run([BUILD_PATH, '--version', stdout=subprocess.PIPE)
    assert result.returncode == 0
    assert '1.2.3' in result.stdout

You can achieve the same by writing your own pytest plugin using pytest hooks.


问:
SUM of TotalSellPrice, Grouped by JobID? - Beginner SQL Question
I'm looking to write a query that gives the YTD sales for each job within our system. We use Bistrack. Here is what I have:

```<code>select C.Shortname AS "Customer", J.JobReference, (OH.TotalSellPrice - OH.NonSalesAmount) AS "TotalSellPrice", CIL.Amount AS "Contract Invoice", CA.Address1, CA.City, CA.TaxAreaID, T.Name AS "Tax Area", CA.PostCode AS "ZIP Code", OH.DateTimeCreated, TotalSalesYTD, J.JobID, CA.CustomerAddressID, C.CustomerID, SaleType
from dbo.CustomerAddress AS CA WITH(NOLOCK)
left join TaxArea AS T WITH(NOLOCK) ON CA.TaxAreaID = T.TaxAreaID
left join Customer as C WITH(NOLOCK) ON CA.CustomerID = C.CustomerID
left join Job as J WITH(NOLOCK) ON CA.CustomerAddressID = J.CustomerAddressID
left join CustomerFinancial as CF WITH(NOLOCK) ON CA.CustomerID = CF.CustomerID
left join OrderHeader AS OH WITH(NOLOCK) ON CA.CustomerAddressID = OH.DeliveryAddressID
left join ContractInvoicingLine AS CIL WITH(NOLOCK) ON OH.ContractInvoicingLineID = CIL.ContractInvoicingLineID
WHERE TotalSalesYTD <> 0 AND OH.DateTimeCreated > '2019-12-31' AND OH.OrderStatus = 8 AND OH.SaleType = 3
ORDER BY C.ShortName, JobReference
</code>```

This displays a result where each job reference is shown multiple times for each order under that job. I'd like to combine the orders into a SUM for each job. So, for example, I want the blue column to be a single number that is just 3362.68 + 101.03 + 1642.86 + 1298.75.

My idea would be to do SUM(OH.TotalSellPrice - OH.NonSalesAmount) AS "TotalSellPrice",  but that doesn't work, seemingly because my other columns are not in the function. I think this might be something simple to fix but I just started in SQL. I have gathered that partitioning could be used from browsing this site, but I have no idea how to apply it to my current query. Any help appreciated, thanks!

答:
From the error message you noted in the comments above, I'm going to assume you're using SQL Server as a database appliance.

In SQL Server, and most other databases, when you use SUM or any other aggregate functions you are required to add a GROUP BY clause that includes all non-aggregated columns from the SELECT clause of the query.

```<code>SELECT
   C.Shortname AS "Customer"
    ,J.JobReference
    ,SUM(OH.TotalSellPrice - OH.NonSalesAmount) AS "TotalSellPrice"
    ,CIL.Amount AS "Contract Invoice"
    ,CA.Address1
    ,CA.City
    ,CA.TaxAreaID
    ,T.Name AS "Tax Area"
    ,CA.PostCode AS "ZIP Code"
    ,OH.DateTimeCreated
    ,TotalSalesYTD
    ,J.JobID
    ,CA.CustomerAddressID
    ,C.CustomerID
    ,SaleType
FROM dbo.CustomerAddress AS CA
LEFT JOIN TaxArea AS T
  ON CA.TaxAreaID = T.TaxAreaID
LEFT JOIN Customer AS C
  ON CA.CustomerID = C.CustomerID
LEFT JOIN Job AS J
  ON CA.CustomerAddressID = J.CustomerAddressID
LEFT JOIN CustomerFinancial AS CF
  ON CA.CustomerID = CF.CustomerID
LEFT JOIN OrderHeader AS OH
  ON CA.CustomerAddressID = OH.DeliveryAddressID
LEFT JOIN ContractInvoicingLine AS CIL
  ON OH.ContractInvoicingLineID = CIL.ContractInvoicingLineID
WHERE TotalSalesYTD <> 0
    AND OH.DateTimeCreated > '2019-12-31'
    AND OH.OrderStatus = 8
    AND OH.SaleType = 3
GROUP BY
   C.Shortname
    ,J.JobReference
    ,CIL.Amount
    ,CA.Address1
    ,CA.City
    ,CA.TaxAreaID
    ,T.Name
    ,CA.PostCode
    ,OH.DateTimeCreated
    ,TotalSalesYTD
    ,J.JobID
    ,CA.CustomerAddressID
    ,C.CustomerID
    ,SaleType
ORDER BY
   C.ShortName
    ,JobReference
</code>```

Plus, have a look at these, and then make informed decisions.

Bad habits : Putting NOLOCK everywhere

Is NOLOCK Ever The Right Choice?

Body:
I'm looking to write a query that gives the YTD sales for each job within our system. We use Bistrack. Here is what I have:

select C.Shortname AS "Customer", J.JobReference, (OH.TotalSellPrice - OH.NonSalesAmount) AS "TotalSellPrice", CIL.Amount AS "Contract Invoice", CA.Address1, CA.City, CA.TaxAreaID, T.Name AS "Tax Area", CA.PostCode AS "ZIP Code", OH.DateTimeCreated, TotalSalesYTD, J.JobID, CA.CustomerAddressID, C.CustomerID, SaleType
from dbo.CustomerAddress AS CA WITH(NOLOCK)
left join TaxArea AS T WITH(NOLOCK) ON CA.TaxAreaID = T.TaxAreaID
left join Customer as C WITH(NOLOCK) ON CA.CustomerID = C.CustomerID
left join Job as J WITH(NOLOCK) ON CA.CustomerAddressID = J.CustomerAddressID
left join CustomerFinancial as CF WITH(NOLOCK) ON CA.CustomerID = CF.CustomerID
left join OrderHeader AS OH WITH(NOLOCK) ON CA.CustomerAddressID = OH.DeliveryAddressID
left join ContractInvoicingLine AS CIL WITH(NOLOCK) ON OH.ContractInvoicingLineID = CIL.ContractInvoicingLineID
WHERE TotalSalesYTD <> 0 AND OH.DateTimeCreated > '2019-12-31' AND OH.OrderStatus = 8 AND OH.SaleType = 3
ORDER BY C.ShortName, JobReference

This displays a result where each job reference is shown multiple times for each order under that job. I'd like to combine the orders into a SUM for each job. So, for example, I want the blue column to be a single number that is just 3362.68 + 101.03 + 1642.86 + 1298.75.

My idea would be to do SUM(OH.TotalSellPrice - OH.NonSalesAmount) AS "TotalSellPrice",  but that doesn't work, seemingly because my other columns are not in the function. I think this might be something simple to fix but I just started in SQL. I have gathered that partitioning could be used from browsing this site, but I have no idea how to apply it to my current query. Any help appreciated, thanks!

Body:
From the error message you noted in the comments above, I'm going to assume you're using SQL Server as a database appliance.

In SQL Server, and most other databases, when you use SUM or any other aggregate functions you are required to add a GROUP BY clause that includes all non-aggregated columns from the SELECT clause of the query.

SELECT
   C.Shortname AS "Customer"
    ,J.JobReference
    ,SUM(OH.TotalSellPrice - OH.NonSalesAmount) AS "TotalSellPrice"
    ,CIL.Amount AS "Contract Invoice"
    ,CA.Address1
    ,CA.City
    ,CA.TaxAreaID
    ,T.Name AS "Tax Area"
    ,CA.PostCode AS "ZIP Code"
    ,OH.DateTimeCreated
    ,TotalSalesYTD
    ,J.JobID
    ,CA.CustomerAddressID
    ,C.CustomerID
    ,SaleType
FROM dbo.CustomerAddress AS CA
LEFT JOIN TaxArea AS T
  ON CA.TaxAreaID = T.TaxAreaID
LEFT JOIN Customer AS C
  ON CA.CustomerID = C.CustomerID
LEFT JOIN Job AS J
  ON CA.CustomerAddressID = J.CustomerAddressID
LEFT JOIN CustomerFinancial AS CF
  ON CA.CustomerID = CF.CustomerID
LEFT JOIN OrderHeader AS OH
  ON CA.CustomerAddressID = OH.DeliveryAddressID
LEFT JOIN ContractInvoicingLine AS CIL
  ON OH.ContractInvoicingLineID = CIL.ContractInvoicingLineID
WHERE TotalSalesYTD <> 0
    AND OH.DateTimeCreated > '2019-12-31'
    AND OH.OrderStatus = 8
    AND OH.SaleType = 3
GROUP BY
   C.Shortname
    ,J.JobReference
    ,CIL.Amount
    ,CA.Address1
    ,CA.City
    ,CA.TaxAreaID
    ,T.Name
    ,CA.PostCode
    ,OH.DateTimeCreated
    ,TotalSalesYTD
    ,J.JobID
    ,CA.CustomerAddressID
    ,C.CustomerID
    ,SaleType
ORDER BY
   C.ShortName
    ,JobReference

Plus, have a look at these, and then make informed decisions.

Bad habits : Putting NOLOCK everywhere

Is NOLOCK Ever The Right Choice?


问:
How do I add custom headers to SignalR's Typescript client?
I am trying to pass a bearer token in the header to authorize client connections. The SignalR hub authorizes client by grabbing the bearer token from the header. I cannot modify the SingalR hub code to use a query string to get the token, nor can I use the built-in JWT token functionality.

How do I add a custom header to the SignalR typescript client?

The only thing I can think to do is override the HttpClient in to add the header however I am not sure if this is possible or how to do this.

I am using @microsoft/signalr in Angular 8 and the latest @microsoft/signalr package.

答:
If this is just to pass a bearer token then no need to do custom headers, to pass an access token you can use withUrl overload that takes IHttpConnectionOptions, this interface has accessTokenFactory that can be used like this:

```<code>yourAuthServicePromise.then(
  (data) => {
    if (data.['result']['accessToken']) {
      this.hubConnection = new signalR.HubConnectionBuilder()
        .withUrl('https://SIGNALR_SERVER_HUB_URL', {
          accessTokenFactory: () => {
            return data.['result']['accessToken'];
          }
        } as signalR.IHttpConnectionOptions)
        .build();
      this.hubConnection.start()
    }
  }
);
</code>```

Don't forget to enable cors policy in the hub Server in order to allow the JS client origin

Body:
If this is just to pass a bearer token then no need to do custom headers, to pass an access token you can use withUrl overload that takes IHttpConnectionOptions, this interface has accessTokenFactory that can be used like this:

yourAuthServicePromise.then(
  (data) => {
    if (data.['result']['accessToken']) {
      this.hubConnection = new signalR.HubConnectionBuilder()
        .withUrl('https://SIGNALR_SERVER_HUB_URL', {
          accessTokenFactory: () => {
            return data.['result']['accessToken'];
          }
        } as signalR.IHttpConnectionOptions)
        .build();
      this.hubConnection.start()
    }
  }
);

Don't forget to enable cors policy in the hub Server in order to allow the JS client origin


问:
pandas retaining index column when using usecols
This is a re-worded version of my question which hopefully makes more sense:

When using read_csv with an implicit index (i.e. the first column in the file does not have a header), everything works and I get a dataframe whose index is the first column in the file - the implicit index column.

However, if I specify usecols as an argument to read_csv, the implicit index column is ignored and the returned dataframe has a standard index created by pandas (0, 1, 2, 3 etc).

I cannot explicitly pass the index column in the list for usecols and then specify the index_col argument because the implicit index column has no header (this is how pandas knows it is an implicit index)!

Is there any way around this?

Here is the original question:

I am trying to read a csv file which has a column of row indexes which is not named, the rest of the columns are named:

```<code>       |head1|head2|
index1 | data1 | data2 |
</code>```

When I read in a certain number of columns with usecols, I also want to include the row indexes. However, as these are not named, I can't include the string in my list for usecols.

I've tried doing a combination of an integer index and strings (e.g. usecols = [0, 'header1', 'header2'] but this does not seem to work.

If I simply specify ind_col as 0, it will use the first column in my selection as the index column.

So, how can I read in a name column selection (via usecols) whilst retaining the first, nameless, column in the file as my row index?

答:
I recently had this same issue and was able to solve it using pandas default unnamed method.</p>

```<code>data = pd.read_csv('advertising.csv', header=0, index_col=[0] , usecols=['Unnamed: 0', 'radio','sales'])
</code>```

Body:
This is a re-worded version of my question which hopefully makes more sense:

When using read_csv with an implicit index (i.e. the first column in the file does not have a header), everything works and I get a dataframe whose index is the first column in the file - the implicit index column.

However, if I specify usecols as an argument to read_csv, the implicit index column is ignored and the returned dataframe has a standard index created by pandas (0, 1, 2, 3 etc).

I cannot explicitly pass the index column in the list for usecols and then specify the index_col argument because the implicit index column has no header (this is how pandas knows it is an implicit index)!

Is there any way around this?

Here is the original question:

I am trying to read a csv file which has a column of row indexes which is not named, the rest of the columns are named:

       |head1|head2|
index1 | data1 | data2 |

When I read in a certain number of columns with usecols, I also want to include the row indexes. However, as these are not named, I can't include the string in my list for usecols.

I've tried doing a combination of an integer index and strings (e.g. usecols = [0, 'header1', 'header2'] but this does not seem to work.

If I simply specify ind_col as 0, it will use the first column in my selection as the index column.

So, how can I read in a name column selection (via usecols) whilst retaining the first, nameless, column in the file as my row index?

Body:
I recently had this same issue and was able to solve it using pandas default unnamed method.

data = pd.read_csv('advertising.csv', header=0, index_col=[0] , usecols=['Unnamed: 0', 'radio','sales'])


问:
How do you run Cleanmgr.exe remotely?
I'm having some trouble getting Clean Manager on Windows 10 to run remotely. I've seen a few different things were you can edit the registry and modify the /sageset or /sagerun to be specific things then run it remotely, but it seems no matter what I do the CleanMgr runs locally on my machine rather than running remotely.

I believe this is the closest I've gotten to get it to run remotely... It seems to still just run locally on my machine though.

Any ideas?

( All variables are set before this portion of the script, this is just a small portion of what's going on that I'm stuck on )

```<code>## Starts cleanmgr.exe
Function Start-CleanMGR {
    Write-Host "Please provide your A-Account details to continue with this cleanup."
    $creds = Get-Credential
    Enter-PSSession -ComputerName $computername -Credential $creds
    try {
        $cleanmgr = Start-Process -Credential $creds -FilePath "C:\Windows\System32\cleanmgr.exe" -ArgumentList '/verylowdisk' -Wait -Verbose
        if ($cleanmgr) {
            Write-Host "Clean Manager ran successfully!                                                                   " -NoNewline -ForegroundColor Green
            Write-Host "[DONE]" -ForegroundColor Green -BackgroundColor Black
        }
    }
    catch [System.Exception] {
        Write-host "Cleanmgr is not installed! To use this portion of the script you must install the following windows features:" -NoNewline -ForegroundColor DarkGray
        Write-host "[ERROR]" -ForegroundColor Red -BackgroundColor Black
    }
} Start-CleanMGR
</code>```

答:
I suggest that you use Invoke-Command

```<code>Function Start-CleanMGR ($computername, $creds) {
        Invoke-Command -ComputerName $computername -Credential $creds -ScriptBlock {
        try {
            $cleanmgr = Start-Process -FilePath "C:\Windows\System32\cleanmgr.exe" -ArgumentList '/verylowdisk' -Wait -Verbose
            if ($cleanmgr) {
                return "Clean Manager ran successfully!"
            }
        }
        catch [System.Exception] {
            return "Cleanmgr is not installed! To use this portion of the script you must install the following windows features:"
        }
    }
}

Start-CleanMGR -computername "remotehost" -creds (Get-Credential)
</code>```

Title: How do you run Cleanmgr.exe remotely?

Body:
I'm having some trouble getting Clean Manager on Windows 10 to run remotely. I've seen a few different things were you can edit the registry and modify the /sageset or /sagerun to be specific things then run it remotely, but it seems no matter what I do the CleanMgr runs locally on my machine rather than running remotely.

I believe this is the closest I've gotten to get it to run remotely... It seems to still just run locally on my machine though.

Any ideas?

( All variables are set before this portion of the script, this is just a small portion of what's going on that I'm stuck on )

## Starts cleanmgr.exe
Function Start-CleanMGR {
    Write-Host "Please provide your A-Account details to continue with this cleanup."
    $creds = Get-Credential
    Enter-PSSession -ComputerName $computername -Credential $creds
    try {
        $cleanmgr = Start-Process -Credential $creds -FilePath "C:\Windows\System32\cleanmgr.exe" -ArgumentList '/verylowdisk' -Wait -Verbose
        if ($cleanmgr) {
            Write-Host "Clean Manager ran successfully!                                                                   " -NoNewline -ForegroundColor Green
            Write-Host "[DONE]" -ForegroundColor Green -BackgroundColor Black
        }
    }
    catch [System.Exception] {
        Write-host "Cleanmgr is not installed! To use this portion of the script you must install the following windows features:" -NoNewline -ForegroundColor DarkGray
        Write-host "[ERROR]" -ForegroundColor Red -BackgroundColor Black
    }
} Start-CleanMGR

Body:
I suggest that you use Invoke-Command

Function Start-CleanMGR ($computername, $creds) {
        Invoke-Command -ComputerName $computername -Credential $creds -ScriptBlock {
        try {
            $cleanmgr = Start-Process -FilePath "C:\Windows\System32\cleanmgr.exe" -ArgumentList '/verylowdisk' -Wait -Verbose
            if ($cleanmgr) {
                return "Clean Manager ran successfully!"
            }
        }
        catch [System.Exception] {
            return "Cleanmgr is not installed! To use this portion of the script you must install the following windows features:"
        }
    }
}

Start-CleanMGR -computername "remotehost" -creds (Get-Credential)