问:
Delete specific files in directory using C#
There are many .bmp files present in my C:\TEMP directory.

I am using following code to delete all .bmp file in my C:\TEMP directory but somehow its not working as I expect. Can anyone help me in this?

```<code>string[] filePaths = Directory.GetFiles(@"c:\TEMP\");
foreach (string filePath in filePaths)
{
    if (filePath.Contains(".bmp"))
        File.Delete(filePath);
}
</code>```

I have already checked that .bmp file and the directory has no read only attribute

答:
For starters, GetFiles has an overload which takes a search pattern http://msdn.microsoft.com/en-us/library/wz42302f.aspx so you can do:

```<code>Directory.GetFiles(@"C:\TEMP\", "*.bmp");
</code>```

Edit: For the case of deleting all .bmp files in TEMP:

```<code>string[] filePaths = Directory.GetFiles(@"c:\TEMP\", "*.bmp");
foreach (string filePath in filePaths)
    {
        File.Delete(filePath);
    }
</code>```

This deletes all .bmp files in the folder but does not access subfolders.

Body:
There are many .bmp files present in my C:\TEMP directory.

I am using following code to delete all .bmp file in my C:\TEMP directory but somehow its not working as I expect. Can anyone help me in this?

string[] filePaths = Directory.GetFiles(@"c:\TEMP\");
foreach (string filePath in filePaths)
{
    if (filePath.Contains(".bmp"))
        File.Delete(filePath);
}

I have already checked that .bmp file and the directory has no read only attribute

Body:
For starters, GetFiles has an overload which takes a search pattern http://msdn.microsoft.com/en-us/library/wz42302f.aspx so you can do:

Directory.GetFiles(@"C:\TEMP\", "*.bmp");

Edit: For the case of deleting all .bmp files in TEMP:

string[] filePaths = Directory.GetFiles(@"c:\TEMP\", "*.bmp");
foreach (string filePath in filePaths)
    {
        File.Delete(filePath);
    }

This deletes all .bmp files in the folder but does not access subfolders.


来源: stackexchange

问:
Multidimensional Array - Illegal String Offset
I have an array that for some reason keeps kicking back an error "Illegal String Offset" I have tried several ways to loop through it but none seem to work.

```<code>$fields = Array (
[cookies] => Array (
    [timeout] => 0
    [votes_per_cookie] => 1
    [enabled] => on
    )
[ip] => Array (
    [timeout] => 0
    [filter] =>
    )
[direct] =>  Array ( )
[membership] => Array (
    [type] => Array ( )
    [once] =>  Array ( )
    )
[captcha] =>  Array ( )
[quota] => Array (
    [votes] => 1000
    )
[date] => Array (
    [start] => 1553846400
    [end] => 1554767940
    [enabled] => on
    )
[selection] => Array (
    [minimum] => 1
    [maximum] => 1
    )
[unique_id] => 1547834405
[results] => Array (
    [require_vote] => Array (
        [enabled] => on
        )
    )
);
</code>```

I am trying to get the value of end in the date array. I have tried this:

```<code>foreach($fields as $field) {
  echo $field['end'];
}
</code>```

this outputs the data but also the illegal offset error.

I have tried this:

```<code>foreach($fields as $key => $value) {
  echo $value['end'];
}
</code>```

This also outputs the same reponse.

if I echo key using the above loop, it returns the appropriate keys (cookies, ip, direct, membership, etc)

I have also tried:

```<code>foreach($fields['date'] as $field) {
    $field['end'];
  }
</code>```

This is just an error.

And finally

```<code>foreach($fields as $field) {
  $field['date']['end'];
}
</code>```

just an error.

答:
Your array should look like this in order to loop through.
I've added quotation strings ("") to your indexes and to your on value. Else you would get a warning: like this 'Use of undefined constant on'.Hope this helps!.

```<code>     $fields = array (
      'cookies' => array ('timeout' => 0,'votes_per_cookie' => 1,'enabled' => 'on'),
      'ip'=> array ('timeout' => 0,'filter' => '',),
      'direct' =>  array (),
      'membership' => array ('type' => array (),'once' =>  array ()),
      'captcha' =>  array (),
      'quota' => array ('votes' => 1000,),
      'date' => array ('start' => 1553846400,'end' => 1554767940,'enabled' => 'on',),
      'selection' => array ('minimum' => 1,'maximum' => 1,),
      'unique_id' => 1547834405,
      'results' => array ('require_vote' => array ('enabled' => 'on'))
    );
</code>```

Now you can loop through it properly with a foreach:

```<code>foreach($fields as $key => $value) {
  if($key == 'date'){
    print_r($value);
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an array that for some reason keeps kicking back an error "Illegal String Offset" I have tried several ways to loop through it but none seem to work.

$fields = Array (
[cookies] => Array (
    [timeout] => 0
    [votes_per_cookie] => 1
    [enabled] => on
    )
[ip] => Array (
    [timeout] => 0
    [filter] =>
    )
[direct] =>  Array ( )
[membership] => Array (
    [type] => Array ( )
    [once] =>  Array ( )
    )
[captcha] =>  Array ( )
[quota] => Array (
    [votes] => 1000
    )
[date] => Array (
    [start] => 1553846400
    [end] => 1554767940
    [enabled] => on
    )
[selection] => Array (
    [minimum] => 1
    [maximum] => 1
    )
[unique_id] => 1547834405
[results] => Array (
    [require_vote] => Array (
        [enabled] => on
        )
    )
);

I am trying to get the value of end in the date array. I have tried this:

foreach($fields as $field) {
  echo $field['end'];
}

this outputs the data but also the illegal offset error.

I have tried this:

foreach($fields as $key => $value) {
  echo $value['end'];
}

This also outputs the same reponse.

if I echo key using the above loop, it returns the appropriate keys (cookies, ip, direct, membership, etc)

I have also tried:

foreach($fields['date'] as $field) {
    $field['end'];
  }

This is just an error.

And finally

foreach($fields as $field) {
  $field['date']['end'];
}

just an error.

Body:
Your array should look like this in order to loop through.
I've added quotation strings ("") to your indexes and to your on value. Else you would get a warning: like this 'Use of undefined constant on'.Hope this helps!.

     $fields = array (
      'cookies' => array ('timeout' => 0,'votes_per_cookie' => 1,'enabled' => 'on'),
      'ip'=> array ('timeout' => 0,'filter' => '',),
      'direct' =>  array (),
      'membership' => array ('type' => array (),'once' =>  array ()),
      'captcha' =>  array (),
      'quota' => array ('votes' => 1000,),
      'date' => array ('start' => 1553846400,'end' => 1554767940,'enabled' => 'on',),
      'selection' => array ('minimum' => 1,'maximum' => 1,),
      'unique_id' => 1547834405,
      'results' => array ('require_vote' => array ('enabled' => 'on'))
    );

Now you can loop through it properly with a foreach:

foreach($fields as $key => $value) {
  if($key == 'date'){
    print_r($value);
  }
}


问:
Angular 7 http error handling not working properly
I am trying to handle 422 error handling on my HTTP request. But somehow the error block doesn't run in the service using catchError operator. If there is no error the code is just working fine. I want to display error message on my page. But angular is only throwing error in console and not running the error block.
Here is my http error response:

And here is the error I am getting only in console.

I want to display error message on my page. Here is my HTTP request.

```<code> renderPlugin(id): Observable<any> {
 return this.http
      .get(`${environment.kbUrl}/${id}?_as_json=1&_nbp=1`, {
        responseType: "text",
        observe: "response"
      })
      .pipe(
        catchError((res: HttpErrorResponse) => {
          console.log(JSON.stringify(res));
          this.toastr.error("error", JSON.stringify(res));
          return throwError(JSON.stringify(res));
        })
      );
  }
</code>```

And here is my method to subscribe to the it.

```<code>this.pluginsService.renderPlugin(this.currentId).subscribe(res =>{
    this.currentString = res.body;
    this.plugin = this.currentString.data.content;
    console.log(this.plugin);
      },
      err =>{
        this.plugin = err;
      });
</code>```

答:
Try removing this code from your Http call:

```<code>  .pipe(
    catchError((res: HttpErrorResponse) => {
      console.log(JSON.stringify(res));
      this.toastr.error("error", JSON.stringify(res));
      return throwError(JSON.stringify(res));
    })
  )
</code>```

And handle your error inside the error block of your subscribe method.

```<code>this.pluginsService.renderPlugin(this.currentId).subscribe(
    res => {
        this.currentString = res.body;
        this.plugin = this.currentString.data.content;
        console.log(this.plugin);
    },
    err => {
       // Handle the error here
       // like displaying toast using the error message received from server
       this.plugin = err;
    }
);
</code>```

Body:
I am trying to handle 422 error handling on my HTTP request. But somehow the error block doesn't run in the service using catchError operator. If there is no error the code is just working fine. I want to display error message on my page. But angular is only throwing error in console and not running the error block.
Here is my http error response:

And here is the error I am getting only in console.

I want to display error message on my page. Here is my HTTP request.

 renderPlugin(id): Observable<any> {
 return this.http
      .get(`${environment.kbUrl}/${id}?_as_json=1&_nbp=1`, {
        responseType: "text",
        observe: "response"
      })
      .pipe(
        catchError((res: HttpErrorResponse) => {
          console.log(JSON.stringify(res));
          this.toastr.error("error", JSON.stringify(res));
          return throwError(JSON.stringify(res));
        })
      );
  }

And here is my method to subscribe to the it.

this.pluginsService.renderPlugin(this.currentId).subscribe(res =>{
    this.currentString = res.body;
    this.plugin = this.currentString.data.content;
    console.log(this.plugin);
      },
      err =>{
        this.plugin = err;
      });

Body:
Try removing this code from your Http call:

  .pipe(
    catchError((res: HttpErrorResponse) => {
      console.log(JSON.stringify(res));
      this.toastr.error("error", JSON.stringify(res));
      return throwError(JSON.stringify(res));
    })
  )

And handle your error inside the error block of your subscribe method.

this.pluginsService.renderPlugin(this.currentId).subscribe(
    res => {
        this.currentString = res.body;
        this.plugin = this.currentString.data.content;
        console.log(this.plugin);
    },
    err => {
       // Handle the error here
       // like displaying toast using the error message received from server
       this.plugin = err;
    }
);


问:
Remove footer tags from CKEditor
I am using CKEditor in my website and here I want to remove footer tags. How can I do it? I am using CKEditor to add some useful content. It is working fine but I don’t want to show the footer tags. It shows p and div tags. How can I remove footer p and div tags from CKEditor?

答:
It depends what the footer is displaying.

This old thread suggests:

Add this code in your config.js file :

```<code>config.removePlugins = 'elementspath';
config.resize_enabled = false;
</code>```

This is part of the basic configuration of CKEditor

If you, however, want to disable some functionality that comes from a CKEditor plugin and is still in your build, you can use the removePlugins setting to prevent the plugin from loading.

```<code>// Remove one plugin.
config.removePlugins = 'elementspath';

// Remove multiple plugins.
config.removePlugins = 'elementspath,save,font';
</code>```

Title: Remove footer tags from CKEditor

Body:
It depends what the footer is displaying.

This old thread suggests:

Add this code in your config.js file :

config.removePlugins = 'elementspath';
config.resize_enabled = false;

This is part of the basic configuration of CKEditor

If you, however, want to disable some functionality that comes from a CKEditor plugin and is still in your build, you can use the removePlugins setting to prevent the plugin from loading.

// Remove one plugin.
config.removePlugins = 'elementspath';

// Remove multiple plugins.
config.removePlugins = 'elementspath,save,font';


问:
HTML website stops working as expected after migrating servers
I'm a web developer for years and I understand a lot about websites and development. But this issue is far from my understanding, I had never encountered it before as it looks mystical for me.

I have HTML website on main server and domain, it's working fine there, all files are loaded and design looks as it should.
Now, I have moved the same website, all the same files to a new server and domain, and the website just broke without touching anything. It's working, but design doesn't look like it should, Javascript is throwing errors in console, design structure is lost. All files needed are loaded, I can see in the Network tab of Chrome Developer Tools but website design structure is lost and JS scripts are not working. Now this is the fun part. If I transfer the same website from new server to the main server, the website looks good once again. I'm stretching my head all day and can't find any issue.
I've also tried to run the same website locally on WAMP or even just from desktop as it's only HTML, and the website is broke as it's in the new server.

Main website URL: [removed as issue is fixed]
New server's website URL: [removed as issue is fixed]

Any ideas? Anyone had encountered this before?

EDIT:

Issue is found and fixed. It was encoding issue. Encoding of the files were changed while transferring files from one server to another.

答:
There are three errors on the "new" site. Two are parse errors from bootstrap.min.js and prettyphoto.js. These files are different between the old and the new site. It looks like it might just be an issue with newline characters, possibly an encoding problem while transferring the files.

The third error is from main.js because $.affix is not a function. The affix plugin is added by bootstrap, which probably isn't working because of the parse error.

I'm guessing if you re-copy bootstrap.min.js and prettyphoto.js from the old to the new site, it will resolve the issue.

Looking a bit further at bootstrap.min.js and prettyphoto.js, there are some nonsense characters in both files. That lends evidence to the idea that it's an encoding issue, probably introduced while copying the files from one place to another.

prettyphoto.js

be/"),movie_id=mov��\��\��Z��Y��\��\��\&")>0&&(movie_id=

bootstrap.min.js

).each(function(){YaYaКV�bhYa Ya� Yaunction(){var d=a

@Herohtar pointed out that the encoding on the two versions of the files is different: windows-1257 on the old site and GBK on the new site. It's possible that the files were edited (e.g. in an IDE or text editor) and saved, and the default encoding in the editor was different than the original, and didn't re-encode (or parse the original encoding) correctly.


问:
image on apache or weblogic interview question
I was asked an interview question where how can I tell if an image is coming from apache or weblogic. How can I determine if it is not a part of the war file?

Thanks

答:
Usually there is a specific rule within the web server for static images (URI based) so just by looking at the full URL of the image, you should be able to tell if it's from Apache or WebLogic.

If the Apache / WebLogic proxy-plugin configuration seems overly complex, you could just try loading the image and tail the access logs on the WebLogic application server to see if the image is being served from it.

If that doesn't work, you can enabled the debug logs for the WebLogic proxy-plugin on apache and monitor the details of all outgoing connections.

ContentLicense: CC BY-SA 3.0


问:
Where to store client data in angular which is later used in REST-API for getting information
I have an angular application, Whenever a user logs in I get all his data along with a jsonwebtoken from server through REST-API request and store it in localstorage.

After that I use the same user data such as email, account_status, id etc  in other REST-API calls for getting more information. This is obviously not the correct way to do, The user can modify his localstorage data and get other user's information easily.

I am using jsonwebtoken for authentication, verifying the token in authgaurd service through REST-API call.

Can anybody suggest the correct way to store the information with brief description.
Can I use Cookies for the issue?

答: If your application logic is complex, you can consider adopting some form of state management, based on the Flux architecture. The most common and well established state management solution is NgRx Store, and it is very similar to Redux, which may be familiar with you if you have worked with React.js.</p>


问:
how to implement One signal in Nativescript for iOS
I'm trying to implement One Signal in Nativescript. I use nativescript-onesignal plugin for that. It works on android but doesn't work on iOS. I give these errors in sidekick console:

```<code>ERROR: Encountered error during push registration with OneSignal: Error Domain=OneSignal Error Code=403 "(null)" UserInfo={returned=Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}}
ERROR: Encountered error during email registration with OneSignal: (null)
</code>```

as long as there are these errors, One Signal can't detect my device as a subscriber.
has anybody an idea that how to implement that for iOS?
I don't know how I should solve that. any idea?

This is my main.ts file:

```<code>// this import should be first in order to load some required settings (like globals and reflect-metadata)
import { platformNativeScriptDynamic } from "nativescript-angular/platform";

import { AppModule } from "./app/app.module";

import * as application from "tns-core-modules/application";
const TnsOneSignal = require("nativescript-onesignal").TnsOneSignal;
// A traditional NativeScript application starts by initializing global objects, setting up global CSS rules, creating, and navigating to the main page.
// Angular applications need to take care of their own initialization: modules, components, directives, routes, DI providers.
// A NativeScript Angular app needs to make both paradigms work together, so we provide a wrapper platform object, platformNativeScriptDynamic,
// that sets up a NativeScript application and can bootstrap the Angular framework.

console.log("main starts");

if (application.ios) {
    class MyDelegate extends UIResponder implements UIApplicationDelegate {

        public static ObjCProtocols = [UIApplicationDelegate];

        public applicationDidFinishLaunchingWithOptions(app: UIApplication, launchOptions: NSDictionary<any, any>): boolean {

            try {

                console.log("TnsOneSignal", TnsOneSignal);
                // init to recieve push notification
                TnsOneSignal.initWithLaunchOptionsAppId(launchOptions, "b2fdda95*********");

                // I have not yet implemented the part of receiving notifications in ios, when I have it I will publish it

            } catch (error) {
                console.log("TnsOneSignal error", error);
            }

            return true;
        }

    }
    application.ios.delegate = MyDelegate;
}

if (application.android) {
    application.on(application.launchEvent, function(args: application.ApplicationEventData) {

        try {

            console.log("TnsOneSignal", TnsOneSignal);
            TnsOneSignal.ini(application.android.context).init()

        } catch (error) {
            console.error("error", error)
        }

    });
}

platformNativeScriptDynamic().bootstrapModule(AppModule);
</code>```

答: After some days, Finally, I found what the problem was! it was fixed by using a VPN.</p>

Body:
I'm trying to implement One Signal in Nativescript. I use nativescript-onesignal plugin for that. It works on android but doesn't work on iOS. I give these errors in sidekick console:

ERROR: Encountered error during push registration with OneSignal: Error Domain=OneSignal Error Code=403 "(null)" UserInfo={returned=Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}}
ERROR: Encountered error during email registration with OneSignal: (null)

as long as there are these errors, One Signal can't detect my device as a subscriber.
has anybody an idea that how to implement that for iOS?
I don't know how I should solve that. any idea?

This is my main.ts file:

// this import should be first in order to load some required settings (like globals and reflect-metadata)
import { platformNativeScriptDynamic } from "nativescript-angular/platform";

import { AppModule } from "./app/app.module";

import * as application from "tns-core-modules/application";
const TnsOneSignal = require("nativescript-onesignal").TnsOneSignal;
// A traditional NativeScript application starts by initializing global objects, setting up global CSS rules, creating, and navigating to the main page.
// Angular applications need to take care of their own initialization: modules, components, directives, routes, DI providers.
// A NativeScript Angular app needs to make both paradigms work together, so we provide a wrapper platform object, platformNativeScriptDynamic,
// that sets up a NativeScript application and can bootstrap the Angular framework.

console.log("main starts");

if (application.ios) {
    class MyDelegate extends UIResponder implements UIApplicationDelegate {

        public static ObjCProtocols = [UIApplicationDelegate];

        public applicationDidFinishLaunchingWithOptions(app: UIApplication, launchOptions: NSDictionary<any, any>): boolean {

            try {

                console.log("TnsOneSignal", TnsOneSignal);
                // init to recieve push notification
                TnsOneSignal.initWithLaunchOptionsAppId(launchOptions, "b2fdda95*********");

                // I have not yet implemented the part of receiving notifications in ios, when I have it I will publish it

            } catch (error) {
                console.log("TnsOneSignal error", error);
            }

            return true;
        }

    }
    application.ios.delegate = MyDelegate;
}

if (application.android) {
    application.on(application.launchEvent, function(args: application.ApplicationEventData) {

        try {

            console.log("TnsOneSignal", TnsOneSignal);
            TnsOneSignal.ini(application.android.context).init()

        } catch (error) {
            console.error("error", error)
        }

    });
}

platformNativeScriptDynamic().bootstrapModule(AppModule);


问:
Error "library not found for" after putting application in AdMob
I am getting an error after I put my application in an AdMob. The app was working until today. The error is the following:

```<code>ld: library not found for -lGoogleAdMobAds
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

How can I fix this? Thank you.

答:
In the case of ld: library not found for -{LIBRARY_NAME} happened because the library file(s) is not existing.

Check the library path on your application targets’ “Build Phases”
  Library Search Paths tab.

The library file(s) path must be according to the real path for example if your file(s) in the root of the project you must set the path like $(PROJECT_DIR)

Body:
I am getting an error after I put my application in an AdMob. The app was working until today. The error is the following:

ld: library not found for -lGoogleAdMobAds
clang: error: linker command failed with exit code 1 (use -v to see invocation)

How can I fix this? Thank you.


问:
How do I generate a random num::BigUint?
I need a random 256-bit unsigned  number. I discovered that there is the RandBigInt trait with the method gen_biguint(), but I am having a tough time finding an implementation for it.

I tried doing this some time ago for BigInt. The crates have been updated since. This is how I am using it to get a BigUint now.

```<code>extern crate num;
extern crate rand;

use num::bigint::{BigInt, BigUint, RandBigInt};

fn main() {
    let mut rng = rand::thread_rng();
    let mut n: BigUint = BigUint::default();
    loop {
        let bigUint: Option<BigUint> = rng.gen_bigint(256).to_biguint();
        match bigUint {
            Some(num) => {
                n = num.clone();
                println!("Found the 1st BigUint - {}", num);
                break;
            }
            _ => {}
        }
    }
}
</code>```

Contents from my Cargo.toml

num = "0.1.42"
rand = "0.4.2"
```

I am sure there must be some straight-forward way of achieving this.

答:
Shepmaster's answer was raising a trait bound error in more recent versions of rand. Got this to work:

Cargo.toml

```<code>edition = "2018"

[dependencies]
rand = "0.6"
num-bigint = { version = "0.2.2", features = ["rand"] }
</code>```

main.rs

use num_bigint::{BigUint, RandBigInt};

fn main() {
    let mut rng = rand::thread_rng();
    let unsigned: BigUint = rng.gen_biguint(256);
    println!("{}", unsigned);
}
```

Body:
I need a random 256-bit unsigned  number. I discovered that there is the RandBigInt trait with the method gen_biguint(), but I am having a tough time finding an implementation for it.

I tried doing this some time ago for BigInt. The crates have been updated since. This is how I am using it to get a BigUint now.

extern crate num;
extern crate rand;

use num::bigint::{BigInt, BigUint, RandBigInt};

fn main() {
    let mut rng = rand::thread_rng();
    let mut n: BigUint = BigUint::default();
    loop {
        let bigUint: Option<BigUint> = rng.gen_bigint(256).to_biguint();
        match bigUint {
            Some(num) => {
                n = num.clone();
                println!("Found the 1st BigUint - {}", num);
                break;
            }
            _ => {}
        }
    }
}

Contents from my Cargo.toml

num = "0.1.42"
rand = "0.4.2"

I am sure there must be some straight-forward way of achieving this.

Body:
Shepmaster's answer was raising a trait bound error in more recent versions of rand. Got this to work:

Cargo.toml

edition = "2018"

[dependencies]
rand = "0.6"
num-bigint = { version = "0.2.2", features = ["rand"] }

main.rs

use num_bigint::{BigUint, RandBigInt};

fn main() {
    let mut rng = rand::thread_rng();
    let unsigned: BigUint = rng.gen_biguint(256);
    println!("{}", unsigned);
}


问:
How do I test did a message box shows up or not in unit testing?
I wanted to test, will the message box show up when my code request it. But I am not so sure what to assert or am I even doing the right thing.

```<code>public void btnSave_Click(object sender, EventArgs e)
        {
            if(txtFirstName.Text.Trim() != "" && txtLastName.Text.Trim() != "" && txtContact.Text.Trim() != "")
            {
                Regex reg = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"); // Only accepting proper email
                Match match = reg.Match(txtEmail.Text.Trim());
                if (match.Success)
                { using (SqlConnection sqlCon = new SqlConnection(connectionString)) // Connecting info to database
                    {
                        sqlCon.Open();
                        SqlCommand sqlCmd = new SqlCommand("ContactAddorEdit", sqlCon);
                        sqlCmd.CommandType = CommandType.StoredProcedure;
                        sqlCmd.Parameters.AddWithValue("@PhoneBookID", PhoneBookID); //connecting each value to database
                        sqlCmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text.Trim());
                        sqlCmd.Parameters.AddWithValue("@LastName", txtLastName.Text.Trim());
                        sqlCmd.Parameters.AddWithValue("@Contact", txtContact.Text.Trim());
                        sqlCmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
                        sqlCmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim());
                        sqlCmd.ExecuteNonQuery(); // Executing the query in database
                        MessageBox.Show("Submitted successfully"); // Showing message when success
                        Clear(); // Clearing the form
                        GridFill();// Refreshing the table
                    }
                }
                else
                {
                    MessageBox.Show(" Please enter a valid Email"); // Showing message when email is not valid
                }
            }
            else
            {
                MessageBox.Show("Please fill Mandatory fields"); // If no input this message will show
            }

        }
</code>```

So if the text box got a empty string there will be an message box pops up and say "Please fill Mandatory fields"

and here is the test that I am trying write

```<code>        [TestMethod]
        public void TestMethod1()
        {
            Form1 form1 = new Form1();
            form1.txtFirstName.Text = "";
            Assert.IsTrue(MessageBox.Show("Please fill Mandatory fields") ;
        }
</code>```

What kind of assert should and use and how do I write it? Can I test it like this? Thank you

答:
You don't use unit tests to test the user interface. They are for testing the logic. A unit test can't click the buttons (who or what will click OK when your message box pops up so the test can finish?) there are UI testing frameworks that can.

Think about what you are trying to test here. Test1 is testing that the form will correctly check that the mandatory fields are filled in. Create a method for that logic, and unit test it:

```<code>public bool MandatoryFieldsArePopulated()
{
     return txtFirstName.Text.Trim() != ""
         && txtLastName.Text.Trim() != ""
         && txtContact.Text.Trim() != "";
}
</code>```

this can easily be tested with unit tests. Then the first line of the btnSave_Click method will be

```<code>if (MandatoryFieldsArePopulated())
</code>```

Structuring your code like this not only enables you to test the logic units individually, it also makes the code clearer and easier to read.

Body:
I wanted to test, will the message box show up when my code request it. But I am not so sure what to assert or am I even doing the right thing.

public void btnSave_Click(object sender, EventArgs e)
        {
            if(txtFirstName.Text.Trim() != "" && txtLastName.Text.Trim() != "" && txtContact.Text.Trim() != "")
            {
                Regex reg = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"); // Only accepting proper email
                Match match = reg.Match(txtEmail.Text.Trim());
                if (match.Success)
                { using (SqlConnection sqlCon = new SqlConnection(connectionString)) // Connecting info to database
                    {
                        sqlCon.Open();
                        SqlCommand sqlCmd = new SqlCommand("ContactAddorEdit", sqlCon);
                        sqlCmd.CommandType = CommandType.StoredProcedure;
                        sqlCmd.Parameters.AddWithValue("@PhoneBookID", PhoneBookID); //connecting each value to database
                        sqlCmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text.Trim());
                        sqlCmd.Parameters.AddWithValue("@LastName", txtLastName.Text.Trim());
                        sqlCmd.Parameters.AddWithValue("@Contact", txtContact.Text.Trim());
                        sqlCmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
                        sqlCmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim());
                        sqlCmd.ExecuteNonQuery(); // Executing the query in database
                        MessageBox.Show("Submitted successfully"); // Showing message when success
                        Clear(); // Clearing the form
                        GridFill();// Refreshing the table
                    }
                }
                else
                {
                    MessageBox.Show(" Please enter a valid Email"); // Showing message when email is not valid
                }
            }
            else
            {
                MessageBox.Show("Please fill Mandatory fields"); // If no input this message will show
            }

        }

