问:
Comma in return value
I know the desired syntax lies in the first function but I for the life of me can't find where it is.

I've attempted to remove commas and add spaces to each .split() each has yielded an undesired return value.

```<code>def get_country_codes(prices):
    price_list = prices.split(',')
    results = ''
    for price in price_list:
        results += price.split('$')[0]
    return results

def main():
    prices = "US$40, AU$89, JP$200"
    price_result = get_country_codes(prices)
    print(price_result)

if __name__ == "__main__":
    main()
</code>```

The current output:

```<code>US AU JP
</code>```

The desired output:

```<code>US, AU, JP
</code>```

答:
It looks like you could benefit from using a list to collect the country codes of the prices instead of a string. Then you can use ', '.join() later.

Maybe like this:

```<code>def get_country_codes(prices):
    country_code_list = []

    for price in prices.split(','):
        country_code = price.split('$')[0].strip()
        country_code_list.append(country_code)

    return country_code_list

if __name__ == '__main__':
    prices = "US$40, AU$89, JP$200"
    result_list = get_country_codes(prices)
    print(', '.join(result_list))
</code>```

Or if you like really short code:

```<code>prices = "US$40, AU$89, JP$200"
print(
    ', '.join(
        price.split('$')[0].strip()
        for price in prices.split(',')))
</code>```

Title: Comma in return value

Body:
I know the desired syntax lies in the first function but I for the life of me can't find where it is.

I've attempted to remove commas and add spaces to each .split() each has yielded an undesired return value.

def get_country_codes(prices):
    price_list = prices.split(',')
    results = ''
    for price in price_list:
        results += price.split('$')[0]
    return results

def main():
    prices = "US$40, AU$89, JP$200"
    price_result = get_country_codes(prices)
    print(price_result)

if __name__ == "__main__":
    main()

The current output:

US AU JP

The desired output:

US, AU, JP

Body:
It looks like you could benefit from using a list to collect the country codes of the prices instead of a string. Then you can use ', '.join() later.

Maybe like this:

def get_country_codes(prices):
    country_code_list = []

    for price in prices.split(','):
        country_code = price.split('$')[0].strip()
        country_code_list.append(country_code)

    return country_code_list

if __name__ == '__main__':
    prices = "US$40, AU$89, JP$200"
    result_list = get_country_codes(prices)
    print(', '.join(result_list))

Or if you like really short code:

prices = "US$40, AU$89, JP$200"
print(
    ', '.join(
        price.split('$')[0].strip()
        for price in prices.split(',')))


来源: stackexchange

问:
How to iterate over columns of "spark" dataframe?
I have the following Spark dataframe that is created dynamically

| name|  number |

+--------+---------+

| Andy | (20,10,30)|

|Berta | (30,40,20)|

| Joe  | (40,90,60)|

+-------+---------+

Now, I need to iterate each row and column in Spark to print the following output, How to do this?

Andy    20

Andy    10

Andy    30

Berta   30

Berta   40

Berta   20

Joe     40

Joe     90

Joe     60

答:
You need explode function.
Here samples of its usage.

ContentLicense: CC BY-SA 4.0


问:
Implement Sharing Location Places Picker same like WhatsApp without Places Picker Since it got deprecated
We had a requirement of sharing location which is a similar kind of WhatsApp with respective to User Interface & functionality.

I have come across that Google Place Picker has got deprecated and also migrated to Places Clients.

Say Like as,

and when they are trying to search,

May be, I am not good at explaining my idea but overall I am in the search of the above kind of implementation.

And also I came to know that Google Charges for the search or the places from the below Url,

https://github.com/rtchagas/pingplacepicker

What all I have tired is,

Coding Part:

```<code>Places.initialize(applicationContext, "Google API Key")
placesClient = Places.createClient(this)

val autocompleteFragment =
          getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment) as AutocompleteSupportFragment

autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));

autocompleteFragment.setOnPlaceSelectedListener(object : PlaceSelectionListener {
            override fun onPlaceSelected(p0: Place) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onError(p0: Status) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }
        });

 val intent = Autocomplete.IntentBuilder(
            AutocompleteActivityMode.FULLSCREEN, fields
        )
            .build(this);
        startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
</code>```

After searching for two three places I am get an error saying Retry. Don't know the reason.

Error:

Help is really appreciated.

答:
I faced the same problem since i'm working with place picker within my app , but since google decided to remove it , i have no choice than have a work around to find a solution !

i decided to use google map to recreate a place picker close experience .

First i created the map as full screen , and i putted an ImageView (Marker) as overlay of it as xml below :

```<code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/coordinator_layout"
xmlns:app="http://schemas.android.com/apk/res-auto">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.streetdev.goodnecity.SelectLocationPicker" />
    <ImageView
        android:layout_centerInParent="true"
        android:src="@drawable/ic_map"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="56dp"
    android:layout_height="56dp"
    app:backgroundTint="@color/colorPrimaryDark"
    android:src="@drawable/ic_plus"
    android:layout_margin="16dp"
    app:layout_anchor="@id/map"
    app:layout_anchorGravity="bottom|end" />
 </android.support.design.widget.CoordinatorLayout>
</code>```

So whenever the user is navigating on the map , the marker will stay in the center of the map like place picker

Now all you have to do is start your map picker using startActivityForResult, you have to handle the cameraPosition with gps ( if its available ) and then as soon as you want to go back with the result ( for me i click on the Fab button ) , you can get the result this way :

```<code>            LatLng latng = mMap.getCameraPosition().target;
            Intent returnIntent = new Intent();
            returnIntent.putExtra("result",String.valueOf(latng.latitude)+";"+String.valueOf(latng.longitude));
            setResult(Activity.RESULT_OK,returnIntent);
            finish();
</code>```

The last step is to handle the result in onActivityResult, you get your result , you do a split using ";" to separate latitude from longitude

hope my example will help some one !

Body:
We had a requirement of sharing location which is a similar kind of WhatsApp with respective to User Interface & functionality.

I have come across that Google Place Picker has got deprecated and also migrated to Places Clients.

Say Like as,

and when they are trying to search,

May be, I am not good at explaining my idea but overall I am in the search of the above kind of implementation.

And also I came to know that Google Charges for the search or the places from the below Url,

https://github.com/rtchagas/pingplacepicker

What all I have tired is,

Coding Part:

Places.initialize(applicationContext, "Google API Key")
placesClient = Places.createClient(this)

val autocompleteFragment =
          getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment) as AutocompleteSupportFragment

autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));

autocompleteFragment.setOnPlaceSelectedListener(object : PlaceSelectionListener {
            override fun onPlaceSelected(p0: Place) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onError(p0: Status) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }
        });

 val intent = Autocomplete.IntentBuilder(
            AutocompleteActivityMode.FULLSCREEN, fields
        )
            .build(this);
        startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);

After searching for two three places I am get an error saying Retry. Don't know the reason.

Error:

Help is really appreciated.

Body:
I faced the same problem since i'm working with place picker within my app , but since google decided to remove it , i have no choice than have a work around to find a solution !

i decided to use google map to recreate a place picker close experience .

First i created the map as full screen , and i putted an ImageView (Marker) as overlay of it as xml below :

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/coordinator_layout"
xmlns:app="http://schemas.android.com/apk/res-auto">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.streetdev.goodnecity.SelectLocationPicker" />
    <ImageView
        android:layout_centerInParent="true"
        android:src="@drawable/ic_map"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="56dp"
    android:layout_height="56dp"
    app:backgroundTint="@color/colorPrimaryDark"
    android:src="@drawable/ic_plus"
    android:layout_margin="16dp"
    app:layout_anchor="@id/map"
    app:layout_anchorGravity="bottom|end" />
 </android.support.design.widget.CoordinatorLayout>

So whenever the user is navigating on the map , the marker will stay in the center of the map like place picker

Now all you have to do is start your map picker using startActivityForResult, you have to handle the cameraPosition with gps ( if its available ) and then as soon as you want to go back with the result ( for me i click on the Fab button ) , you can get the result this way :

            LatLng latng = mMap.getCameraPosition().target;
            Intent returnIntent = new Intent();
            returnIntent.putExtra("result",String.valueOf(latng.latitude)+";"+String.valueOf(latng.longitude));
            setResult(Activity.RESULT_OK,returnIntent);
            finish();

The last step is to handle the result in onActivityResult, you get your result , you do a split using ";" to separate latitude from longitude

hope my example will help some one !


问:
Dynamic image height and width in html emails in Outlook
I am sending an HTML email with the content generated by React.js.  In the body of the email I have to put the client's icon in a 40x40 cell.

Some client's icons are square and they look fine.  Others are tall or wide and Outlook is distorting them to fit in the 40x40 cell, which is not cool.

Here are a few things I have tried, and how Outlook ruins them:

Shows the image in its full size (max-height and max-width are not working):

```

<ol start="2">
<li><strong>Distorts the image making it a 40x40 square:</strong></li>
</ol>

<pre class="lang-html prettyprint-override"><code><table border="0" cellPadding="0" cellSpacing="0" width="40" height="40">
  <tbody>
    <tr>
      <td align="center">
        <img
          alt=""
          border="0"
          src={iconUrl}
          width="40"
          height="40"
          style={{ display: "block", width: "auto", height: "auto", maxHeight: "40px", maxWidth: "40px" }}
        />
      </td>
    </tr>
  </tbody>
</table>
</code>```

Shows the image in its full size:

```

<ol start="4">
<li><strong>Outlook does not support any <code>background</code> style properties, so nothing appears</strong>:</li>
</ol>

<pre class="lang-html prettyprint-override"><code><table border="0" cellPadding="0" cellSpacing="0" width="40" height="40">
  <tbody>
    <tr>
      <td align="center">
        <div
          style={{
            display: "block",
            height: "40px",
            width: "40px",
            backgroundImage: `url(${iconUrl})`,
            backgroundSize: "cover",
            backgroundRepeat: "no-repeat",
            backgroundPosition: "center center",
          }}
        />
      </td>
    </tr>
  </tbody>
</table>
</code>```

Shows the image in its full size:

```

Any suggestions?  Thanks.

答:
Outlook will ignore image widths set in the inline style. Since your icons are supposed to be 40px, declare the width as

```<code><table role="presentation" cellspacing="0" cellpadding="0" border="0" width="40">
  <tr>
    <td style="text-align: center">
      <img src="https://via.placeholder.com/40" width="40" height="40" alt="" border="0"  style="height: auto; max-width: 40px;">
    </td>
  </tr>
</table>
</code>```

In addition, Outlook only does background images using VML.

Finally, Outlook and other email clients will ignore HTML and CSS that is not formatted in the correct manner. I would suggest brushing up on the correct way to separate css values ;. You will experience less headaches.

Good luck.

Body:
I am sending an HTML email with the content generated by React.js.  In the body of the email I have to put the client's icon in a 40x40 cell.

Some client's icons are square and they look fine.  Others are tall or wide and Outlook is distorting them to fit in the 40x40 cell, which is not cool.

Here are a few things I have tried, and how Outlook ruins them:

Shows the image in its full size (max-height and max-width are not working):

Distorts the image making it a 40x40 square:

Shows the image in its full size:

Outlook does not support any background style properties, so nothing appears:

        <div
          style={{
            display: "block",
            height: "40px",
            width: "40px",
            backgroundImage: `url(${iconUrl})`,
            backgroundSize: "cover",
            backgroundRepeat: "no-repeat",
            backgroundPosition: "center center",
          }}
        />

Shows the image in its full size:

Any suggestions?  Thanks.

Body:
Outlook will ignore image widths set in the inline style. Since your icons are supposed to be 40px, declare the width as <img width="40" />

<table role="presentation" cellspacing="0" cellpadding="0" border="0" width="40">
  <tr>
    <td style="text-align: center">
      <img src="https://via.placeholder.com/40" width="40" height="40" alt="" border="0"  style="height: auto; max-width: 40px;">
    </td>
  </tr>
</table>

In addition, Outlook only does background images using VML.

Finally, Outlook and other email clients will ignore HTML and CSS that is not formatted in the correct manner. I would suggest brushing up on the correct way to separate css values ;. You will experience less headaches.

Good luck.


问:
How to check if Key was store in KeyChain in Swift
I was trying to store two keys private and public in KeyChain and when I try to do so my result valuable return 0 which I am assuming that mean it was store ,but when I try to get back to decrypt  a message I am getting it back as nil so if there is a way to check if the keys were store based SecItemCopyMatching? but I am not getting any error while creating them</p>

```<code>let tagName = "PrivateKeyTag"
let privkey = "key"
        let privkeyData = Data(privkey!.utf8)
        let privateFilter: [String : Any] = [
            (kSecClass as String)              : kSecClassKey,
            (kSecAttrKeyType as String)        : kSecAttrKeyTypeRSA,
            (kSecAttrApplicationTag as String) : tagName,
            (kSecValueData as String)          : privkeyData,
            (kSecAttrKeyClass as String)       : kSecAttrKeyClassPrivate,
           // kSecAttrKeySizeInBits as String: 2048,
            (kSecReturnPersistentRef as String): true,

            ] as [String : Any]
        let result = SecItemAdd(privateFilter as CFDictionary, nil)
        if ((result != noErr) && (result != errSecDuplicateItem)) {
            NSLog("Cannot add key to keychain, status \(result).")
        }

let getquery: [String: Any] = [kSecClass as String: kSecClassKey,
                                       kSecAttrApplicationTag as String: tag,
                                       kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
                                       ]
        var item: CFTypeRef?
        let status = SecItemCopyMatching(getquery as CFDictionary, &item)
        guard status == errSecSuccess else {
            print("key not found")
            return
        }
        let key = item as! SecKey
</code>```

答:
When you create a cryptographic key, you can set the parameter kSecAttrIsPermanent to true which will automatically store the key in the default keychain. This will clean your code a bit so you no longer have to deal with the SecItemAdd() and all the error handling with that. So here is a simpler way to do what you're trying to do.

To create a key and query a key

```<code>let tag = "com.example.keys.mykey".data(using: .utf8)!
let attributes: [String: Any] =
    [kSecAttrKeyType as String:            kSecAttrKeyTypeRSA,
     kSecAttrKeySizeInBits as String:      2048,
     kSecPrivateKeyAttrs as String:
        [kSecAttrIsPermanent as String:    true,
         kSecAttrApplicationTag as String: tag]
]

let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, nil)
let query: [String: Any] = [kSecClass as String: kSecClassKey,
                            kSecAttrApplicationTag as String: tag,
                            kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
                            kSecReturnRef as String: true]