So if the text box got a empty string there will be an message box pops up and say "Please fill Mandatory fields"

and here is the test that I am trying write

        [TestMethod]
        public void TestMethod1()
        {
            Form1 form1 = new Form1();
            form1.txtFirstName.Text = "";
            Assert.IsTrue(MessageBox.Show("Please fill Mandatory fields") ;
        }

What kind of assert should and use and how do I write it? Can I test it like this? Thank you

Body:
You don't use unit tests to test the user interface. They are for testing the logic. A unit test can't click the buttons (who or what will click OK when your message box pops up so the test can finish?) there are UI testing frameworks that can.

Think about what you are trying to test here. Test1 is testing that the form will correctly check that the mandatory fields are filled in. Create a method for that logic, and unit test it:

public bool MandatoryFieldsArePopulated()
{
     return txtFirstName.Text.Trim() != ""
         && txtLastName.Text.Trim() != ""
         && txtContact.Text.Trim() != "";
}

this can easily be tested with unit tests. Then the first line of the btnSave_Click method will be

if (MandatoryFieldsArePopulated())

Structuring your code like this not only enables you to test the logic units individually, it also makes the code clearer and easier to read.


问:
React prop disappears
I'm obviously not understanding something here when it comes to react/react router 4. I'm trying to check if a user is logged in or out to control the navbar user status routes. I can't seem to access the prop, it just disappears. Can someone point out what I'm not understanding? isUserLoggedInServerCheck returns a value at Server, it then returns a value at AppServer, however, at CandidateLanding it returns undefined.

Path: Server

```<code>onPageLoad(sink => {
  let isUserLoggedInServerCheck = false;
  if (sink.request.cookies.sssr) {
    isUserLoggedInServerCheck = true;
  }

  sink.renderIntoElementById(
    'react-target',
    renderToString(
      <AppServer
        location={sink.request.url}
        isUserLoggedInServerCheck={isUserLoggedInServerCheck}
      />
    )
  );
});
</code>```

Path: AppServer

```<code>const AppServer = props => {
  const context = {};
  const { location, isUserLoggedInServerCheck } = props;

  return (
    <StaticRouter context={context} location={location} isUserLoggedInServerCheck={isUserLoggedInServerCheck}>
      <div className="application">
        <Switch>
          <Route path="/" exact component={CandidateLanding} />
        </Switch>
      </div>
    </StaticRouter>
  );
};
</code>```

Path: CandidateLanding

```<code>function CandidateLanding(props) {
  const { location, isUserLoggedInServerCheck } = props;

  return (
    <div>
      <Navbar location={location.path} isUserLoggedInServerCheck={isUserLoggedInServerCheck} />
    </div>
  );
}

const CandidateLandingContainer = withTracker(props => {
  const { isUserLoggedInServerCheck } = props;
  if (Meteor.isServer) {
    return {
      isUserLoggedInServerCheck
    };
  }

  if (Meteor.isClient) {
    return {
      isUserLoggedInServerCheck
    };
  }
})(CandidateLanding);
</code>```

答:
You are passing your props to StaticRouter and they never make it to the CandidateLanding component. The best way to do this would be to use the render function for route

```<code><Route path="/" exact render={ (props) => <CandidateLanding {...props} anotherProp={ anotherVariable } />} />
</code>```

Make sure you remove the unnecessary props from Static Router as well.
Source

Title: React prop disappears

Body:
I'm obviously not understanding something here when it comes to react/react router 4. I'm trying to check if a user is logged in or out to control the navbar user status routes. I can't seem to access the prop, it just disappears. Can someone point out what I'm not understanding? isUserLoggedInServerCheck returns a value at Server, it then returns a value at AppServer, however, at CandidateLanding it returns undefined.

Path: Server

onPageLoad(sink => {
  let isUserLoggedInServerCheck = false;
  if (sink.request.cookies.sssr) {
    isUserLoggedInServerCheck = true;
  }

  sink.renderIntoElementById(
    'react-target',
    renderToString(
      <AppServer
        location={sink.request.url}
        isUserLoggedInServerCheck={isUserLoggedInServerCheck}
      />
    )
  );
});

Path: AppServer

const AppServer = props => {
  const context = {};
  const { location, isUserLoggedInServerCheck } = props;

  return (
    <StaticRouter context={context} location={location} isUserLoggedInServerCheck={isUserLoggedInServerCheck}>

        <Switch>
          <Route path="/" exact component={CandidateLanding} />
        </Switch>

    </StaticRouter>
  );
};

Path: CandidateLanding

function CandidateLanding(props) {
  const { location, isUserLoggedInServerCheck } = props;

  return (

      <Navbar location={location.path} isUserLoggedInServerCheck={isUserLoggedInServerCheck} />

  );
}

const CandidateLandingContainer = withTracker(props => {
  const { isUserLoggedInServerCheck } = props;
  if (Meteor.isServer) {
    return {
      isUserLoggedInServerCheck
    };
  }

  if (Meteor.isClient) {
    return {
      isUserLoggedInServerCheck
    };
  }
})(CandidateLanding);

Body:
You are passing your props to StaticRouter and they never make it to the CandidateLanding component. The best way to do this would be to use the render function for route

<Route path="/" exact render={ (props) => <CandidateLanding {...props} anotherProp={ anotherVariable } />} />

Make sure you remove the unnecessary props from Static Router as well.
Source


问:
Set Background color for a selected item in a Select option (multiple)
I'm trying to change the background color of the selected items in a listbox (select multiple options).

I tried with css... I tried with  JavaScript... and with jquery... I really don't know what happen!! But I'm unable to find the answer :_(.

I read at least 10 questions in this forum.. and I tried all the proposed solutions but I only can change the background of the complete list... not the selected items. The only way I found is to use an unordered list with clickable list items instead if my select - option ... but I'm working with a form, and I want to send to the server the selected items in the traditional way.

答:
This will change the background color of the selected option

```<code>$('select').change(function() {
    $('option').css('background', 'none');
    $('option:selected').css('backgroundColor', 'red');
}).change();
</code>```

Check working example at http://jsfiddle.net/TxbVt/1/

Body:
This will change the background color of the selected option

$('select').change(function() {
    $('option').css('background', 'none');
    $('option:selected').css('backgroundColor', 'red');
}).change();

Check working example at http://jsfiddle.net/TxbVt/1/


问:
How to dynamically set an image or use default
I am mapping through objects and would like to dynamically add the image source, but if there is not an image, id like to load the default image. Ideally this take as little computational power as can be because there are lots of images that will change often..

I already have the dynamic image src setup, but i dont have the loop to check if it exists. Just wondering what the fastest way to do this is.

```<code>...
render() {
    const images = require.context("../../../../../public/images", true);
...

return {
{this.props.items.map...

<img src={images(`./${item.item}`)} />

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

答:
You can create a custom image component to handle this:

```<code>import React from 'react';

class Img extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      src: this.props.src,
      error: false,
    };

   this.onError = this.onError.bind(this);
  }

  onError = () => {
    if (!this.state.error) {
      this.setState({
        src: this.props.defaultSrc,
        error: true,
      });
    }
  }

  render() {
    const { src } = this.state;

    return (
      <img
        src={src}
        onError={this.onError}
      />
    );
  }
}