var item: CFTypeRef?
let status2 = SecItemCopyMatching(query as CFDictionary, &item)
guard status2 == errSecSuccess else { print("error1"); return }
let key = item as! SecKey
</code>```

Running this code I believe will accomplish what you are trying to do in the code you provided in the question. I tried running the code you gave and the version of Xcode and swift I am using gives compiler errors.

If you run the code in this answer you will notice that no errors are printed to the console, indicating that the key was successfully found in the default keychain.

Body:
I was trying to store two keys private and public in KeyChain and when I try to do so my result valuable return 0 which I am assuming that mean it was store ,but when I try to get back to decrypt  a message I am getting it back as nil so if there is a way to check if the keys were store based SecItemCopyMatching? but I am not getting any error while creating them

let tagName = "PrivateKeyTag"
let privkey = "key"
        let privkeyData = Data(privkey!.utf8)
        let privateFilter: [String : Any] = [
            (kSecClass as String)              : kSecClassKey,
            (kSecAttrKeyType as String)        : kSecAttrKeyTypeRSA,
            (kSecAttrApplicationTag as String) : tagName,
            (kSecValueData as String)          : privkeyData,
            (kSecAttrKeyClass as String)       : kSecAttrKeyClassPrivate,
           // kSecAttrKeySizeInBits as String: 2048,
            (kSecReturnPersistentRef as String): true,

            ] as [String : Any]
        let result = SecItemAdd(privateFilter as CFDictionary, nil)
        if ((result != noErr) && (result != errSecDuplicateItem)) {
            NSLog("Cannot add key to keychain, status \(result).")
        }

let getquery: [String: Any] = [kSecClass as String: kSecClassKey,
                                       kSecAttrApplicationTag as String: tag,
                                       kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
                                       ]
        var item: CFTypeRef?
        let status = SecItemCopyMatching(getquery as CFDictionary, &item)
        guard status == errSecSuccess else {
            print("key not found")
            return
        }
        let key = item as! SecKey

Body:
When you create a cryptographic key, you can set the parameter kSecAttrIsPermanent to true which will automatically store the key in the default keychain. This will clean your code a bit so you no longer have to deal with the SecItemAdd() and all the error handling with that. So here is a simpler way to do what you're trying to do.

To create a key and query a key

let tag = "com.example.keys.mykey".data(using: .utf8)!
let attributes: [String: Any] =
    [kSecAttrKeyType as String:            kSecAttrKeyTypeRSA,
     kSecAttrKeySizeInBits as String:      2048,
     kSecPrivateKeyAttrs as String:
        [kSecAttrIsPermanent as String:    true,
         kSecAttrApplicationTag as String: tag]
]

let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, nil)
let query: [String: Any] = [kSecClass as String: kSecClassKey,
                            kSecAttrApplicationTag as String: tag,
                            kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
                            kSecReturnRef as String: true]
var item: CFTypeRef?
let status2 = SecItemCopyMatching(query as CFDictionary, &item)
guard status2 == errSecSuccess else { print("error1"); return }
let key = item as! SecKey

Running this code I believe will accomplish what you are trying to do in the code you provided in the question. I tried running the code you gave and the version of Xcode and swift I am using gives compiler errors.

If you run the code in this answer you will notice that no errors are printed to the console, indicating that the key was successfully found in the default keychain.


问:
How to place a small square box across every td element having text in css?
I am working on a table in html in which I want to place a square box across every td element in css

```<code><tr>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["series_title"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["episode_title"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["description"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["series_title_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["episode_title_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["description_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"> <?php echo basename($file, ".mp4"); ?></td>
</tr>
</code>```

The above html/php code display the table/td element in the following fashion:

Problem Statement:

I am wondering what changes I should make in the inline css code above so that I am able to make a small square box (as shown below) across every td element having text in css. At this moment, as shown above in an image it is
making a big square box

答:
Your table tag needs a cellspacing.  </p>

```<code><table cellspacing="10px">
  <tr>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["series_title"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["episode_title"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["description"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["series_title_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["episode_title_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["description_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo basename($file, ".mp4"); ?></td>
  </tr>
</table>
</code>```

Body:
I am working on a table in html in which I want to place a square box across every td element in css

    <?php echo $program["series_title"]; ?>
    <?php echo $program["episode_title"]; ?>
    <?php echo $program["description"]; ?>
    <?php echo $program["series_title_fr"]; ?>
    <?php echo $program["episode_title_fr"]; ?>
    <?php echo $program["description_fr"]; ?>
     <?php echo basename($file, ".mp4"); ?>

The above html/php code display the table/td element in the following fashion:

Problem Statement:

I am wondering what changes I should make in the inline css code above so that I am able to make a small square box (as shown below) across every td element having text in css. At this moment, as shown above in an image it is
making a big square box

Body:
Your table tag needs a cellspacing.

<table cellspacing="10px">
  <tr>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["series_title"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["episode_title"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["description"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["series_title_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["episode_title_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["description_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo basename($file, ".mp4"); ?></td>
  </tr>
</table>


问:
Issue while hitting Post Method api in swift
I'm trying to call an API in which I'm trying to send some parameters and array of images, but when I hit the API I get an error, Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber dataUsingEncoding:]: unrecognized selector sent to instance 0xfb47bab3e1e91166'. I have checked through breakpoint it crashes on parameters, I'm confused why it is giving this error, my code for the API is this,

```<code>func addAPI()
{
    let headers: HTTPHeaders = [
        /* "Authorization": "your_access_token",  in case you need authorization header */
        "Content-type": "multipart/form-data"
    ]

    let parameters :[String: Any]  = ["name":productNameTxt.text!,
                                      "price":priceTxt.text!,
                                      "size": sizeTxt.text!,
                                      "weight":weightTxt.text!,
                                      "quality":qualityTxt.text!,
                                      "brand":brandTxt.text!,
                                      "shippingCost":shippingCostTxt.text!,
                                      "details":detailTxt.text!,
                                      "material_id":materialId,
                                      "material_type_id": subMaterialId,
                                      "maxQuantity":4]

    Alamofire.upload(multipartFormData: { multipartFormData in

        for (key, value) in parameters {
            if let data = ((value) as AnyObject).data(using: String.Encoding.utf8.rawValue) {
                multipartFormData.append(data, withName: key)

            }
        }

        for (index, image) in self.imageArray.enumerated() {
            multipartFormData.append(image.pngData()!, withName: "file", fileName: "image\(index).png", mimeType: "image/png")
        }
</code>```

//            for i in 0..

```<code>    },
                     to: addProductUrl,method:HTTPMethod.post,
                     headers:headers, encodingCompletion: { encodingResult in
                        switch encodingResult {
                        case .success(let upload, _, _):
                            upload
                                .validate()
                                .responseJSON { response in
                                    switch response.result {
                                    case .success(let value):
                                      //  compBlock(value as AnyObject,true)
                                        print("responseObject: \(value)")
                                    case .failure(let responseError):
                                        print("responseError: \(responseError)")
                                    }
                            }
                        case .failure(let encodingError):
                            print("encodingError: \(encodingError)")
                            let errorDesc = (encodingError as NSError).localizedDescription
                            //failure(errorDesc as NSString,false)
                        }
    })

}
</code>```

What is this error for and how I can remove it?

答:
It would be better if you follow like this:</p>

```<code> //[String:String] instead of [String : Any]
 let parameters :[String: String]  = ["name":productNameTxt.text!,
                                  "price":priceTxt.text!,
                                  "size": sizeTxt.text!,
                                  "weight":weightTxt.text!,
                                  "quality":qualityTxt.text!,
                                  "brand":brandTxt.text!,
                                  "shippingCost":shippingCostTxt.text!,
                                  "details":detailTxt.text!,
                                  "material_id":"\(materialId)",
                                  "material_type_id": subMaterialId,
                                  "maxQuantity":4]

multipartFormData.append((value.data(using: .utf8))!, withName: key)
</code>```

Body:
I'm trying to call an API in which I'm trying to send some parameters and array of images, but when I hit the API I get an error, Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber dataUsingEncoding:]: unrecognized selector sent to instance 0xfb47bab3e1e91166'. I have checked through breakpoint it crashes on parameters, I'm confused why it is giving this error, my code for the API is this,

func addAPI()
{
    let headers: HTTPHeaders = [
        /* "Authorization": "your_access_token",  in case you need authorization header */
        "Content-type": "multipart/form-data"
    ]

    let parameters :[String: Any]  = ["name":productNameTxt.text!,
                                      "price":priceTxt.text!,
                                      "size": sizeTxt.text!,
                                      "weight":weightTxt.text!,
                                      "quality":qualityTxt.text!,
                                      "brand":brandTxt.text!,
                                      "shippingCost":shippingCostTxt.text!,
                                      "details":detailTxt.text!,
                                      "material_id":materialId,
                                      "material_type_id": subMaterialId,
                                      "maxQuantity":4]

    Alamofire.upload(multipartFormData: { multipartFormData in

        for (key, value) in parameters {
            if let data = ((value) as AnyObject).data(using: String.Encoding.utf8.rawValue) {
                multipartFormData.append(data, withName: key)

            }
        }

        for (index, image) in self.imageArray.enumerated() {
            multipartFormData.append(image.pngData()!, withName: "file", fileName: "image\(index).png", mimeType: "image/png")
        }

//            for i in 0..

    },
                     to: addProductUrl,method:HTTPMethod.post,
                     headers:headers, encodingCompletion: { encodingResult in
                        switch encodingResult {
                        case .success(let upload, _, _):
                            upload
                                .validate()
                                .responseJSON { response in
                                    switch response.result {
                                    case .success(let value):
                                      //  compBlock(value as AnyObject,true)
                                        print("responseObject: \(value)")
                                    case .failure(let responseError):
                                        print("responseError: \(responseError)")
                                    }
                            }
                        case .failure(let encodingError):
                            print("encodingError: \(encodingError)")
                            let errorDesc = (encodingError as NSError).localizedDescription
                            //failure(errorDesc as NSString,false)
                        }
    })

}

What is this error for and how I can remove it?

Body:
It would be better if you follow like this:

 //[String:String] instead of [String : Any]
 let parameters :[String: String]  = ["name":productNameTxt.text!,
                                  "price":priceTxt.text!,
                                  "size": sizeTxt.text!,
                                  "weight":weightTxt.text!,
                                  "quality":qualityTxt.text!,
                                  "brand":brandTxt.text!,
                                  "shippingCost":shippingCostTxt.text!,
                                  "details":detailTxt.text!,
                                  "material_id":"\(materialId)",
                                  "material_type_id": subMaterialId,
                                  "maxQuantity":4]

multipartFormData.append((value.data(using: .utf8))!, withName: key)


问:
Swipe to switch tab selection
I have an application that is a Tab activity with various tabs that load an Activity. I would like to add swipe gesturing to switch between tabs, on both the tab control itself and each activity loaded in a tab.  Is something like this possible? I'm not sure at what "depth" the gesture is listened to when you're making gestures on an Activity hosted in the tab control, or if the inner activities would have to pass data to the Tab Host.</p>

答:
You can use a gesture detector. As far as I know it listens to gestures "globally". To restrict it to the tab you could check whether the gesture has occurred inside the boundaries of the tab.

GestureDetector

Detects various gestures and events
  using the supplied MotionEvents. The
  GestureDetector.OnGestureListener
  callback will notify users when a
  particular motion event has occurred.
  This class should only be used with
  MotionEvents reported via touch (don't
  use for trackball events). To use this
  class:

Create an instance of the
GestureDetector for your View In the
nTouchEvent(MotionEvent) method
ensure you call

onTouchEvent(MotionEvent). The
methods defined in your callback will
be executed when the events occur

Source: http://developer.android.com/reference/android/view/GestureDetector.html

Swipe Gesture

This page shows how to recognize a swipe-gesture using the GestureDetector:
http://smartandroidians.blogspot.com/2010/04/swipe-action-and-viewflipper-in-android.html

ContentLicense: CC BY-SA 3.0

Title: Swipe to switch tab selection


问:
Why does this PowerShell function's default argument change value based on the use of . or & to invoke a command within it?
I've run into some curious behaviour with a default argument that appears to change value (null or an empty string) based on whether that function used a . or & to invoke a native command inside it.

Here is an example script with two identical functions, where the only difference is how they invoke a native command (cmd.exe):

```<code>function Format-Type($value)
{
    if ($value -eq $null) { '(null)' } else { $value.GetType().FullName }
}

function Use-Dot
{
    param(
        [string] $Arg = [System.Management.Automation.Language.NullString]::Value
    )

    Write-Host ".: $(Format-Type $Arg)"

    . cmd.exe /c exit 0
}

function Use-Ampersand
{
    param(
        [string] $Arg = [System.Management.Automation.Language.NullString]::Value
    )

    Write-Host "&: $(Format-Type $Arg)"

    & cmd.exe /c exit 0
}

Use-Dot
Use-Ampersand
</code>```

On PowerShell 5.1 I get the following output which shows that the argument's value is different in the two cases:

```<code>.: (null)
&: System.String
</code>```

It sounds ludicrous for this behaviour to be correlated in this way and therefore I'm sure I must be missing something obvious (or maybe very subtle) here, but what is that?

--

The question What is the . shorthand for in a PowerShell pipeline? talks about the difference in scope between . and & but that doesn't mention why a default argument, which is not even referenced in the command invocation, might be affected by its use. In my example the caller appears to be affected before the command is even invoked.

答:
This one is fascinating, and I can't fully explain it but can confirm that it appears to be caused by dot-sourcing in the first function. I've simplified your script for repro purposes like this:

```<code>function Use-Dot
{
    param
    (
        [string]
        $Param1 = [System.Management.Automation.Language.NullString]::Value
    )

    $Param1.GetType()

    . {$null}
}

function Use-Invoke
{
    param
    (
        [string]
        $Param2 = [System.Management.Automation.Language.NullString]::Value
    )

    $Param2.GetType()

    & {$null}
}

Use-Dot
Use-Invoke
</code>```

This returns a null invocation error for Use-Dot and returns the string type for Use-Invoke:

```<code>PS C:\> C:\TestArgScope.ps1
You cannot call a method on a null-valued expression.
At c:\TestArgScope.ps1:10 char:5
+     $Param1.GetType()
+     ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object
</code>```

Now consider doing it this way:

```<code>function Use-Dot
{
    param
    (
        [string]
        $Param1
    )

    $Param1.GetType()

    . {$null}
}

function Use-Invoke
{
    param
    (
        [string]
        $Param2
    )

    $Param2.GetType()

    & {$null}
}

Use-Dot -Param1 [System.Management.Automation.Language.NullString]::Value
Use-Invoke -Param1 [System.Management.Automation.Language.NullString]::Value
</code>```

This outputs the string type for both functions, which I think indicates that the problem occurs during parameter binding when default parameter values are supplied. As SheldonH pointed out, the dot-sourcing appears to be changing the type-conversion behavior for the function that follows it, but why? I don't have all the answers, but a couple of comments:

there should be no reason to dot-source a call to cmd.exe - dot-sourcing has a very specific use case and is not the same as invoking the command.

I don't really see a reason to use the NullString type at all. I know that this isn't actually your production script so I don't know why you've demonstrated with that, but it really has a specific purpose which is for .NET method calls.

Dot-Sourcing inside a function is probably a bad idea and could have some wonky results.

String comparisons to $null are a bad idea - why use that when you can just do:

```<code>if (!($Arg)) {<do something>}
</code>```

Body:
I've run into some curious behaviour with a default argument that appears to change value (null or an empty string) based on whether that function used a . or & to invoke a native command inside it.

Here is an example script with two identical functions, where the only difference is how they invoke a native command (cmd.exe):

function Format-Type($value)
{
    if ($value -eq $null) { '(null)' } else { $value.GetType().FullName }
}

function Use-Dot
{
    param(
        [string] $Arg = [System.Management.Automation.Language.NullString]::Value
    )

    Write-Host ".: $(Format-Type $Arg)"

    . cmd.exe /c exit 0
}

function Use-Ampersand
{
    param(
        [string] $Arg = [System.Management.Automation.Language.NullString]::Value
    )

    Write-Host "&: $(Format-Type $Arg)"

    & cmd.exe /c exit 0
}

Use-Dot
Use-Ampersand

On PowerShell 5.1 I get the following output which shows that the argument's value is different in the two cases:

.: (null)
&: System.String

It sounds ludicrous for this behaviour to be correlated in this way and therefore I'm sure I must be missing something obvious (or maybe very subtle) here, but what is that?

--

The question What is the . shorthand for in a PowerShell pipeline? talks about the difference in scope between . and & but that doesn't mention why a default argument, which is not even referenced in the command invocation, might be affected by its use. In my example the caller appears to be affected before the command is even invoked.

Body:
This one is fascinating, and I can't fully explain it but can confirm that it appears to be caused by dot-sourcing in the first function. I've simplified your script for repro purposes like this:

function Use-Dot
{
    param
    (
        [string]
        $Param1 = [System.Management.Automation.Language.NullString]::Value
    )

    $Param1.GetType()

    . {$null}
}

function Use-Invoke
{
    param
    (
        [string]
        $Param2 = [System.Management.Automation.Language.NullString]::Value
    )

    $Param2.GetType()

    & {$null}
}

Use-Dot
Use-Invoke

This returns a null invocation error for Use-Dot and returns the string type for Use-Invoke:

PS C:\> C:\TestArgScope.ps1
You cannot call a method on a null-valued expression.
At c:\TestArgScope.ps1:10 char:5
+     $Param1.GetType()
+     ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

Now consider doing it this way:

function Use-Dot
{
    param
    (
        [string]
        $Param1
    )

    $Param1.GetType()

    . {$null}
}

function Use-Invoke
{
    param
    (
        [string]
        $Param2
    )

    $Param2.GetType()

    & {$null}
}

Use-Dot -Param1 [System.Management.Automation.Language.NullString]::Value
Use-Invoke -Param1 [System.Management.Automation.Language.NullString]::Value

This outputs the string type for both functions, which I think indicates that the problem occurs during parameter binding when default parameter values are supplied. As SheldonH pointed out, the dot-sourcing appears to be changing the type-conversion behavior for the function that follows it, but why? I don't have all the answers, but a couple of comments:

there should be no reason to dot-source a call to cmd.exe - dot-sourcing has a very specific use case and is not the same as invoking the command.

I don't really see a reason to use the NullString type at all. I know that this isn't actually your production script so I don't know why you've demonstrated with that, but it really has a specific purpose which is for .NET method calls.

Dot-Sourcing inside a function is probably a bad idea and could have some wonky results.

String comparisons to $null are a bad idea - why use that when you can just do:

if (!($Arg)) {<do something>}


问:
eclipse doesn't compile the project
I had running project opened in eclipse. After an accidental restart of windows, now when I open the eclipse I see my project is marked with a little red cross. Now when I run the main method I get a java.lang.NoClassDefFoundError.

I have tried restarting eclipse, Project -> Clean but it doesn't solve the problem.

When I checked the project directory, inside 'target' folder there are no compiled .class files. I tried building the project but I can't get the compiled class files, which is the reason for the error.

How do I solve this?

答:
I tried all the solutions here, but here's what worked for me.

First, remove the project from eclipse.

Then, in your project folder, delete the 2 files that eclipse creates. They're hidden, but they're called .project and .classpath.

Finally, add the project back into eclipse and eclipse will recreate those 2 files and a new configuration for your project.

My specific issue was that it a project that was missing a Java Builder because it thought it was a scala project. The only way for me to reset this was by removing the project, deleting the 2 files, and adding it back in.

Title: eclipse doesn't compile the project


问:
Powershell script to change users and launch another script
I have a script called ADInfo.ps1 that is used to query AD using the ActiveDirectory module in Powershell.  In order to run the script, you must be running Powershell as an AD user.  This is not an issue with most of our customers as we log into most of our customer's servers with AD accounts - but not always.  I know that we can run this to open a new PS window with AD credentials:

```<code>Start-Process powershell.exe -Credential ""
</code>```

I'm trying to take the thought out of this for my team, so I'm trying to find a way to run the script, and if it finds it's not running PS as a domain account that it will prompt for AD credentials and re-run the script.  So is there a variation of the line above where I could force it to launch

```<code>.\ADInfo.ps1
</code>```

as an Active Directory user?

答:
And I got it...</p>

```<code>start-process powershell.exe -argument .\AdInfo.ps1 -credential ""
</code>```

Body:
I have a script called ADInfo.ps1 that is used to query AD using the ActiveDirectory module in Powershell.  In order to run the script, you must be running Powershell as an AD user.  This is not an issue with most of our customers as we log into most of our customer's servers with AD accounts - but not always.  I know that we can run this to open a new PS window with AD credentials:

Start-Process powershell.exe -Credential ""

I'm trying to take the thought out of this for my team, so I'm trying to find a way to run the script, and if it finds it's not running PS as a domain account that it will prompt for AD credentials and re-run the script.  So is there a variation of the line above where I could force it to launch

.\ADInfo.ps1

as an Active Directory user?

Body:
And I got it...

start-process powershell.exe -argument .\AdInfo.ps1 -credential ""


问:
Why is verbose redirection creating a line between data in exported CSV file?
I have the following code that imports two csv files and merges them together. As part of the merge I remove the two files used and export one main CSV file.

```<code>$csvfiles | ForEach-Object {
    Import-Csv "$csvLocation\$_";
    Remove-Item "$csvLocation\$_" -Verbose 4>&1 | tee .\log.txt -Append
} | Export-Csv -NoTypeInformation "$csvLocation\$DBName.csv" -Force
</code>```

The CSV generated looks like this with the 4>&1 verbose redirection:

Notice the extra empty in between row between server1 and server2.

The CSV I'm expecting should be like this (no in between extra row):

```
server  Database    role    members
server1 DB1 role1   memberx
server1 DB1 role2   membery
server2 DB1 role1   memberx
server2 DB1 role2   membery
```

Of course without this part

```<code>4>&1|tee .\log.txt -append
</code>```

the exported CSV looks good. However, I want the verbose messages printed to the console and file (with 4>&1 | tee .\log.txt -Append it only seems to print to file unfortunately).

VERBOSE: Performing remove...

and the only way it works is with 4>&1.

I tried redirecting to a variable. I tried many things but to no avail.

UPDATE: In regards to the second solution HAL offered below.

```<code>$csvfiles | ForEach-Object {
    Import-Csv "$csvLocation\$_" | Export-Csv -Append -NoTypeInformation "$csvLocation\$DBName.csv" -Force;
    Remove-Item "$csvLocation\$_" -Verbose 4>&1 | tee .\log.txt -Append
}
</code>```

the output i'd normally see on the console with just -verbose looked like this:

```<code>VERBOSE: Performing the operation "Remove File" on target
"D:\MyFiles\Scripts\Migration\CSVFiles\Database1_RolesMembers_server1.domain.com.c
sv".
VERBOSE: Performing the operation "Remove File" on target
"D:\MyFiles\Scripts\Migration\CSVFiles\Database1_RolesMembers_server2.domain.com.c
sv".
</code>```

however, HAL's code results in this verbose console output:

```<code>VERBOSE: Performing the operation "Remove File" on target
"D:\MyFiles\Scripts\Migration\CSVFiles\Datab
VERBOSE: ase1_RolesMembers_server1.domain.com.csv".
VERBOSE: Performing the operation "Remove File" on target
"D:\MyFiles\Scripts\Migration\CSVFiles\Datab
VERBOSE: ase1_RolesMembers_server2.domain.com.csv".
</code>```

of course its insignificant but its worth noting the strange output style anyways

as far as the csv file generated, it STILL results in empty line, but even more:

答:
The issue is all about objects, streams and trying to force two different objects into the same stream. What is happening is illustrated with my SO answer here: Running Line by Line Produces Odd Result Compared to Running Lines as a Single Line with Semicolons

TLDR: Basically what is happening is you are trying to pass 2 different objects down the same pipeline (see about_Redirection), and PowerShell does a "best effort" interpretation which is a "bleahh -> blank" interpretation when it gets to Export-CSV. It also explains why no output to the console is displayed.

The best way to interpret what is going down the pipe is to break it up and assign to variables to see what is going on:

Unrolling the loop, the First command, and type is:

```<code>PS C:\> $csv = Import-Csv a.csv
PS C:\> $csv.GetType()

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

Second command is:

```<code>PS C:\> $ri = Remove-Item a.csv -Verbose 4>&1 | tee .\log.txt -Append
PS C:\> $ri.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    VerboseRecord                            System.Management.Automation.InformationalRecord
</code>```

Basically what is happening is, The first command:

```<code>Import-CSV ...
</code>```

Output an Object[] array to the Information (1) stream.

The second command:

```<code>Remove-Item -Verbose
</code>```

Outputs to the Verbose (4) stream.

The third command, the redirect:
    4>&1 ...

Outputs the Verbose (4) stream content to the Information (1) stream.

The fourth command,

```<code>... | tee .\log.txt -Append
</code>```

Takes the Remove-Item redirected output on the Information (1) stream, and outputs to both the Information (1) stream and the log file.

When we combine them inside the ForEach-Object loop, we are creating an array of competing objects on the Information (1) stream:

```<code>PS C:\> 1..2|foreach{$csv; $ri}

server  Database role  members
------  -------- ----  -------
server1 DB1      role1 memberx
server1 DB1      role2 membery
VERBOSE: Performing the operation "Remove File" on target "C:\a.csv".
server1 DB1      role1 memberx
server1 DB1      role2 membery
VERBOSE: Performing the operation "Remove File" on target "C:\a.csv".
</code>```

These competing objects then get passed down the pipeline to the next Export-Csv command:

```<code> 1..2 | foreach{$csv,$ri} | Export-Csv .\out.csv -NoTypeInformation
</code>```

This gets us a "Raw" CSV:

```<code>"server","Database","role","members"
"server1","DB1","role1","memberx"
"server1","DB1","role2","membery"
,,,
"server1","DB1","role1","memberx"
"server1","DB1","role2","membery"
,,,
</code>```

Where we can clearly see the 4 objects were being passed down the pipeline. The Export-Csv gets 4 objects:

Object[] array

VerboseRecord object (the Remove-Item -Verbose redirected output)

The second Object[] array

The second VerboseRecord object

This is where PowerShell will take the first Object[] array object to build the structure of the Export-Csv file. It will then take the VerboseRecord object, and since it doesn't have a way to "fit" it into the CSV, it outputs an empty record. It then  takes the second Object[], and since it "fits", will output it to the CSV. It will then take the second VerboseRecord object, and, again, since it doesn't have a way to "fit" it into the CSV, it outputs an empty record.

Notice that all 4 objects are in the CSV, even if PowerShell didn't know what to do with them. This is why you see no output on the PowerShell console. The Information (1) stream content is fully being directed down the pipeline to be consumed by the Export-Csv cmdlet, and not the console Host. This is why you don't "see" the -Verbose output from the Remove-Item command on the console, but you do see it in the file.

TLDR2: Lesson 1: Don't output multiple things to the pipeline if you have something that consumes it in the end. With pipelines, only try to work with one thing at a time.

The code can be fixed 2 ways: If you need pipelines, split the two operations into ... well... two operations to prevent corruption of the pipeline:

```<code>$csvfiles | ForEach-Object {
    Import-Csv "$csvLocation\$_";
} | Export-Csv -NoTypeInformation "$csvLocation\$DBName.csv" -Force

$csvfiles | ForEach-Object {
    Remove-Item "$csvLocation\$_" -Verbose 4>&1 | tee .\log.txt -Append
}
</code>```

Or, IMHO, don't ForEach into a pipeline and expect everything to work, as things may have to be accumulated into memory before being passed on. Eliminate the end pipeline consumer and pull the Export-Csv into the ForEach-Object loop, and append your content into it.

Edit: Don't forget to start off with an empty CSV File first :-)

```<code>Remove-Item "$csvLocation\$DBName.csv" -ErrorAction SilentlyContinue

$csvfiles | ForEach-Object {
    Import-Csv "$csvLocation\$_" | Export-Csv -Append -NoTypeInformation "$csvLocation\$DBName.csv" -Force;
    Remove-Item "$csvLocation\$_" -Verbose 4>&1 | tee .\log.txt -Append
}
</code>```

Body:
I have the following code that imports two csv files and merges them together. As part of the merge I remove the two files used and export one main CSV file.

$csvfiles | ForEach-Object {
    Import-Csv "$csvLocation\$_";
    Remove-Item "$csvLocation\$_" -Verbose 4>&1 | tee .\log.txt -Append
} | Export-Csv -NoTypeInformation "$csvLocation\$DBName.csv" -Force

The CSV generated looks like this with the 4>&1 verbose redirection:

Notice the extra empty in between row between server1 and server2.

The CSV I'm expecting should be like this (no in between extra row):

server  Database    role    members
server1 DB1 role1   memberx
server1 DB1 role2   membery
server2 DB1 role1   memberx
server2 DB1 role2   membery

Of course without this part

4>&1|tee .\log.txt -append

the exported CSV looks good. However, I want the verbose messages printed to the console and file (with 4>&1 | tee .\log.txt -Append it only seems to print to file unfortunately).

VERBOSE: Performing remove...

and the only way it works is with 4>&1.

I tried redirecting to a variable. I tried many things but to no avail.

UPDATE: In regards to the second solution HAL offered below.

$csvfiles | ForEach-Object {
    Import-Csv "$csvLocation\$_" | Export-Csv -Append -NoTypeInformation "$csvLocation\$DBName.csv" -Force;
    Remove-Item "$csvLocation\$_" -Verbose 4>&1 | tee .\log.txt -Append
}

the output i'd normally see on the console with just -verbose looked like this:

VERBOSE: Performing the operation "Remove File" on target
"D:\MyFiles\Scripts\Migration\CSVFiles\Database1_RolesMembers_server1.domain.com.c
sv".
VERBOSE: Performing the operation "Remove File" on target
"D:\MyFiles\Scripts\Migration\CSVFiles\Database1_RolesMembers_server2.domain.com.c
sv".

however, HAL's code results in this verbose console output:

VERBOSE: Performing the operation "Remove File" on target
"D:\MyFiles\Scripts\Migration\CSVFiles\Datab
VERBOSE: ase1_RolesMembers_server1.domain.com.csv".
VERBOSE: Performing the operation "Remove File" on target
"D:\MyFiles\Scripts\Migration\CSVFiles\Datab
VERBOSE: ase1_RolesMembers_server2.domain.com.csv".

of course its insignificant but its worth noting the strange output style anyways

as far as the csv file generated, it STILL results in empty line, but even more:

Body:
The issue is all about objects, streams and trying to force two different objects into the same stream. What is happening is illustrated with my SO answer here: Running Line by Line Produces Odd Result Compared to Running Lines as a Single Line with Semicolons

TLDR: Basically what is happening is you are trying to pass 2 different objects down the same pipeline (see about_Redirection), and PowerShell does a "best effort" interpretation which is a "bleahh -> blank" interpretation when it gets to Export-CSV. It also explains why no output to the console is displayed.

The best way to interpret what is going down the pipe is to break it up and assign to variables to see what is going on:

Unrolling the loop, the First command, and type is:

PS C:\> $csv = Import-Csv a.csv
PS C:\> $csv.GetType()

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

Second command is:

PS C:\> $ri = Remove-Item a.csv -Verbose 4>&1 | tee .\log.txt -Append
PS C:\> $ri.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    VerboseRecord                            System.Management.Automation.InformationalRecord

Basically what is happening is, The first command:

Import-CSV ...

Output an Object[] array to the Information (1) stream.

The second command:

Remove-Item -Verbose

Outputs to the Verbose (4) stream.

The third command, the redirect:
    4>&1 ...

Outputs the Verbose (4) stream content to the Information (1) stream.

The fourth command,

... | tee .\log.txt -Append

Takes the Remove-Item redirected output on the Information (1) stream, and outputs to both the Information (1) stream and the log file.

When we combine them inside the ForEach-Object loop, we are creating an array of competing objects on the Information (1) stream:

PS C:\> 1..2|foreach{$csv; $ri}

server  Database role  members
------  -------- ----  -------
server1 DB1      role1 memberx
server1 DB1      role2 membery
VERBOSE: Performing the operation "Remove File" on target "C:\a.csv".
server1 DB1      role1 memberx
server1 DB1      role2 membery
VERBOSE: Performing the operation "Remove File" on target "C:\a.csv".

These competing objects then get passed down the pipeline to the next Export-Csv command:

 1..2 | foreach{$csv,$ri} | Export-Csv .\out.csv -NoTypeInformation

This gets us a "Raw" CSV:

"server","Database","role","members"
"server1","DB1","role1","memberx"
"server1","DB1","role2","membery"
,,,
"server1","DB1","role1","memberx"
"server1","DB1","role2","membery"
,,,

Where we can clearly see the 4 objects were being passed down the pipeline. The Export-Csv gets 4 objects:

Object[] array

VerboseRecord object (the Remove-Item -Verbose redirected output)

The second Object[] array

The second VerboseRecord object

This is where PowerShell will take the first Object[] array object to build the structure of the Export-Csv file. It will then take the VerboseRecord object, and since it doesn't have a way to "fit" it into the CSV, it outputs an empty record. It then  takes the second Object[], and since it "fits", will output it to the CSV. It will then take the second VerboseRecord object, and, again, since it doesn't have a way to "fit" it into the CSV, it outputs an empty record.

Notice that all 4 objects are in the CSV, even if PowerShell didn't know what to do with them. This is why you see no output on the PowerShell console. The Information (1) stream content is fully being directed down the pipeline to be consumed by the Export-Csv cmdlet, and not the console Host. This is why you don't "see" the -Verbose output from the Remove-Item command on the console, but you do see it in the file.

TLDR2: Lesson 1: Don't output multiple things to the pipeline if you have something that consumes it in the end. With pipelines, only try to work with one thing at a time.

The code can be fixed 2 ways: If you need pipelines, split the two operations into ... well... two operations to prevent corruption of the pipeline:

$csvfiles | ForEach-Object {
    Import-Csv "$csvLocation\$_";
} | Export-Csv -NoTypeInformation "$csvLocation\$DBName.csv" -Force

$csvfiles | ForEach-Object {
    Remove-Item "$csvLocation\$_" -Verbose 4>&1 | tee .\log.txt -Append
}

Or, IMHO, don't ForEach into a pipeline and expect everything to work, as things may have to be accumulated into memory before being passed on. Eliminate the end pipeline consumer and pull the Export-Csv into the ForEach-Object loop, and append your content into it.

Edit: Don't forget to start off with an empty CSV File first :-)

Remove-Item "$csvLocation\$DBName.csv" -ErrorAction SilentlyContinue

$csvfiles | ForEach-Object {
    Import-Csv "$csvLocation\$_" | Export-Csv -Append -NoTypeInformation "$csvLocation\$DBName.csv" -Force;
    Remove-Item "$csvLocation\$_" -Verbose 4>&1 | tee .\log.txt -Append
}


问:
How to update pub package webdev for flutter web
when I try to "serve" my flutter web app
I'm getting this error:

This version of webdev does not support the build_daemon protocol
  used by your version of build_runner. A newer version of webdev is
  available which supports your version of the build_daemon. Please
  update.

how do I update webdev ?
"pub global" seems to offer only "activate"/ "deactivate"
and "pub upgrade" is only looking into the pubspec.yaml file

any idea?

答:
Oh... I just run "pub global deactivate " and then "pub global activate ".
Anyway I opened an issue on github suggesting to add the feature "update".
I hope this easy solution might help you,
feel free to follow up the issue.</p>


问:
How to show a histogram of percentages instead of counts using Altair
How do I get a histogram of percentages of total instead of a histogram of count using Altair and Pandas?

I have this at the moment:

Which I got by doing this:

```<code>d = {'age': ['12', '32', '43', '54', '32', '32', '12']}
dfTest = pd.DataFrame(data=d)

alt.Chart(dfTest).mark_bar().encode(
    alt.X("age:Q", bin=True),
    y='count()',
)
</code>```

答:
You can do this with a Join Aggregate transform followed by a Calculate transform:

```<code>import pandas as pd
import altair as alt

source = pd.DataFrame({'age': ['12', '32', '43', '54', '32', '32', '12']})

alt.Chart(source).transform_joinaggregate(
    total='count(*)'
).transform_calculate(
    pct='1 / datum.total'
).mark_bar().encode(
    alt.X('age:Q', bin=True),
    alt.Y('sum(pct):Q', axis=alt.Axis(format='%'))
)
</code>```

Edit: this was my initial answer, which is much more complicated:

It's not entirely straightforward, because it requires manually specifying the bin and aggregate transforms currently implied by your encoding, followed by a calculate transform to compute the percentages. Here is an example:

```<code>import pandas as pd
import altair as alt

source = pd.DataFrame({'age': ['12', '32', '43', '54', '32', '32', '12']})

alt.Chart(source).transform_bin(
    ['age_min', 'age_max'],
    field='age',
).transform_aggregate(
    count='count()',
    groupby=['age_min', 'age_max']
).transform_joinaggregate(
    total='sum(count)'
).transform_calculate(
    pct='datum.count / datum.total'
).mark_bar().encode(
    alt.X("age_min:Q", bin='binned'),
    x2='age_max',
    y=alt.Y('pct:Q', axis=alt.Axis(format='%'))
)
</code>```

I'm hoping that we'll be able to streamline the transform API in the future.

Body:
How do I get a histogram of percentages of total instead of a histogram of count using Altair and Pandas?

I have this at the moment:

Which I got by doing this:

d = {'age': ['12', '32', '43', '54', '32', '32', '12']}
dfTest = pd.DataFrame(data=d)

alt.Chart(dfTest).mark_bar().encode(
    alt.X("age:Q", bin=True),
    y='count()',
)

Body:
You can do this with a Join Aggregate transform followed by a Calculate transform:

import pandas as pd
import altair as alt

source = pd.DataFrame({'age': ['12', '32', '43', '54', '32', '32', '12']})

alt.Chart(source).transform_joinaggregate(
    total='count(*)'
).transform_calculate(
    pct='1 / datum.total'
).mark_bar().encode(
    alt.X('age:Q', bin=True),
    alt.Y('sum(pct):Q', axis=alt.Axis(format='%'))
)

Edit: this was my initial answer, which is much more complicated:

It's not entirely straightforward, because it requires manually specifying the bin and aggregate transforms currently implied by your encoding, followed by a calculate transform to compute the percentages. Here is an example:

import pandas as pd
import altair as alt

source = pd.DataFrame({'age': ['12', '32', '43', '54', '32', '32', '12']})

alt.Chart(source).transform_bin(
    ['age_min', 'age_max'],
    field='age',
).transform_aggregate(
    count='count()',
    groupby=['age_min', 'age_max']
).transform_joinaggregate(
    total='sum(count)'
).transform_calculate(
    pct='datum.count / datum.total'
).mark_bar().encode(
    alt.X("age_min:Q", bin='binned'),
    x2='age_max',
    y=alt.Y('pct:Q', axis=alt.Axis(format='%'))
)

I'm hoping that we'll be able to streamline the transform API in the future.


问:
check if username exists inside firebase database
Am trying to check if a username exists from a database by calling the function checkifUsernameExists(username) within an if statement. the problem is firebase's built function called

```<code> public void onDataChange(@NonNull DataSnapshot dataSnapshot)
</code>```

cannot return a boolean value. What can i do?

```<code>    mCreateBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String username = musername.getText().toString();
            String email = mEmail.getText().toString();
            String password = mPassword.getText().toString();

            if (TextUtils.isEmpty(username) || TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
                Toast.makeText(registerActivity.this, "Cannot sign you in. Please check the form and try again",
                        Toast.LENGTH_SHORT).show();
            } else if (password.length() < 6) {
                Toast.makeText(registerActivity.this, "Password must be at least 6 characters",Toast.LENGTH_LONG).show();
            } else if (email_exists == true) {
                Toast.makeText(registerActivity.this, "Email already exists",Toast.LENGTH_LONG).show();
            } else if (checkifUsernameExists(username)) {
                Toast.makeText(registerActivity.this, "Username already exists", Toast.LENGTH_LONG).show();
            } else {
                message.setTitle("Registering user");
                message.setMessage("Pleases wait while we create your account");
                message.setCanceledOnTouchOutside(false);
                message.show();
                //registerUser(username, email, password);
            }

        }
    });
}
</code>```

```<code>
    private boolean checkifUsernameExists(String username) {
        Query usernameQuery = FirebaseDatabase.getInstance().getReference().child("users").orderByChild("username").equalTo(username);
        usernameQuery.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.getChildrenCount() > 0) {

                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

</code>```

答:
Make the checkifUsernameExists() method void and call the registerUser() method inside it if the username doesn't exist in the database.</p>

```<code>mCreateBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        String username = musername.getText().toString();
        String email = mEmail.getText().toString();
        String password = mPassword.getText().toString();

        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
            Toast.makeText(registerActivity.this, "Cannot sign you in. Please check the form and try again",
                    Toast.LENGTH_SHORT).show();
        } else if (password.length() < 6) {
            Toast.makeText(registerActivity.this, "Password must be at least 6 characters",Toast.LENGTH_LONG).show();
        } else if (email_exists == true) {
            Toast.makeText(registerActivity.this, "Email already exists",Toast.LENGTH_LONG).show();
        } else {
            checkifUsernameExists(username, email, password);
        }

    }
});

private void checkifUsernameExists(final String username, final String email, final String password) {

    Query usernameQuery = FirebaseDatabase.getInstance().getReference().child("users").orderByChild("username").equalTo(username);
    usernameQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                // the username is already in the database
                Toast.makeText(registerActivity.this, "Username already exists", Toast.LENGTH_LONG).show();
            }else {
                message.setTitle("Registering user");
                message.setMessage("Pleases wait while we create your account");
                message.setCanceledOnTouchOutside(false);
                message.show();
                registerUser(username, email, password);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}
</code>```

Body:
Am trying to check if a username exists from a database by calling the function checkifUsernameExists(username) within an if statement. the problem is firebase's built function called

 public void onDataChange(@NonNull DataSnapshot dataSnapshot)

cannot return a boolean value. What can i do?

    mCreateBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String username = musername.getText().toString();
            String email = mEmail.getText().toString();
            String password = mPassword.getText().toString();

            if (TextUtils.isEmpty(username) || TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
                Toast.makeText(registerActivity.this, "Cannot sign you in. Please check the form and try again",
                        Toast.LENGTH_SHORT).show();
            } else if (password.length() < 6) {
                Toast.makeText(registerActivity.this, "Password must be at least 6 characters",Toast.LENGTH_LONG).show();
            } else if (email_exists == true) {
                Toast.makeText(registerActivity.this, "Email already exists",Toast.LENGTH_LONG).show();
            } else if (checkifUsernameExists(username)) {
                Toast.makeText(registerActivity.this, "Username already exists", Toast.LENGTH_LONG).show();
            } else {
                message.setTitle("Registering user");
                message.setMessage("Pleases wait while we create your account");
                message.setCanceledOnTouchOutside(false);
                message.show();
                //registerUser(username, email, password);
            }

        }
    });
}

    private boolean checkifUsernameExists(String username) {
        Query usernameQuery = FirebaseDatabase.getInstance().getReference().child("users").orderByChild("username").equalTo(username);
        usernameQuery.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.getChildrenCount() > 0) {

                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

Body:
Make the checkifUsernameExists() method void and call the registerUser() method inside it if the username doesn't exist in the database.

mCreateBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        String username = musername.getText().toString();
        String email = mEmail.getText().toString();
        String password = mPassword.getText().toString();

        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
            Toast.makeText(registerActivity.this, "Cannot sign you in. Please check the form and try again",
                    Toast.LENGTH_SHORT).show();
        } else if (password.length() < 6) {
            Toast.makeText(registerActivity.this, "Password must be at least 6 characters",Toast.LENGTH_LONG).show();
        } else if (email_exists == true) {
            Toast.makeText(registerActivity.this, "Email already exists",Toast.LENGTH_LONG).show();
        } else {
            checkifUsernameExists(username, email, password);
        }

    }
});

private void checkifUsernameExists(final String username, final String email, final String password) {

    Query usernameQuery = FirebaseDatabase.getInstance().getReference().child("users").orderByChild("username").equalTo(username);
    usernameQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                // the username is already in the database
                Toast.makeText(registerActivity.this, "Username already exists", Toast.LENGTH_LONG).show();
            }else {
                message.setTitle("Registering user");
                message.setMessage("Pleases wait while we create your account");
                message.setCanceledOnTouchOutside(false);
                message.show();
                registerUser(username, email, password);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}


问:
How can I remove all white space in a string and store the data in between?
I am a new programmer (< 1 year) so please forgive if I am making a simple thing complicated.

I'm trying to remove all the white space (the tab and space characters) in a given string and store the data as individual elements in a vector as I go. I also want to account for leading and trailing white space.

I've tried using string methods to move two indexes forward in the string while checking along the way for these characters. I've rewritten the code at least five times so far and I always end up with:

```<code>terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::at: __n (which is 7754) >= this->size() (which is 42)
Aborted (core dumped)
</code>```

#include <iostream>
#include <string>
#include <vector>

using namespace std;

void  makeTokens(string& separate);

int main()
{
    string test = "  u       65.45\t\t   36.12\t     78.25  0.00";

    makeTokens(test);

    return 0;
}

void  makeTokens(string& separate)
{
    vector<string> tokens;
    unsigned short index1, index2 = 0;

    while (separate.at(index1) == ' ' || separate.at(index1) == '\t')
    {
        index1++;
        index2 = index1 + 1;
    }

    while (index2 < separate.length())
    {
        if (separate.at(index2) == ' ' || separate.at(index2) == '\t')
        {
            tokens.push_back(separate.substr(index1, index2 - index1));

            index1 = index2;

            while (separate.at(index1) == ' ' || separate.at(index1) == '\t')
            {
                index1++;
            }

            index2 = index1 + 1;
        }
        else
        {
            index2++;
        }

        if (index2 == separate.length() - 1)
        {
            if (separate.at(index2) == ' ' || separate.at(index2) == '\t')
            {
                tokens.push_back(separate.substr(index1));
            }
        }
    }

    for (unsigned short i = 0; i < tokens.size(); i++)
    {
        cout << tokens[i] << "|" << endl;
    }
}
```

<p>I want the console to output:</p>

```u|
65.45|
36.12|
78.25|
0.00|
```

<p>If a similar test string were passed, except with white space on the end, I still want the same output.</p>

<p>EDIT:
I have changed my index declarations to:</p>

```unsigned short index1 = 0;
unsigned short index2 = 0;
```

<p>Now the console outputs:</p>

```u|
65.45|
36.12|
78.25|
```

The final 0.00 is still missing.

答:
The first instance of undefined behavior is here:

```<code>    unsigned short index1, ...

    while (separate.at(index1) ...
//                     ^^^^^^
</code>```

index1 is not initialized.

Body:
I am a new programmer (< 1 year) so please forgive if I am making a simple thing complicated.

I'm trying to remove all the white space (the tab and space characters) in a given string and store the data as individual elements in a vector as I go. I also want to account for leading and trailing white space.

I've tried using string methods to move two indexes forward in the string while checking along the way for these characters. I've rewritten the code at least five times so far and I always end up with:

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::at: __n (which is 7754) >= this->size() (which is 42)
Aborted (core dumped)

#include <iostream>
#include <string>
#include <vector>

using namespace std;

void  makeTokens(string& separate);

int main()
{
    string test = "  u       65.45\t\t   36.12\t     78.25  0.00";

    makeTokens(test);

    return 0;
}

void  makeTokens(string& separate)
{
    vector<string> tokens;
    unsigned short index1, index2 = 0;

    while (separate.at(index1) == ' ' || separate.at(index1) == '\t')
    {
        index1++;
        index2 = index1 + 1;
    }

    while (index2 < separate.length())
    {
        if (separate.at(index2) == ' ' || separate.at(index2) == '\t')
        {
            tokens.push_back(separate.substr(index1, index2 - index1));

            index1 = index2;

            while (separate.at(index1) == ' ' || separate.at(index1) == '\t')
            {
                index1++;
            }

            index2 = index1 + 1;
        }
        else
        {
            index2++;
        }

        if (index2 == separate.length() - 1)
        {
            if (separate.at(index2) == ' ' || separate.at(index2) == '\t')
            {
                tokens.push_back(separate.substr(index1));
            }
        }
    }

    for (unsigned short i = 0; i < tokens.size(); i++)
    {
        cout << tokens[i] << "|" << endl;
    }
}

I want the console to output:

u|
65.45|
36.12|
78.25|
0.00|

If a similar test string were passed, except with white space on the end, I still want the same output.

EDIT:
I have changed my index declarations to:

unsigned short index1 = 0;
unsigned short index2 = 0;

Now the console outputs:

u|
65.45|
36.12|
78.25|

The final 0.00 is still missing.

Body:
The first instance of undefined behavior is here:

    unsigned short index1, ...

    while (separate.at(index1) ...
//                     ^^^^^^

index1 is not initialized.


问:
Fatal Error Unable to attach to base address
When I try to do a composer update, it appears the following message: "Fatal Error Unable to attach to base address"
I'm using symfony 3

I hope you could help me. Thanks

Error image

答: The only thing that fixed this for us was to reboot our computer. Go figure!</p>


问:
How to resize images and appropriate xml files accordingly?
I am trying to apply object detection model to dataset that includes about 180 images and same number of xml files with bounding boxes coordinates for each image.
The problem is that all the images are of different size, but before putting them into the model they all should be of same size. If I just resize images all coordinates of bounding boxes will become incorrect so they should be updated too.

One solution is to resize images and them manually update each xml file, but would be good to have some other solution.

答:
To resize your bounding box coordinates, you can use the following logic:
If your original image dimensions are (width_orig,height_orig),your resized image dimensions are (width_new,height_new) and your initial bounding box coordinates are x_min,y_min,x_max,y_max, your new bounding box coordinates will be x_min*x_scale,y_min*y_scale,x_max*x_scale,y_max*y_scale where x_scale = width_new/width_orig
y_scale = height_new/height_orig
Hopefully, if you finally need your annotations in csv format, you can use this xml_to_csv converter to convert your xml files to csv and then read and modify the rows in csv file appropriately.

Hope this helps!


问:
How can I get these values and text strings added in during my for/next loop?
I have a series of numbers that get updated to a master sheet based on their own separate tabs. I enter a set of numbers in rngB and they populate based on the dimensions of the for/next loop based on the multipliers in the array multplr.

Everything works as it should, but I'm trying to also have a range (x,40) populate with this: wsA.Cells(x, 40).Formula = "=""TSR: ""&AX6&"" - ""&AY6&"" - ""&AZ6&"" USD Annual"

Loop:

```<code>        For x = 6 To FinalRow
            wsA.Cells(x, 40).Formula = "=""TSR: ""&AX6&"" - ""&AY6&"" - ""&AZ6&"" USD Annual"
        Next x
</code>```

it populates the formula, but doesn't autofill like it should, it just repeats the save thing in Cells(6,40)

I know there's the autofill/destination method, but my prior for/next formula loop works as it should, so I'm confused what's going on here.

Rest of script:

```<code>Sub UpdateTSRS()

Dim wbk As Workbook
Dim wsA As Worksheet, wsB As Worksheet
Dim rngA As Range, rngB As Range, rngC As Range
Dim rIterator As Range, c As Range, spread As Range
Dim fndRow As Long, i As Long, j As Long, x As Long
Dim multplr As Variant
Dim FinalRow
multplr = Array(1, 1.1, 1.15, 1.2, 1.3)

Set wbk = ThisWorkbook
Set wsA = wbk.Sheets("Annual")
Set wsB = wbk.Sheets("New Annual")
Set rngA = wsA.Range(wsA.Range("E6"), wsA.Range("E6").End(xlDown))
Set rngB = wsB.Range(wsB.Range("A2"), wsB.Range("A2").End(xlDown))
Set rngC = wsA.Range(wsA.Range("AW6"), wsA.Range("AW6").End(xlDown))

FinalRow = wsA.Cells(Rows.Count, 49).End(xlUp).Row

For Each rIterator In rngB
        On Error Resume Next
        fndRow = Application.Match(rIterator.Value, rngA, 0) + _
            rngA.Range("E1").Row - 1
        If Err.Number <> 0 Then
        Else
        For i = 0 To 4
            For j = 3 To 9
                If j <> 6 Then
                Set c = wsA.Cells(fndRow + i, j + 43)
                c.Interior.Color = VBA.RGB(255, 255, 0)
                wsA.Cells(fndRow + i, j + 43).Value = rIterator.Offset(, j - 1).Value * multplr(i)
            End If
            Next j
        Next i
        End If
        Err.Clear
    Next rIterator

        For x = 6 To FinalRow
            wsA.Cells(x, 49).FormulaR1C1 = "=RC[-1]-RC[-3]"
        Next x

        For x = 6 To FinalRow
            wsA.Cells(x, 40).Formula = "=""TSR: ""&AX6&"" - ""&AY6&"" - ""&AZ6&"" USD Annual"
        Next x
End Sub
</code>```

答:
No loop needed:

```<code>wsA.Range(wsA.Cells(6, 40),wsA.Cells(FinalRow, 40)).Formula = "=""TSR: ""&AX6&"" - ""&AY6&"" - ""&AZ6&"" USD Annual"
</code>```

Same with other formula:

```<code>wsA.Range(wsA.Cells(6, 49),wsA.Cells(FinalRow, 49)).FormulaR1C1 = "=RC[-1]-RC[-3]"
</code>```

Body:
I have a series of numbers that get updated to a master sheet based on their own separate tabs. I enter a set of numbers in rngB and they populate based on the dimensions of the for/next loop based on the multipliers in the array multplr.

Everything works as it should, but I'm trying to also have a range (x,40) populate with this: wsA.Cells(x, 40).Formula = "=""TSR: ""&AX6&"" - ""&AY6&"" - ""&AZ6&"" USD Annual"

Loop:

        For x = 6 To FinalRow
            wsA.Cells(x, 40).Formula = "=""TSR: ""&AX6&"" - ""&AY6&"" - ""&AZ6&"" USD Annual"
        Next x

it populates the formula, but doesn't autofill like it should, it just repeats the save thing in Cells(6,40)

I know there's the autofill/destination method, but my prior for/next formula loop works as it should, so I'm confused what's going on here.

Rest of script:

Sub UpdateTSRS()

Dim wbk As Workbook
Dim wsA As Worksheet, wsB As Worksheet
Dim rngA As Range, rngB As Range, rngC As Range
Dim rIterator As Range, c As Range, spread As Range
Dim fndRow As Long, i As Long, j As Long, x As Long
Dim multplr As Variant
Dim FinalRow
multplr = Array(1, 1.1, 1.15, 1.2, 1.3)

Set wbk = ThisWorkbook
Set wsA = wbk.Sheets("Annual")
Set wsB = wbk.Sheets("New Annual")
Set rngA = wsA.Range(wsA.Range("E6"), wsA.Range("E6").End(xlDown))
Set rngB = wsB.Range(wsB.Range("A2"), wsB.Range("A2").End(xlDown))
Set rngC = wsA.Range(wsA.Range("AW6"), wsA.Range("AW6").End(xlDown))

FinalRow = wsA.Cells(Rows.Count, 49).End(xlUp).Row

For Each rIterator In rngB
        On Error Resume Next
        fndRow = Application.Match(rIterator.Value, rngA, 0) + _
            rngA.Range("E1").Row - 1
        If Err.Number <> 0 Then
        Else
        For i = 0 To 4
            For j = 3 To 9
                If j <> 6 Then
                Set c = wsA.Cells(fndRow + i, j + 43)
                c.Interior.Color = VBA.RGB(255, 255, 0)
                wsA.Cells(fndRow + i, j + 43).Value = rIterator.Offset(, j - 1).Value * multplr(i)
            End If
            Next j
        Next i
        End If
        Err.Clear
    Next rIterator

        For x = 6 To FinalRow
            wsA.Cells(x, 49).FormulaR1C1 = "=RC[-1]-RC[-3]"
        Next x

        For x = 6 To FinalRow
            wsA.Cells(x, 40).Formula = "=""TSR: ""&AX6&"" - ""&AY6&"" - ""&AZ6&"" USD Annual"
        Next x
End Sub

Body:
No loop needed:

wsA.Range(wsA.Cells(6, 40),wsA.Cells(FinalRow, 40)).Formula = "=""TSR: ""&AX6&"" - ""&AY6&"" - ""&AZ6&"" USD Annual"

Same with other formula:

wsA.Range(wsA.Cells(6, 49),wsA.Cells(FinalRow, 49)).FormulaR1C1 = "=RC[-1]-RC[-3]"


问:
How to get DayOfWeek from an Instant.now()
Assuming the following code...

```<code>Instant x = Instant.now();
</code>```

How do I get day of week from x?

答:
I have awarded points to techtabu, but I ended up using atOffset instead.  Here is where I ended up...

```<code>int currentDayOfWeekValue = Instant.now().atOffset(ZoneOffset.UTC).getDayOfWeek().getValue();
</code>```

I am amazed how difficult the Java8 datetime libraries are.  There are so many variations of similar concepts...

Instant

LocalDate

LocalTime

LocalDateTime

OffsetDateTime

ZoneOffset

ZonedDateTime

Rhetorical questions:

Is Zulu and UTC the same or different?

What is the timezone associated with Instant.now() - the results suggest Zulu?

Why can't I manipulate an Instant object like a LocalDateTime - methods are similar but different?

How are ZonedDateTime and OffsetDateTime different - they seem to be addressing the same concept.

Body:
Assuming the following code...

Instant x = Instant.now();

How do I get day of week from x?

Body:
I have awarded points to techtabu, but I ended up using atOffset instead.  Here is where I ended up...

int currentDayOfWeekValue = Instant.now().atOffset(ZoneOffset.UTC).getDayOfWeek().getValue();

I am amazed how difficult the Java8 datetime libraries are.  There are so many variations of similar concepts...

Instant

LocalDate

LocalTime

LocalDateTime

OffsetDateTime

ZoneOffset

ZonedDateTime

Rhetorical questions:

Is Zulu and UTC the same or different?

What is the timezone associated with Instant.now() - the results suggest Zulu?

Why can't I manipulate an Instant object like a LocalDateTime - methods are similar but different?

How are ZonedDateTime and OffsetDateTime different - they seem to be addressing the same concept.


问:
"Attempting to use incompatible return type" with class implementing Serializable
I have the following interface:

Slicer

```<code>public interface Slicer {
    Optional<Map<String, ? extends Serializable>> pointer();
}
</code>```

of which I have an implementation:

DynamoDbSlicer

```<code>public abstract class DynamoDbSlicer implements Slicer {

    @Override
    public abstract Optional<Map<String, AttributeValue> pointer();
}
</code>```

where AttributeValue is from the AWS SDK and defined as:

```<code>public final class AttributeValue implements SdkPojo, Serializable, ToCopyableBuilder<AttributeValue.Builder, AttributeValue> {
</code>```

Note that it implements Serializable.

I am getting a compiler error on the abstract method in DynamoDbSlicer:

```<code>pointer() in DynamoDbSlicer clashes with pointer() in Slicer; attempting to use incompatible return type
</code>```

What am I missing?

答:
At first glance, this looks like it should compile, because Java (since 1.5) has had return type covariance.  This means that an overriding method can declare a return type that is a subtype of the original method's return type.

It looks like Optional<Map<String, Serializable>> is a subtype of Optional<Map<String, ? extends Serializable>>, but it's not.  Interestingly, if you remove the Optional part from both return types, this compiles.

```<code>interface Slicer {
    Map<String, ? extends Serializable> pointer();
}
abstract class DynamoDbSlicer implements Slicer {
    @Override
    public abstract Map<String, Serializable> pointer();
}
</code>```

It compiles because Map<String, Serializable> is a subtype of Map<String, ? extends Serializable> -- one can assign an instance of the former to a variable of the latter type.

However, adding Optional makes it fail to compile for the same reason that a List<Dog> isn't a List<Animal> -- generics are invariant.  In this analogy, Dog is like the specific subtype that matches Map<String, Serializable>, and Animal is like the general type that matches Map<String, ? extends Serializable>.  Just like a List<Dog> is not a List<Animal>, a Optional<Map<String, Serializable>> is not a Optional<Map<String, ? extends Serializable>>.

The easiest way of getting this to compile without removing the Optional bit is to match the type exactly.

```<code>abstract class DynamoDbSlicer implements Slicer {
    @Override
    public abstract Map<String, ? extends Serializable> pointer();
}
</code>```

If this doesn't fit your requirements, then you'll need to create a type parameter on the interface that your class can supply as a type argument.

```<code>interface Slicer<T extends Serializable> {
    Optional<Map<String, T>> pointer();
}
abstract class DynamoDbSlicer implements Slicer<AttributeValue> {
    @Override
    public abstract Optional<Map<String, AttributeValue>> pointer();
}
</code>```

The type parameter allows this to compile.

Body:
I have the following interface:

Slicer

public interface Slicer {
    Optional<Map<String, ? extends Serializable>> pointer();
}

of which I have an implementation:

DynamoDbSlicer

public abstract class DynamoDbSlicer implements Slicer {

    @Override
    public abstract Optional<Map<String, AttributeValue> pointer();
}

where AttributeValue is from the AWS SDK and defined as:

public final class AttributeValue implements SdkPojo, Serializable, ToCopyableBuilder<AttributeValue.Builder, AttributeValue> {

Note that it implements Serializable.

I am getting a compiler error on the abstract method in DynamoDbSlicer:

pointer() in DynamoDbSlicer clashes with pointer() in Slicer; attempting to use incompatible return type

What am I missing?

Body:
At first glance, this looks like it should compile, because Java (since 1.5) has had return type covariance.  This means that an overriding method can declare a return type that is a subtype of the original method's return type.

It looks like Optional<Map<String, Serializable>> is a subtype of Optional<Map<String, ? extends Serializable>>, but it's not.  Interestingly, if you remove the Optional part from both return types, this compiles.

interface Slicer {
    Map<String, ? extends Serializable> pointer();
}
abstract class DynamoDbSlicer implements Slicer {
    @Override
    public abstract Map<String, Serializable> pointer();
}

It compiles because Map<String, Serializable> is a subtype of Map<String, ? extends Serializable> -- one can assign an instance of the former to a variable of the latter type.

However, adding Optional makes it fail to compile for the same reason that a List<Dog> isn't a List<Animal> -- generics are invariant.  In this analogy, Dog is like the specific subtype that matches Map<String, Serializable>, and Animal is like the general type that matches Map<String, ? extends Serializable>.  Just like a List<Dog> is not a List<Animal>, a Optional<Map<String, Serializable>> is not a Optional<Map<String, ? extends Serializable>>.

The easiest way of getting this to compile without removing the Optional bit is to match the type exactly.

abstract class DynamoDbSlicer implements Slicer {
    @Override
    public abstract Map<String, ? extends Serializable> pointer();
}

If this doesn't fit your requirements, then you'll need to create a type parameter on the interface that your class can supply as a type argument.

interface Slicer<T extends Serializable> {
    Optional<Map<String, T>> pointer();
}
abstract class DynamoDbSlicer implements Slicer<AttributeValue> {
    @Override
    public abstract Optional<Map<String, AttributeValue>> pointer();
}

The type parameter allows this to compile.


问:
MVC5 textarea rows cols work only when specified explicitly and not via htmlAttributes
@Html.TextAreaFor(model => model.DESCRIPTION, 20, 50, new { htmlAttributes = new { @class = "form-control"} })

Question: The above code displays rows and cols of textarea correctly but the below ignores rows/cols and displays the default size per browser. What's wrong in below code?

The extra new in below code was auto created by VS when creating a MVC Entity Framework controller (as documented at http://www.asp.net/mvc/overview/releases/mvc51-release-notes)

@Html.TextAreaFor(model => model.DESCRIPTION, new { htmlAttributes = new { @class = "form-control", @rows="20", @cols="50"} })

答:
Replace this

```<code>@Html.TextAreaFor(model => model.DESCRIPTION, 20, 50, new { htmlAttributes = new { @class = "form-control"} })
</code>```

For This

```<code>@Html.TextAreaFor(model => model.DESCRIPTION, 20, 50, htmlAttributes: new { @class = "form-control",@rows="6" })
</code>```

Body:
Replace this

@Html.TextAreaFor(model => model.DESCRIPTION, 20, 50, new { htmlAttributes = new { @class = "form-control"} })

For This

@Html.TextAreaFor(model => model.DESCRIPTION, 20, 50, htmlAttributes: new { @class = "form-control",@rows="6" })