export default Img;
</code>```

And then you can set like this:

```<code><Img src='if-this-image-not-exists-doesnt-matter.png' defaultSrc='https://picsum.photos/id/237/200/300' />
</code>```

Body:
I am mapping through objects and would like to dynamically add the image source, but if there is not an image, id like to load the default image. Ideally this take as little computational power as can be because there are lots of images that will change often..

I already have the dynamic image src setup, but i dont have the loop to check if it exists. Just wondering what the fastest way to do this is.

...
render() {
    const images = require.context("../../../../../public/images", true);
...

return {
{this.props.items.map...

<img src={images(`./${item.item}`)} />

....)}

Body:
You can create a custom image component to handle this:

import React from 'react';

class Img extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      src: this.props.src,
      error: false,
    };

   this.onError = this.onError.bind(this);
  }

  onError = () => {
    if (!this.state.error) {
      this.setState({
        src: this.props.defaultSrc,
        error: true,
      });
    }
  }

  render() {
    const { src } = this.state;

    return (
      <img
        src={src}
        onError={this.onError}
      />
    );
  }
}

export default Img;

And then you can set like this:

<Img src='if-this-image-not-exists-doesnt-matter.png' defaultSrc='https://picsum.photos/id/237/200/300' />


问:
How to convert a hex float to a float in C/C++ using _mm_extract_ps SSE GCC instrinc function
I'm writing a SSE code to 2-D convolution but SSE documentation is very sparse.

I'm calculating dot-product with _mm_dp_ps and using _mm_extract_ps to get the dot-product result but _mm_extract_ps returns a hex float and I can't figure out how to convert this hex float to a regular float.

I could use __builtin_ia32_vec_ext_v4sf that returns a float but I wanna keep compatibility with others compilers.

```<code>_mm_extract_ps (__m128 __X, const int __N)
{
  union { int i; float f; } __tmp;
  __tmp.f = __builtin_ia32_vec_ext_v4sf ((__v4sf)__X, __N);
  return __tmp.i;
}
</code>```

What point I'm missing?

A little help will be appreciated, thanks.

OpenSUSE 11.2, GCC 4.4.1, C++

Compiler options: -fopenmp -Wall -O3 -msse4.1 -march=core2

Linker options: -lgomp -Wall -O3 -msse4.1 -march=core2

答:
And just to exemplify all that has been mentioned so far:

main.c

```<code>#include <assert.h>

#include <x86intrin.h>

int main(void) {

    /* 32-bit. */
    {
        __m128 x = _mm_set_ps(1.5f, 2.5f, 3.5f, 4.5f);

        /* _MM_EXTRACT_FLOAT */
        float f;
        _MM_EXTRACT_FLOAT(f, x, 3);
        assert(f == 1.5f);
        _MM_EXTRACT_FLOAT(f, x, 2);
        assert(f == 2.5f);
        _MM_EXTRACT_FLOAT(f, x, 1);
        assert(f == 3.5f);
        _MM_EXTRACT_FLOAT(f, x, 0);
        assert(f == 4.5f);

        /* _mm_cvtss_f32 + _mm_shuffle_ps */
        assert(_mm_cvtss_f32(x) == 4.5f);
        assert(_mm_cvtss_f32(_mm_shuffle_ps(x, x, 1)) == 3.5f);
        assert(_mm_cvtss_f32(_mm_shuffle_ps(x, x, 2)) == 2.5f);
        assert(_mm_cvtss_f32(_mm_shuffle_ps(x, x, 3)) == 1.5f);
    }

    /* 64-bit. */
    {
        __m128d x = _mm_set_pd(1.5, 2.5);
        /* _mm_cvtsd_f64 + _mm_unpackhi_pd */
        assert(_mm_cvtsd_f64(x) == 2.5);
        assert(_mm_cvtsd_f64(_mm_unpackhi_pd(x, x)) == 1.5);
    }
}
</code>```

GitHub upstream.

Compile and run:

```<code>gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
./main.out
</code>```

Doubles mentioned at: _mm_cvtsd_f64 analogon for higher order floating point

Tested on Ubuntu 19.04 amd64.

Body:
I'm writing a SSE code to 2-D convolution but SSE documentation is very sparse.

I'm calculating dot-product with _mm_dp_ps and using _mm_extract_ps to get the dot-product result but _mm_extract_ps returns a hex float and I can't figure out how to convert this hex float to a regular float.

I could use __builtin_ia32_vec_ext_v4sf that returns a float but I wanna keep compatibility with others compilers.

_mm_extract_ps (__m128 __X, const int __N)
{
  union { int i; float f; } __tmp;
  __tmp.f = __builtin_ia32_vec_ext_v4sf ((__v4sf)__X, __N);
  return __tmp.i;
}

What point I'm missing?

A little help will be appreciated, thanks.

OpenSUSE 11.2, GCC 4.4.1, C++

Compiler options: -fopenmp -Wall -O3 -msse4.1 -march=core2

Linker options: -lgomp -Wall -O3 -msse4.1 -march=core2

Body:
And just to exemplify all that has been mentioned so far:

main.c

#include <assert.h>

#include <x86intrin.h>

int main(void) {

    /* 32-bit. */
    {
        __m128 x = _mm_set_ps(1.5f, 2.5f, 3.5f, 4.5f);

        /* _MM_EXTRACT_FLOAT */
        float f;
        _MM_EXTRACT_FLOAT(f, x, 3);
        assert(f == 1.5f);
        _MM_EXTRACT_FLOAT(f, x, 2);
        assert(f == 2.5f);
        _MM_EXTRACT_FLOAT(f, x, 1);
        assert(f == 3.5f);
        _MM_EXTRACT_FLOAT(f, x, 0);
        assert(f == 4.5f);

        /* _mm_cvtss_f32 + _mm_shuffle_ps */
        assert(_mm_cvtss_f32(x) == 4.5f);
        assert(_mm_cvtss_f32(_mm_shuffle_ps(x, x, 1)) == 3.5f);
        assert(_mm_cvtss_f32(_mm_shuffle_ps(x, x, 2)) == 2.5f);
        assert(_mm_cvtss_f32(_mm_shuffle_ps(x, x, 3)) == 1.5f);
    }

    /* 64-bit. */
    {
        __m128d x = _mm_set_pd(1.5, 2.5);
        /* _mm_cvtsd_f64 + _mm_unpackhi_pd */
        assert(_mm_cvtsd_f64(x) == 2.5);
        assert(_mm_cvtsd_f64(_mm_unpackhi_pd(x, x)) == 1.5);
    }
}

GitHub upstream.

Compile and run:

gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
./main.out

Doubles mentioned at: _mm_cvtsd_f64 analogon for higher order floating point

Tested on Ubuntu 19.04 amd64.


问:
How to use JCS with Spring boot(Rest api)
I am new to Spring boot caching, as per my requirement i want to use JCS with spring boot(rest api). I have searched over the google but, haven't got much information about it.

There is info available with java class. Does any one knows how to use it or any related tutorial or information.

This might be the opinion based question. But it is much needed.

```<code>  public static void main(String[] args) {
//   Initialize the JCS object and get an instance of the default cache region
try {
    JCS cache = JCS.getInstance("default");

String key = "key0";
String value = "value0";

cache.put(key, value);
cache.put("vasu","dev");

} catch (CacheException e) {
    e.printStackTrace();
}
</code>```

}

答:
As far as caching with spring boot is concerned, spring supports the following cache providers, as it has been mentioned in the following link.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-caching.html

To quote, It says

If you have not defined a bean of type CacheManager or a CacheResolver
  named cacheResolver (see CachingConfigurer), Spring Boot tries to
  detect the following providers (in the indicated order):

Generic

JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, and others)

EhCache 2.x

Hazelcast

Infinispan

Couchbase

Redis

Caffeine

Simple

I will suggest to use Ehcache, you can check more details on Ehcache with Spring framework in the below link.
https://www.baeldung.com/spring-cache-tutorial

If you are only interested about JCS, then refer below the link to have an understanding.

https://codyburleson.com/quick-and-simple-caching-with-apache-commons-jcs/

In case pf Spring boot, I will suggest to create class and wrap JCS inside that class so that you can wire in any class so that you can abstract away the JCS implementation details. I provide below outline.

@Autowired CacheUpdater cacheUpdate;

in the method, you can write like this,

public void someMethod(... params) {
    cacheUpdater.update(key,value)
}

It is not necessary that, you have to have a method called update(), you can create any method and it should internally call JCS to put the key and value in cache.

Body:
I am new to Spring boot caching, as per my requirement i want to use JCS with spring boot(rest api). I have searched over the google but, haven't got much information about it.

There is info available with java class. Does any one knows how to use it or any related tutorial or information.

This might be the opinion based question. But it is much needed.

  public static void main(String[] args) {
//   Initialize the JCS object and get an instance of the default cache region
try {
    JCS cache = JCS.getInstance("default");

String key = "key0";
String value = "value0";

cache.put(key, value);
cache.put("vasu","dev");

} catch (CacheException e) {
    e.printStackTrace();
}

}


问:
How do I package golang test helper code?
I have some test helper code in my golang library that I want to use when testing in various subpackages. However, I've hit a snag:

```<code>outer
|
+- test_helpers_test.go
|
+- inner
   |
   +- something.go
   +- something_test.go
</code>```

To use the code in test_helpers_test.go, I have to import the outer package. But when I import the outer package from something_test.go, it complains "import cycle not allowed in test"

So I tried making a package for the shared test helpers:

```<code>outer
|
+- test
|  |
|  +- test_helpers_test.go
|
+- inner
   |
   +- something.go
   +- something_test.go
</code>```

And now it complains "no non-test Go files in /home/karl/Projects/outer/test"

I don't want to call it test_helpers.go because it's part of my testing code, not my library code. I don't want to ship that code in the library.

How do I solve this?

Update: I can work around the issue by creating a dummy.go file in the test directory, but now there's a new problem: Importing a package DOESN'T import its test code! So now I get: ./something_test.go:12:2: undefined: test.AssertDoesPanic

答:
Following go issue 8279, I have seen dummy files added, as in tommie/acme-cli commit 479f8c7

```<code>outer/outer.go

// +build ignore+
package outer
</code>```

See if that could help here, as a workaround.

As commented above, using a test helper code in an internal package (from Go 1.4+) is another option, since no client from this project would be able to access said helper. See design document.

You can see it used in a typical Go project layout.

Body:
I have some test helper code in my golang library that I want to use when testing in various subpackages. However, I've hit a snag:

outer
|
+- test_helpers_test.go
|
+- inner
   |
   +- something.go
   +- something_test.go

To use the code in test_helpers_test.go, I have to import the outer package. But when I import the outer package from something_test.go, it complains "import cycle not allowed in test"

So I tried making a package for the shared test helpers:

outer
|
+- test
|  |
|  +- test_helpers_test.go
|
+- inner
   |
   +- something.go
   +- something_test.go

And now it complains "no non-test Go files in /home/karl/Projects/outer/test"

I don't want to call it test_helpers.go because it's part of my testing code, not my library code. I don't want to ship that code in the library.

How do I solve this?

Update: I can work around the issue by creating a dummy.go file in the test directory, but now there's a new problem: Importing a package DOESN'T import its test code! So now I get: ./something_test.go:12:2: undefined: test.AssertDoesPanic

Body:
Following go issue 8279, I have seen dummy files added, as in tommie/acme-cli commit 479f8c7

outer/outer.go

// +build ignore+
package outer

See if that could help here, as a workaround.

As commented above, using a test helper code in an internal package (from Go 1.4+) is another option, since no client from this project would be able to access said helper. See design document.

You can see it used in a typical Go project layout.


问:
Manage Filter ID Gmail
I am trying to create a filter for every people's email in a group. However, sometimes the a person's email can changes like adding new email or change to another mail email. That means I have to update the filter accordingly. I tried to create filter with ID that with the person's name. So I can retrieve that filter to modify it. However, it seems that the Gmail filter's ID are created automatically.

```<code>var filter = Gmail.newFilter()
var email = 'something@some.com'
filter.id = 'person'
filter.criteria = Gmail.newFilterCriteria()
filter.criteria.query = email
filter.action = Gmail.newFilterAction()
filter.action.addLabelIds = ['Label_1']
Gmail.Users.Settings.Filters.create(filter, 'me')
</code>```

When I get back the filter, it will say that it cannot be found

var filter2 = Gmail.Users.Settings.Filters.get('me', 'person')

This will return Not Found error even I can see the filter in setting in my Gmail. The actually ID for the filter I created above is ANe1Bmgel8OKlEXD-uArX77ISk35Lph1MbWWjA.

My question is what's the good way to manager filters through changes, keep them updated?

答:
Instead of:

```<code>Gmail.Users.Settings.Filters.create(filter, 'me');
</code>```

Try:

```<code>var filterProps = Gmail.Users.Settings.Filters.create(filter, 'me');
var filterId = filterProps.id;
</code>```

Per the API documentation for creating a filter,

If successful, this method returns a Users.settings.filters resource in the response body.

The code above worked for me in a similar situation. To keep track of the filterId outside of Gmail, you could then tie the person's name to the id via the property service:

```<code>PropertiesService.getScriptProperties().setProperty(nameVar, filterId);
</code>```

and then retrieve it like so:

```<code>PropertiesService.getScriptProperties().getProperty(nameVar);
</code>```

Title: Manage Filter ID Gmail

Body:
I am trying to create a filter for every people's email in a group. However, sometimes the a person's email can changes like adding new email or change to another mail email. That means I have to update the filter accordingly. I tried to create filter with ID that with the person's name. So I can retrieve that filter to modify it. However, it seems that the Gmail filter's ID are created automatically.

var filter = Gmail.newFilter()
var email = 'something@some.com'
filter.id = 'person'
filter.criteria = Gmail.newFilterCriteria()
filter.criteria.query = email
filter.action = Gmail.newFilterAction()
filter.action.addLabelIds = ['Label_1']
Gmail.Users.Settings.Filters.create(filter, 'me')

When I get back the filter, it will say that it cannot be found

var filter2 = Gmail.Users.Settings.Filters.get('me', 'person')

This will return Not Found error even I can see the filter in setting in my Gmail. The actually ID for the filter I created above is ANe1Bmgel8OKlEXD-uArX77ISk35Lph1MbWWjA.

My question is what's the good way to manager filters through changes, keep them updated?

Body:
Instead of:

Gmail.Users.Settings.Filters.create(filter, 'me');

Try:

var filterProps = Gmail.Users.Settings.Filters.create(filter, 'me');
var filterId = filterProps.id;

Per the API documentation for creating a filter,

If successful, this method returns a Users.settings.filters resource in the response body.

The code above worked for me in a similar situation. To keep track of the filterId outside of Gmail, you could then tie the person's name to the id via the property service:

PropertiesService.getScriptProperties().setProperty(nameVar, filterId);

and then retrieve it like so:

PropertiesService.getScriptProperties().getProperty(nameVar);


问:
Match Lines From Two Lists With Wildcards In One List
I have two lists, one of which contains wildcards (in this case represented by *). I would like to compare the two lists and create an output of those that match, with each wildcard * representing a single character.

For example:

File 1

```<code>123456|Jane|Johnson|Pharmacist|janejohnson@gmail.com
09876579|Frank|Roberts|Butcher|frankie1@hotmail.com
092362936|Joe|Jordan|Joiner|joe@joesjoinery.com
928|Bob|Horton|Farmer|bhorton@farmernews.co.uk
</code>```

File 2

```<code>1***6|Jane|Johnson|Pharmacist|janejohnson@gmail.com
09876579|Frank|Roberts|Butcher|f**1@hotmail.com
092362936|Joe|Jordan|J*****|joe@joesjoinery.com
928|Bob|Horton|Farmer|b*****n@f*********.co.uk
</code>```

Output

```<code>092362936|Joe|Jordan|Joiner|joe@joesjoinery.com
928|Bob|Horton|Farmer|bhorton@farmernews.co.uk
</code>```

Explanation

The first two lines are not considered matches because the number of *s is not equal to the number of characters shown in the first file. The latter two are, so they are added to output.

I have tried to reason out ways to do this in AWK and using Join, but I don't know any way to even start trying to achieve this. Any help would be greatly appreciated.

答:
```<code>$ cat tst.awk
NR==FNR {
    file1[$0]
    next
}
{
    # Make every non-* char literal (see https://stackoverflow.com/a/29613573/1745001):
    gsub(/[^^*]/,"[&]")  # Convert every char X to [X] except ^ and *
    gsub(/\^/,"\\^")     # Convert every ^ to \^

    # Convert every * to .:
    gsub(/\*/,".")

    # Add line start/end anchors
    $0 = "^" $0 "$"

    # See if the current file2 line matches any line from file1
    # and if so print that line from file1:
    for ( line in file1 ) {
        if ( line ~ $0 ) {
            print line
        }
    }
}

$ awk -f tst.awk file1 file2
092362936|Joe|Jordan|Joiner|joe@joesjoinery.com
928|Bob|Horton|Farmer|bhorton@farmernews.co.uk
</code>```

Body:
I have two lists, one of which contains wildcards (in this case represented by *). I would like to compare the two lists and create an output of those that match, with each wildcard * representing a single character.

For example:

File 1

123456|Jane|Johnson|Pharmacist|janejohnson@gmail.com
09876579|Frank|Roberts|Butcher|frankie1@hotmail.com
092362936|Joe|Jordan|Joiner|joe@joesjoinery.com
928|Bob|Horton|Farmer|bhorton@farmernews.co.uk

File 2

1***6|Jane|Johnson|Pharmacist|janejohnson@gmail.com
09876579|Frank|Roberts|Butcher|f**1@hotmail.com
092362936|Joe|Jordan|J*****|joe@joesjoinery.com
928|Bob|Horton|Farmer|b*****n@f*********.co.uk

Output

092362936|Joe|Jordan|Joiner|joe@joesjoinery.com
928|Bob|Horton|Farmer|bhorton@farmernews.co.uk

Explanation

The first two lines are not considered matches because the number of *s is not equal to the number of characters shown in the first file. The latter two are, so they are added to output.

I have tried to reason out ways to do this in AWK and using Join, but I don't know any way to even start trying to achieve this. Any help would be greatly appreciated.


问:
Basic C# question if - else
I was wondering if someone could tell me if this sample is correct please.
Please ignore the if statement i wrote it for demonstration purposes only.

basically what I want to know is, if I need to throw an exception in my else, is it right to have it return false then thrown an exception, like follows:

```<code>public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        return false;
        throw new OutOfMemoryException();
    }
}
</code>```

OR - should I throw exception then return false outside else statement like this:

```<code>public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        throw new OutOfMemoryException();
    }
    return false;
}
</code>```

答:
If you return false and then throw an exception than the exception will not be thrown. the method exits at the return statement.

if you throw an exception and then return false, then the exception will be thrown and caught in the appropriate catch block and your final return false will not execute.

So, if you want to throw an exception here, then throw the exception. If you want to return false here, return false.

Title: Basic C# question if - else

Body:
I was wondering if someone could tell me if this sample is correct please.
Please ignore the if statement i wrote it for demonstration purposes only.

basically what I want to know is, if I need to throw an exception in my else, is it right to have it return false then thrown an exception, like follows:

public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        return false;
        throw new OutOfMemoryException();
    }
}

OR - should I throw exception then return false outside else statement like this:

public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        throw new OutOfMemoryException();
    }
    return false;
}


问:
How can get the value of the public part of the venn diagram which drawn by venn-package in R
Now I am using venn package in R to draw venn diagram and I succeeded.But I also want to get the value of the public part of the venn diagram.Although I have queried the official document,I cannot find any function to solve my problem.By the way,I need to draw a diagram with 6 sets,so you cannot use vennDiagram package.I hope to get your help.

```<code>library(venn)
venn(list("A" = c(1,2,3),"B" = c(3,4,5),"C" = c(1,2,3,4,5,6)))
</code>```

答:
For the lengths of the intersections you can try:

```<code>library(venn)

v <- venn(list("A" = c(1,2,3),"B" = c(3,4,5),"C" = c(1,2,3,4,5,6)))
lengths(attr(v, "intersections"))

C   B:C   A:C A:B:C
1     2     2     1
</code>```

For the values that intersect you can do:

```<code>attr(v, "intersections")

$C
[1] 6

$`B:C`
[1] 4 5

$`A:C`
[1] 1 2

$`A:B:C`
[1] 3
</code>```

Body:
Now I am using venn package in R to draw venn diagram and I succeeded.But I also want to get the value of the public part of the venn diagram.Although I have queried the official document,I cannot find any function to solve my problem.By the way,I need to draw a diagram with 6 sets,so you cannot use vennDiagram package.I hope to get your help.

library(venn)
venn(list("A" = c(1,2,3),"B" = c(3,4,5),"C" = c(1,2,3,4,5,6)))

Body:
For the lengths of the intersections you can try:

library(venn)

v <- venn(list("A" = c(1,2,3),"B" = c(3,4,5),"C" = c(1,2,3,4,5,6)))
lengths(attr(v, "intersections"))

C   B:C   A:C A:B:C
1     2     2     1

For the values that intersect you can do:

attr(v, "intersections")

$C
[1] 6

$`B:C`
[1] 4 5

$`A:C`
[1] 1 2

$`A:B:C`
[1] 3


问:
Spring Boot / MySql :: SQLException: Access denied for user 'user1'@'dhcp-etc' (using password: YES)
After reading and trying the answers of similar posts, I do want to ask this question. Has my issue to do with migrating to spring boot 2.0.0?

After creating any MySql database, locally or RDS AWS, I cannot get my Spring Boot 2.0.0 application connected to it. I still see that the exception: ... Access denied for user ... (using password: YES).

IMPORTANT: With the following simple Java program I could !! access the AWS RDS MySql database. I could also create tables, etc.

```<code>Class.forName("com.mysql.jdbc.Driver");
// Username and password created via MySQL workbench
String username = "dbuser";
String password = "dbpassword";
String jdbcUrl = "jdbc:mysql://myhostname:3306/mydatabase?user=" + username + "&password=" + password;
Connection con = DriverManager.getConnection(jdbcUrl);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(selectStmt);
</code>```

With a simple Spring Boot 2.0.0 application, I cannot get connected. First I get this error:

2018-12-25 10:36:59.670 ERROR 7184 --- [           main]
  com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception
  during pool initialization.

java.sql.SQLException: Access denied for user
  'dbuser'@'dhcp-etc' (using password: YES)

Further down I get this error:

java.lang.IllegalStateException: Failed to load ApplicationContext

Caused by: org.springframework.beans.factory.BeanCreationException:
  Error creating bean with name 'entityManagerFactory' defined in class
  path resource
  [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]:
  Invocation of init method failed; nested exception is
  javax.persistence.PersistenceException: [PersistenceUnit: default]
  Unable to build Hibernate SessionFactory Caused by:

javax.persistence.PersistenceException: [PersistenceUnit: default]
  Unable to build Hibernate SessionFactory Caused by:

org.hibernate.exception.GenericJDBCException: Unable to open JDBC
  Connection for DDL execution Caused by: java.sql.SQLException: Access
  denied for user 'dbsetup'@'dhcp-ipaddress-etc-.nl' (using password:
  YES)

And:

org.springframework.jdbc.support.MetaDataAccessException: Could not
  get Connection for extracting meta data; nested exception is
  org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to
  obtain JDBC Connection; nested exception is java.sql.SQLException:
  Access denied for user 'dbuser'@'dhcp-etc' (using password: YES)

This is my application.properties file:

```<code>spring.datasource.url=jdbc:mysql://myhostname:3306/mydatabase
spring.datasource.username=dbuser
spring.datasource.password=dbpassword
#REMOVED: spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
</code>```

Using this addition to the connection string does not have any effect: ?useSSL=false

My pom.xml contains:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
    <relativePath/>
</parent>

// anything related to databases:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

// I also tried version 5.1.40
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.11</version> <!-- without this version, same results -->
</dependency>
</code>```

After connecting correctly from my PC (with Spring Boot) I will continue to develop with an EC2 instance.

AWS RDS MySQL version: 5.6.41.

答:
Check your application.properties file carefully, there should not be any space after your DB username or password.
or, you can write in this way :

spring.datasource.url=jdbc:mysql://localhost:3306/dbname?user=dbuser&password=dbpassword

Body:
After reading and trying the answers of similar posts, I do want to ask this question. Has my issue to do with migrating to spring boot 2.0.0?

After creating any MySql database, locally or RDS AWS, I cannot get my Spring Boot 2.0.0 application connected to it. I still see that the exception: ... Access denied for user ... (using password: YES).

IMPORTANT: With the following simple Java program I could !! access the AWS RDS MySql database. I could also create tables, etc.

Class.forName("com.mysql.jdbc.Driver");
// Username and password created via MySQL workbench
String username = "dbuser";
String password = "dbpassword";
String jdbcUrl = "jdbc:mysql://myhostname:3306/mydatabase?user=" + username + "&password=" + password;
Connection con = DriverManager.getConnection(jdbcUrl);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(selectStmt);

With a simple Spring Boot 2.0.0 application, I cannot get connected. First I get this error:

2018-12-25 10:36:59.670 ERROR 7184 --- [           main]
  com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception
  during pool initialization.

java.sql.SQLException: Access denied for user
  'dbuser'@'dhcp-etc' (using password: YES)

Further down I get this error:

java.lang.IllegalStateException: Failed to load ApplicationContext

Caused by: org.springframework.beans.factory.BeanCreationException:
  Error creating bean with name 'entityManagerFactory' defined in class
  path resource
  [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]:
  Invocation of init method failed; nested exception is
  javax.persistence.PersistenceException: [PersistenceUnit: default]
  Unable to build Hibernate SessionFactory Caused by:

javax.persistence.PersistenceException: [PersistenceUnit: default]
  Unable to build Hibernate SessionFactory Caused by:

org.hibernate.exception.GenericJDBCException: Unable to open JDBC
  Connection for DDL execution Caused by: java.sql.SQLException: Access
  denied for user 'dbsetup'@'dhcp-ipaddress-etc-.nl' (using password:
  YES)

And:

org.springframework.jdbc.support.MetaDataAccessException: Could not
  get Connection for extracting meta data; nested exception is
  org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to
  obtain JDBC Connection; nested exception is java.sql.SQLException:
  Access denied for user 'dbuser'@'dhcp-etc' (using password: YES)

This is my application.properties file:

spring.datasource.url=jdbc:mysql://myhostname:3306/mydatabase
spring.datasource.username=dbuser
spring.datasource.password=dbpassword
#REMOVED: spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect

Using this addition to the connection string does not have any effect: ?useSSL=false

My pom.xml contains:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
    <relativePath/>
</parent>

// anything related to databases:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

// I also tried version 5.1.40
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.11</version>
</dependency>

After connecting correctly from my PC (with Spring Boot) I will continue to develop with an EC2 instance.

AWS RDS MySQL version: 5.6.41.


问:
How to use window's keydown listener for keys Chrome uses as shortcuts?
Strange problem I've come across running this code in Google Chrome:

window.addEventListener('keydown', function (event) {
    console.log(event)
})
```

<p>While I see the log for some keys ("w", "a", "s", spacebar, "esc", for example) - other keys do not trigger this event: "d", "r", "l"</p>

<p>In fact, some of these letters (like "r") are a built-in shortcut in Chrome that cause some other event to fire, i.e a page refresh.</p>

<p>Interestingly, using <code>preventDefault</code> does not solve the problem:</p>

<pre class="lang-js prettyprint-override"><code>window.addEventListener('keydown', function (event) {
    event.preventDefault()
    console.log(event)
})
</code>```

Note that in Firefox the original code (without preventDefault) works fine - but not in Chrome.

Any idea how to solve this?

Update
Might be worth noting (though I'm not sure why this affects it) that when running this code from the file system, there is no problem on Chrome. But once this code is being served (i.e from localhost) then we run into the issue.

答:
Wow. Turns out I had an extension installed which was doing some whacky things with keybindings.

It's a good extension otherwise for productivity, but if anyone else is using it, watch out for this gotcha:

Vimium

Body:
Strange problem I've come across running this code in Google Chrome:

window.addEventListener('keydown', function (event) {
    console.log(event)
})

While I see the log for some keys ("w", "a", "s", spacebar, "esc", for example) - other keys do not trigger this event: "d", "r", "l"

In fact, some of these letters (like "r") are a built-in shortcut in Chrome that cause some other event to fire, i.e a page refresh.

Interestingly, using preventDefault does not solve the problem:

window.addEventListener('keydown', function (event) {
    event.preventDefault()
    console.log(event)
})

Note that in Firefox the original code (without preventDefault) works fine - but not in Chrome.

Any idea how to solve this?

Update
Might be worth noting (though I'm not sure why this affects it) that when running this code from the file system, there is no problem on Chrome. But once this code is being served (i.e from localhost) then we run into the issue.


问:
Web Speech API text-to-speech not working on mobile
The below works on Desktop Chrome/Safari/Firefox, but not on mobile.

Even though on Chrome mobile I have 1) SpeechRecognition working perfectly; 2) SpeechSynthesisUtterance loads correctly, I can check all the attributes, load voices (remote debugging via DevTools) - just the phone wouldn't speak (iPhone Safari and Android Chrome tested).

Also, when I try this demo on mobile, it says my browser supports speech synthesis, I can select from the voices available, but the browser won't speak.

Any ideas what might be going wrong here?

```<code><script>
    var u = new SpeechSynthesisUtterance();
    u.text = "hello world";
    speechSynthesis.speak(u);
</script>
</code>```

答:
Have you tried adding window in front of speechSynthesis?
The code is window.speechSynthesis.speak(u) .</p>


问:
How to write a new row in an existing csv file without appending it in the last line?
I want to add a new row to an existing .csv file in python.

I tried by the following by appending a line to the csv file in spyder IDE in windows.

```<code>def write_to_file():

file = open('E:/Python/Sample//Dataset.csv','a')
file.write(",".join([str(newID),request.form['username'],request.form['age']]))

file.close()
</code>```

I expect the new values in a new row. But it is appending the new values in the last row.

If i add name "Erick" and Age "60", the output looks like the below image.

But I expect something like the below.

答:
What you're doing is correct, but you're assuming that the file already ends with a new line character

You need to put file.write("\n") before and/or after you've written each line

Body:
I want to add a new row to an existing .csv file in python.

I tried by the following by appending a line to the csv file in spyder IDE in windows.

def write_to_file():

file = open('E:/Python/Sample//Dataset.csv','a')
file.write(",".join([str(newID),request.form['username'],request.form['age']]))

file.close()

I expect the new values in a new row. But it is appending the new values in the last row.

If i add name "Erick" and Age "60", the output looks like the below image.

But I expect something like the below.


问:
How IntStream avoid hidden boxing costs
When you have

```<code>Stream.of(1 ,10).reduce(0,(v1, v2) -> v1 + v2);
</code>```

versus

```<code>IntStream.of(1 ,10).reduce(0,(v1, v2) -> v1 + v2);
</code>```

How does `IntStream? avoid the hidden boxing costs?

And why is boxing expensive in terms of performance?

答:
More of an addendum towards the consequences of boxing: it is not only the direct penalty for various additional method calls.

Keep in mind that the boxing part leads to the creation of new objects. Sure, as creating objects is a frequent operation in OOP, that operation is highly optimized. But still: it takes time fetch memory for a new object, and its constructor and all other init steps need to run. That basically adds up. And worse: when you do that on high scale, you put up a significant burden on the garbage collector.

( I remember seeing a question here long time ago where the OP asked why his application was showing extremely high GC activity. Turned out that he was doing some large loop where he boxed int values to Integer objects, just to throw away said objects moments later. Just avoiding that boxing dramatically improved the overall performance characteristics of his application )

Title: How IntStream avoid hidden boxing costs

Body:
When you have

Stream.of(1 ,10).reduce(0,(v1, v2) -> v1 + v2);

versus

IntStream.of(1 ,10).reduce(0,(v1, v2) -> v1 + v2);

How does `IntStream? avoid the hidden boxing costs?

And why is boxing expensive in terms of performance?


问:
How to send HTML emails where the signature doesn't get clipped?
I am trying to send emails through PHP and, while the messages get delivered, I'm having a small issue. In Gmail, and probably other email clients, the last line of the message (the signature) is getting clipped. By "clipped" I mean that the last line is hidden, with a sort of button that can be clicked to unhide the last line.

Is there some way to stop this from happening? This is my first time trying to send HTML emails through PHP, so I thought maybe there's some kind of syntax I don't know about.

I'm basically just using the phpmailer example code:

```<code>require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded

$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch

$mail->IsSMTP(); // telling the class to use SMTP

try {
  $mail->Host       = "mail.yourdomain.com"; // SMTP server
  $mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
  $mail->SMTPAuth   = true;                  // enable SMTP authentication
  $mail->SMTPSecure = "tls";                 // sets the prefix to the servier
  $mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
  $mail->Port       = 587;                   // set the SMTP port for the GMAIL server
  $mail->Username   = "yourusername@gmail.com";  // GMAIL username
  $mail->Password   = "yourpassword";            // GMAIL password
  $mail->AddReplyTo('name@yourdomain.com', 'First Last');
  $mail->AddAddress('whoto@otherdomain.com', 'John Doe');
  $mail->SetFrom('name@yourdomain.com', 'First Last');
  $mail->AddReplyTo('name@yourdomain.com', 'First Last');
  $mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
  $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
  $mail->MsgHTML(file_get_contents('contents.html'));
  $mail->AddAttachment('images/phpmailer.gif');      // attachment
  $mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
  $mail->Send();
  echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}
</code>```

Appreciate your advice.

答:
Solution often repeated on SO is to eliminate any sort of "repetition" so people add unique timestamps in the footer, invisible images etc.

In my case Gmail exhibited a bug and would display this message because the first name was appearing inside the subject line and inside the body of the email.

And it wasn't even trimming the message, it was displaying the full message, but saying that it's trimmed.

Solution is to try to manually cut out chunks of the email and keep sending yourself tests until you stop seeing the notice and then work your way out from there.

Body:
I am trying to send emails through PHP and, while the messages get delivered, I'm having a small issue. In Gmail, and probably other email clients, the last line of the message (the signature) is getting clipped. By "clipped" I mean that the last line is hidden, with a sort of button that can be clicked to unhide the last line.

Is there some way to stop this from happening? This is my first time trying to send HTML emails through PHP, so I thought maybe there's some kind of syntax I don't know about.

I'm basically just using the phpmailer example code:

require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded

$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch

$mail->IsSMTP(); // telling the class to use SMTP

try {
  $mail->Host       = "mail.yourdomain.com"; // SMTP server
  $mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
  $mail->SMTPAuth   = true;                  // enable SMTP authentication
  $mail->SMTPSecure = "tls";                 // sets the prefix to the servier
  $mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
  $mail->Port       = 587;                   // set the SMTP port for the GMAIL server
  $mail->Username   = "yourusername@gmail.com";  // GMAIL username
  $mail->Password   = "yourpassword";            // GMAIL password
  $mail->AddReplyTo('name@yourdomain.com', 'First Last');
  $mail->AddAddress('whoto@otherdomain.com', 'John Doe');
  $mail->SetFrom('name@yourdomain.com', 'First Last');
  $mail->AddReplyTo('name@yourdomain.com', 'First Last');
  $mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
  $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
  $mail->MsgHTML(file_get_contents('contents.html'));
  $mail->AddAttachment('images/phpmailer.gif');      // attachment
  $mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
  $mail->Send();
  echo "Message Sent OK

\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}

Appreciate your advice.


问:
The method max(Comparator<? super List<Integer>>) in the type Stream<List<Integer>> is not applicable for the arguments (Comparator<Integer>)
I am trying to fetch the student name based on his maximum marks using java8 streams API.

```<code>import static java.util.Arrays.asList;
public class Main {

    public static void main(String args[]) {
        new StudentReport(asList(
                new StudentData("Rohit", asList(100, 81, 82, 83)),
                new StudentData("Ram", asList(84, 85, 86, 87))));
    }
}

import java.util.List;
public class StudentData {

    private String name;
    private List<Integer> marks;

    StudentData(String name, List<Integer> marks) {
        this.name = name;
        this.marks = marks;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Integer> getMarks() {
        return marks;
    }
    public void setMarks(List<Integer> marks) {
        this.marks = marks;
    }
}

import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;

public class StudentReport {

    public StudentReport(List<StudentData> studentData)
    {
        printStudentNameWithMaxMarks(studentData);
    }

    private void printStudentNameWithMaxMarks(List<StudentData> studentData) {
// I am getting erro here.
        studentData.stream().map(student -> student.getMarks())
        .max(Comparator.comparing(Integer::intValue)).get();
    }

}
</code>```

I would like to return the "Rohit" in output because he scores max 100 marks. whether it is possible to achieve in a single stream operation, compare all the marks and return

```<code>new StudentData("Rohit", asList(100, 81, 82, 83)),
new StudentData("Ram", asList(84, 85, 86, 87))));
</code>```

Thanks in Advance and appreciating your help.

答:
The StudentData, you might be looking for can be obtained using.:

```<code>Optional<StudentData> studentWithMaxMarksInAnySubject = studentData
        .stream()
        // student with highest marks in any subject when there individual max scores are compared
        .max(Comparator.comparingInt(a ->
                a.getMarks().stream()
                        .mapToInt(i -> i)
                        .max() // max marks per student
                        .orElse(0)));
</code>```

To print the name of such a student, you can use a void call using ifPresent as:

```<code>studentData
        .stream()
        .max(Comparator.comparingInt(a ->
                a.getMarks().stream()
                        .mapToInt(i -> i)
                        .max()
                        .orElse(0)))
        .map(StudentData::getName)
        .ifPresent(System.out::println);
</code>```

Body:
I am trying to fetch the student name based on his maximum marks using java8 streams API.

import static java.util.Arrays.asList;
public class Main {

    public static void main(String args[]) {
        new StudentReport(asList(
                new StudentData("Rohit", asList(100, 81, 82, 83)),
                new StudentData("Ram", asList(84, 85, 86, 87))));
    }
}

import java.util.List;
public class StudentData {

    private String name;
    private List<Integer> marks;

    StudentData(String name, List<Integer> marks) {
        this.name = name;
        this.marks = marks;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Integer> getMarks() {
        return marks;
    }
    public void setMarks(List<Integer> marks) {
        this.marks = marks;
    }
}

import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;

public class StudentReport {

    public StudentReport(List<StudentData> studentData)
    {
        printStudentNameWithMaxMarks(studentData);
    }

    private void printStudentNameWithMaxMarks(List<StudentData> studentData) {
// I am getting erro here.
        studentData.stream().map(student -> student.getMarks())
        .max(Comparator.comparing(Integer::intValue)).get();
    }

}

I would like to return the "Rohit" in output because he scores max 100 marks. whether it is possible to achieve in a single stream operation, compare all the marks and return

new StudentData("Rohit", asList(100, 81, 82, 83)),
new StudentData("Ram", asList(84, 85, 86, 87))));

Thanks in Advance and appreciating your help.

Body:
The StudentData, you might be looking for can be obtained using.:

Optional<StudentData> studentWithMaxMarksInAnySubject = studentData
        .stream()
        // student with highest marks in any subject when there individual max scores are compared
        .max(Comparator.comparingInt(a ->
                a.getMarks().stream()
                        .mapToInt(i -> i)
                        .max() // max marks per student
                        .orElse(0)));

To print the name of such a student, you can use a void call using ifPresent as:

studentData
        .stream()
        .max(Comparator.comparingInt(a ->
                a.getMarks().stream()
                        .mapToInt(i -> i)
                        .max()
                        .orElse(0)))
        .map(StudentData::getName)
        .ifPresent(System.out::println);


问:
Program to view what a webpage would look through a mobile phone
I know this might off subject but what's a good program let's me view what a website might look like on a iPhone or other mobile device which connects to the Internet. Dreamweaver cs3 might have this but I can't find it anyone know?</p>

答:
Use the iphone simulator (part of the iphone SDK) and go to the webpage you want to test using safari.

Very simple except you will need a intel mac ( can be done on a ppc mac but installing the SDK requires some tricks on ppc and is not supported).

OwnerDisplayName: Sarmenhb

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: hhafez


问:
Sorting a dictionary by key and then also sorting the list of values related to each key and outputting to CSV file?
I am trying to sort a dictionary by key as well as value to create an output CSV file, I am having trouble getting the desired output file.

I've tried sorting the keys separately and the list of values separately but when outputting to the file the pairs are messed up.

    data = {}
    with open(filename, mode = 'r') as f:
        reader = csv.reader(f, delimiter = ',')
        for n, row in enumerate(reader):
            if not n:
                continue
            category, value = row
            if category not in data:
                data[category] = set()
            data[category].add((value))

    columnNames = sorted(data.keys())
    columnValues = []
    for value in data.values():
        columnValues.append(sorted(value))

    print(columnValues)
    with open('sorteddata.csv', 'w') as outfile:
        writer = csv.writer(outfile, delimiter = ',')
        writer.writerow(columnNames)
        writer.writerows(zip_longest(*columnValues))

```

If the input is {'number': {54, 1, 95, 78, 85, 87}}, 'name': {'bob', 'steve', 'alex'}, 'color': {'blue', 'yellow', 'black'}} the output should be {'color': {'black', 'blue', 'yellow'}, 'name': {'alex', 'bob', 'steve'}, 'number': {1, 54, 78, 85, 87, 94}}

Instead I get an output that looks like {'color': {'alex', 'bob', 'steve'}, 'name': {'black', 'blue', 'yellow'}, 'number': {1, 54, 78, 85, 87, 94}} where the color and name values are swapped but in the correct order.

答:
here you are sorting the keys and values independently, and not linking them correctly. You need to sort with the keys first and then for the corresponding values, sort the list

Here is a working solution with OrderDict

```<code>import collections
inp = {
    'number': {54, 1, 95, 78, 85, 87},
    'name': {'bob', 'steve', 'alex'},
    'color': {'blue', 'yellow', 'black'}}

ans = collections.OrderedDict()
for item in sorted(inp):     # sorting with the key
    val = sorted(inp[item])  # fetching the value list from the input dict
    print(item, val)
    ans[item] = sorted(val)  # saving the item and sorted values, in the new list
print(ans)
</code>```

Body:
I am trying to sort a dictionary by key as well as value to create an output CSV file, I am having trouble getting the desired output file.

I've tried sorting the keys separately and the list of values separately but when outputting to the file the pairs are messed up.

    data = {}
    with open(filename, mode = 'r') as f:
        reader = csv.reader(f, delimiter = ',')
        for n, row in enumerate(reader):
            if not n:
                continue
            category, value = row
            if category not in data:
                data[category] = set()
            data[category].add((value))

    columnNames = sorted(data.keys())
    columnValues = []
    for value in data.values():
        columnValues.append(sorted(value))

    print(columnValues)
    with open('sorteddata.csv', 'w') as outfile:
        writer = csv.writer(outfile, delimiter = ',')
        writer.writerow(columnNames)
        writer.writerows(zip_longest(*columnValues))

If the input is {'number': {54, 1, 95, 78, 85, 87}}, 'name': {'bob', 'steve', 'alex'}, 'color': {'blue', 'yellow', 'black'}} the output should be {'color': {'black', 'blue', 'yellow'}, 'name': {'alex', 'bob', 'steve'}, 'number': {1, 54, 78, 85, 87, 94}}

Instead I get an output that looks like {'color': {'alex', 'bob', 'steve'}, 'name': {'black', 'blue', 'yellow'}, 'number': {1, 54, 78, 85, 87, 94}} where the color and name values are swapped but in the correct order.

Body:
here you are sorting the keys and values independently, and not linking them correctly. You need to sort with the keys first and then for the corresponding values, sort the list

Here is a working solution with OrderDict

import collections
inp = {
    'number': {54, 1, 95, 78, 85, 87},
    'name': {'bob', 'steve', 'alex'},
    'color': {'blue', 'yellow', 'black'}}

ans = collections.OrderedDict()
for item in sorted(inp):     # sorting with the key
    val = sorted(inp[item])  # fetching the value list from the input dict
    print(item, val)
    ans[item] = sorted(val)  # saving the item and sorted values, in the new list
print(ans)


问:
Cannot find control with path: 'alternateAddress -> [object Object]'
I'm adding a form group dynamically to a form with FormArray. While I push a newly created form group and display in template, angular is having trouble to find the path of that control element.

I've referenced the angular doc on adding dynamic controls with form array.
https://angular.io/guide/reactive-forms#dynamic-controls-using-form-arrays
and also a similar problem in stack overflow : Angular: Cannot find control with path: 'variable-> 0 -> id'

component class:

```<code>get alternateAddress() {
    return this.signupForm.get('alternateAddress') as FormArray;
  }
 buildAddress() {
    return this.fb.group({
      city: [''],
      street: ['']
    });
  }
  addAlternateAddress() {
    this.alternateAddress.push( this.buildAddress());
  }
  ngOnInit() {
    this.signupForm = this.fb.group({
      name: ['', [Validators.required]],
      password: ['', [Validators.required]],
      confirmPassword: ['', [Validators.required]],
      email: ['', [Validators.email]],
      subscribe: [''],
      phone: ['', [Validators.required, Validators.pattern]],
      topic: ['', [Validators.required]],
      address: this.fb.group({
        city: [''],
        street: ['']
      }),
      alternateAddress: this.fb.array([ ])
    }, {validator: PasswordMatchValidator});
</code>```

Component template

 <button type="button" class="btn btn-sm btn-warning" (click)="addAlternateAddress()">Add alternate address</button>

 0">

            City
            <input type="text" class="form-control" name="city" [formControlName]="city">

            Street
            <input type="text" class="form-control" name="street" [formControlName]="street">

```

I'm not quite sure how to provide a path to form group and refer to it's individual controls as in the documentation, only the controls part is demonstrated.

Thanks to the community for putting their effort to debug.

答:
Thanks developer033 for the comment. It indeed helped me to debug the code.

```<code>    <div class="form-group" formArrayName="alternateAddress" *ngFor="let addr of alternateAddress.controls; let i=index">
                <div [formGroupName]="i">
<div class="form-group">
                <label for="city">City</label>
                <input type="text" class="form-control" name="city" formControlName="city">
              </div>
</code>```

This solved the issue. Binding the index to [formGroupName] and using the formControlName without square brackets.

Body:
I'm adding a form group dynamically to a form with FormArray. While I push a newly created form group and display in template, angular is having trouble to find the path of that control element.

I've referenced the angular doc on adding dynamic controls with form array.
https://angular.io/guide/reactive-forms#dynamic-controls-using-form-arrays
and also a similar problem in stack overflow : Angular: Cannot find control with path: 'variable-> 0 -> id'

component class:

get alternateAddress() {
    return this.signupForm.get('alternateAddress') as FormArray;
  }
 buildAddress() {
    return this.fb.group({
      city: [''],
      street: ['']
    });
  }
  addAlternateAddress() {
    this.alternateAddress.push( this.buildAddress());
  }
  ngOnInit() {
    this.signupForm = this.fb.group({
      name: ['', [Validators.required]],
      password: ['', [Validators.required]],
      confirmPassword: ['', [Validators.required]],
      email: ['', [Validators.email]],
      subscribe: [''],
      phone: ['', [Validators.required, Validators.pattern]],
      topic: ['', [Validators.required]],
      address: this.fb.group({
        city: [''],
        street: ['']
      }),
      alternateAddress: this.fb.array([ ])
    }, {validator: PasswordMatchValidator});

Component template

 <button type="button" class="btn btn-sm btn-warning" (click)="addAlternateAddress()">Add alternate address</button>

 0">

            City
            <input type="text" class="form-control" name="city" [formControlName]="city">

            Street
            <input type="text" class="form-control" name="street" [formControlName]="street">

I'm not quite sure how to provide a path to form group and refer to it's individual controls as in the documentation, only the controls part is demonstrated.

Thanks to the community for putting their effort to debug.

Body:
Thanks developer033 for the comment. It indeed helped me to debug the code.

    <div class="form-group" formArrayName="alternateAddress" *ngFor="let addr of alternateAddress.controls; let i=index">
                <div [formGroupName]="i">
<div class="form-group">
                <label for="city">City</label>
                <input type="text" class="form-control" name="city" formControlName="city">
              </div>

This solved the issue. Binding the index to [formGroupName] and using the formControlName without square brackets.


问:
Write image text to a new text file?
I am using tesseract for OCR. I am on ubuntu 18.04.

I have this program which extracts the texts from an image and print it. I want that program to create a new text file and paste the extracted content on to the new text file, but I am only able to do these

copy the content to clipboard

open new texteditor(geditor) file
I don't know how to paste the copied content

Here is my program which extracts the text from image

```<code>from pytesseract import image_to_string
from PIL import Image
print image_to_string(Image.open('sample.jpg'))
</code>```

Here is the program which copies the text to clipboard,

```<code>import os
def addToClipBoard(text):
    command = 'echo ' + text.strip() + '| clip'
    os.system(command)
</code>```

This program will open the geditor and create  a new text file

```<code>import subprocess
proc = subprocess.Popen(['gedit', 'file.txt'])
</code>```

Any help would be appreciated.

答:
If you just want the text, then open a text file and write to it:</p>

```<code>from pytesseract import image_to_string
from PIL import Image
text =  image_to_string(Image.open('sample.jpg'))

with open('file.txt', mode = 'w') as f:
    f.write(text)
</code>```

Title: Write image text to a new text file?

Body:
I am using tesseract for OCR. I am on ubuntu 18.04.

I have this program which extracts the texts from an image and print it. I want that program to create a new text file and paste the extracted content on to the new text file, but I am only able to do these

copy the content to clipboard

open new texteditor(geditor) file
I don't know how to paste the copied content

Here is my program which extracts the text from image

from pytesseract import image_to_string
from PIL import Image
print image_to_string(Image.open('sample.jpg'))

Here is the program which copies the text to clipboard,

import os
def addToClipBoard(text):
    command = 'echo ' + text.strip() + '| clip'
    os.system(command)

This program will open the geditor and create  a new text file

import subprocess
proc = subprocess.Popen(['gedit', 'file.txt'])

Any help would be appreciated.

Body:
If you just want the text, then open a text file and write to it:

from pytesseract import image_to_string
from PIL import Image
text =  image_to_string(Image.open('sample.jpg'))

with open('file.txt', mode = 'w') as f:
    f.write(text)