问:
How Can I Write Android Application with api 9 on Android-studio 3.4.1?
I Want to write an Android Application for Devices Running Android 2.3 and later. But It has some issues.

At first my "build.gradle" was:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "#.#.#"
        minSdkVersion 9
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

</code>```

But on build I get this error message:

```<code>ERROR: Manifest merger failed : uses-sdk:minSdkVersion 9 cannot be smaller than version 14 declared in library [com.android.support:appcompat-v7:28.0.0] /home/#/.gradle/caches/transforms-2/files-2.1/2f2898e7868f192ee52215913109e968/AndroidManifest.xml as the library might be using APIs not available in 9
    Suggestion: use a compatible library with a minSdk of at most 9,
        or increase this project's minSdk version to at least 14,
        or use tools:overrideLibrary="android.support.v7.appcompat" to force usage (may lead to runtime failures)
</code>```

I can't change 'targetSdkVersion' and 'compileSdkVersion' because this error will be occurred:

```<code>Google Play requires that apps target API level 26 or higher.
</code>```

Can you please tell me what should I do?

答:
The problem is with the support libraries you're using, the minimum SDK version for all support library packages is at least API level 14. link

The distribution of Android API level less than 10 is below 0.1%, I would recommend you to have a higher min API.android version distributions

Body:
I Want to write an Android Application for Devices Running Android 2.3 and later. But It has some issues.

At first my "build.gradle" was:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "#.#.#"
        minSdkVersion 9
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

But on build I get this error message:

ERROR: Manifest merger failed : uses-sdk:minSdkVersion 9 cannot be smaller than version 14 declared in library [com.android.support:appcompat-v7:28.0.0] /home/#/.gradle/caches/transforms-2/files-2.1/2f2898e7868f192ee52215913109e968/AndroidManifest.xml as the library might be using APIs not available in 9
    Suggestion: use a compatible library with a minSdk of at most 9,
        or increase this project's minSdk version to at least 14,
        or use tools:overrideLibrary="android.support.v7.appcompat" to force usage (may lead to runtime failures)

I can't change 'targetSdkVersion' and 'compileSdkVersion' because this error will be occurred:

Google Play requires that apps target API level 26 or higher.

Can you please tell me what should I do?


来源: stackexchange

问:
How to implement Laravel’s Must Verify Email feature in the API registration?
I implemented MustVerifyEmail interface in my user model

```<code>class User extends Authenticatable implements MustVerifyEmail
</code>```

also I made VerificationApi Controller

```<code><?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Verified;

class VerificationApiController extends Controller
{
    use VerifiesEmails;

    * Mark the authenticated user’s email address as verified.

    *

    * @param \Illuminate\Http\Request $request

    * @return \Illuminate\Http\Response

    */

    public function verify(Request $request) {

    $userID = $request['id'];

    $user = User::findOrFail($userID);

    $date = date("Y-m-d H:i:s");

    $user->email_verified_at = $date; // to enable the “email_verified_at field of that user be a current time stamp by mimicing the must verify email feature

    $user->save();

    return response()->json('Email verified!');

    }

    /**

    * Resend the email verification notification.

    *

    * @param \Illuminate\Http\Request $request

    * @return \Illuminate\Http\Response

    */

    public function resend(Request $request)

    {

    if ($request->user()->hasVerifiedEmail()) {

    return response()->json('User already have verified email!', 422);

    // return redirect($this->redirectPath());

    }

    $request->user()->sendEmailVerificationNotification();

    return response()->json('The notification has been resubmitted');

    }
}
</code>```

and I made

```<code><?php

namespace App\Notifications;

use Illuminate\Support\Carbon;

use Illuminate\Support\Facades\URL;

use Illuminate\Auth\Notifications\VerifyEmail as VerifyEmailBase;

class VerifyApiEmail extends VerifyEmailBase

{

/**

* Get the verification URL for the given notifiable.

*

* @param mixed $notifiable

* @return string

*/

protected function verificationUrl($notifiable)

{

return URL::temporarySignedRoute(

'verificationapi.verify', Carbon::now()->addMinutes(60), ['id' => $notifiable->getKey()]

); // this will basically mimic the email endpoint with get request

}

}
</code>```

in my api.php file I added

```<code>Route::get('email/verify/{id}', 'VerificationApiController@verify')->name('verificationapi.verify');

Route::get('email/resend', 'VerificationApiController@resend')->name('verificationapi.resend');
</code>```

So when i register to my api I get verification email in my mailtrap and when I click the button it says that my email is verified and in my database it changes from null to email_verified_at 2019-05-27 13:04:20 but when I put middleware('verified') on my routes and when I login with user that I have registrated in my postman I get

```<code>
    "message": "Your email address is not verified.",
    "exception": "Symfony\\Component\\HttpKernel\\Exception\\HttpException",
</code>```

my register() and login() functions look like this:

```<code> public function register(Request $request, User $user)
    {
        $phoneRegex = "(06|387)[0-9]{7,8}";
        $request->validate([
            'first_name' => 'required|string',
            'last_name' => 'required|string',
            'email' => 'required|string|email|unique:users',
            'password' => 'required|string|confirmed',
            'phone_number' => 'required|string|min:6',

        ]);
        $user = new User([
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
            'phone_number' => $request['phone_number'],
        ]);
        $user->save();

            Auth::login($user,true);
            $user->sendApiEmailVerificationNotification();

            $success['message'] = 'Please confirm yourself by clicking on verify user button sent to you on your email';

            return response()->json(['success'=>$success], $this->successStatus);
}
</code>```

```<code>public function login(Request $request)
    {
        $request->request->add([
            'client_id' => env("PASSPORT_CLIENT_ID"),
            'client_secret' => env("PASSPORT_CLIENT_SECRET"),
            'grant_type' => 'password',
            'scope' => '',
        ]);
        $tokenRequest = $request->create('/oauth/token', 'POST', $request->all());
        $response = Route::dispatch($tokenRequest);

        return $response;
    }
</code>```

can someone help me with this?

答:
I just added this to my login() function and now it looks like this

```<code>public function login(Request $request)
    {
        $request->request->add([
            'client_id' => env("PASSPORT_CLIENT_ID"),
            'client_secret' => env("PASSPORT_CLIENT_SECRET"),
            'grant_type' => 'password',
            'scope' => '',
        ]);
        $tokenRequest = $request->create('/oauth/token', 'POST', $request->all());
        $response = Route::dispatch($tokenRequest);

        $user = User::where('email', $request->username)->first();

        if($user->email_verified_at !== NULL){
            $success['message'] = "Login successfull";
            return $response;
            }else{
            return response()->json(['error'=>'Please Verify Email'], 401);
            }
    }
</code>```

and now if you did not verify your email you can't login it does not give you your access and refresh token back but I don't have to use my middleware('verified') on my routes so if someone still have better solution I would appreciate it.

ContentLicense: CC BY-SA 4.0

Body:
I implemented MustVerifyEmail interface in my user model

class User extends Authenticatable implements MustVerifyEmail

also I made VerificationApi Controller

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Verified;

class VerificationApiController extends Controller
{
    use VerifiesEmails;

    * Mark the authenticated user’s email address as verified.

    *

    * @param \Illuminate\Http\Request $request

    * @return \Illuminate\Http\Response

    */

    public function verify(Request $request) {

    $userID = $request['id'];

    $user = User::findOrFail($userID);

    $date = date("Y-m-d H:i:s");

    $user->email_verified_at = $date; // to enable the “email_verified_at field of that user be a current time stamp by mimicing the must verify email feature

    $user->save();

    return response()->json('Email verified!');

    }

    /**

    * Resend the email verification notification.

    *

    * @param \Illuminate\Http\Request $request

    * @return \Illuminate\Http\Response

    */

    public function resend(Request $request)

    {

    if ($request->user()->hasVerifiedEmail()) {

    return response()->json('User already have verified email!', 422);

    // return redirect($this->redirectPath());

    }

    $request->user()->sendEmailVerificationNotification();

    return response()->json('The notification has been resubmitted');

    }
}

and I made

<?php

namespace App\Notifications;

use Illuminate\Support\Carbon;

use Illuminate\Support\Facades\URL;

use Illuminate\Auth\Notifications\VerifyEmail as VerifyEmailBase;

class VerifyApiEmail extends VerifyEmailBase

{

/**

* Get the verification URL for the given notifiable.

*

* @param mixed $notifiable

* @return string

*/

protected function verificationUrl($notifiable)

{

return URL::temporarySignedRoute(

'verificationapi.verify', Carbon::now()->addMinutes(60), ['id' => $notifiable->getKey()]

); // this will basically mimic the email endpoint with get request

}

}

in my api.php file I added

Route::get('email/verify/{id}', 'VerificationApiController@verify')->name('verificationapi.verify');

Route::get('email/resend', 'VerificationApiController@resend')->name('verificationapi.resend');

So when i register to my api I get verification email in my mailtrap and when I click the button it says that my email is verified and in my database it changes from null to email_verified_at 2019-05-27 13:04:20 but when I put middleware('verified') on my routes and when I login with user that I have registrated in my postman I get

    "message": "Your email address is not verified.",
    "exception": "Symfony\\Component\\HttpKernel\\Exception\\HttpException",

my register() and login() functions look like this:

 public function register(Request $request, User $user)
    {
        $phoneRegex = "(06|387)[0-9]{7,8}";
        $request->validate([
            'first_name' => 'required|string',
            'last_name' => 'required|string',
            'email' => 'required|string|email|unique:users',
            'password' => 'required|string|confirmed',
            'phone_number' => 'required|string|min:6',

        ]);
        $user = new User([
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
            'phone_number' => $request['phone_number'],
        ]);
        $user->save();

            Auth::login($user,true);
            $user->sendApiEmailVerificationNotification();

            $success['message'] = 'Please confirm yourself by clicking on verify user button sent to you on your email';

            return response()->json(['success'=>$success], $this->successStatus);
}

public function login(Request $request)
    {
        $request->request->add([
            'client_id' => env("PASSPORT_CLIENT_ID"),
            'client_secret' => env("PASSPORT_CLIENT_SECRET"),
            'grant_type' => 'password',
            'scope' => '',
        ]);
        $tokenRequest = $request->create('/oauth/token', 'POST', $request->all());
        $response = Route::dispatch($tokenRequest);

        return $response;
    }

can someone help me with this?

Body:
I just added this to my login() function and now it looks like this

public function login(Request $request)
    {
        $request->request->add([
            'client_id' => env("PASSPORT_CLIENT_ID"),
            'client_secret' => env("PASSPORT_CLIENT_SECRET"),
            'grant_type' => 'password',
            'scope' => '',
        ]);
        $tokenRequest = $request->create('/oauth/token', 'POST', $request->all());
        $response = Route::dispatch($tokenRequest);

        $user = User::where('email', $request->username)->first();

        if($user->email_verified_at !== NULL){
            $success['message'] = "Login successfull";
            return $response;
            }else{
            return response()->json(['error'=>'Please Verify Email'], 401);
            }
    }

and now if you did not verify your email you can't login it does not give you your access and refresh token back but I don't have to use my middleware('verified') on my routes so if someone still have better solution I would appreciate it.


问:
Why add nameserver and NS record
When I register a domain and get hosing on different company I have to add the hosting company nameserver. This might sound reasonable.

BUT, in the hosing company cpanel there would be NS records with their nameservers, why is this needed ? Also the same if I leave the default nameservers in my domain there are NS records in the DNS section pointing to the same nsx.blabla.com.

Here is a photo explaining what I mean:
https://i.stack.imgur.com/kGy9O.png

So when a request to my domain is made, a final A record is needed. In order to obtain that record, the requester looks up for A record by asking whom? The nameseever added in the liat above or the nameserver in the NS record ?

答:
So when a request to my domain is made, a final A record is needed. In order to obtain that record, the requester looks up for A record by asking whom?

By asking domain NS where pointed the NS records then ask this server(ip on which NS records are pointing) where pointed domain A or AAAA record.

Title: Why add nameserver and NS record


问:
Lightweight JVM Instrumentation to find unused code
I was wondering if there is any lightweight way I could instrument a production JVM to gather information over a period of some months to gather statistics on unused code in my code base.

Thanks a lot for looking at this.

答:
File this under "experimental science project".  But the invoke dynamic feature coming in JDK7 was used in an interesting low-overhead test coverage prototype.

Maybe a bit too bleeding-edge today, but interesting once Java 7 is out.

ContentLicense: CC BY-SA 3.0


问:
In Promise loop, how to wait on request response?
I'm trying to make a loop that sends requests.

However, I would like to wait to receive the answer of the request before sending the next one. How can I proceed?

```<code> private start(): Promise<string> {
    return new Promise((resolve, reject) => {
      for (let j = 0, p = Promise.resolve(); j < count; j++) {
        p = p.then(_ => new Promise<null>(res =>
          setTimeout(() => {
            if (j === (count - 1)) {
              resolve();
            } else {
              this.http.get();
              res();
            }
          }, 1000)
        ));
      }
    });
  }
</code>```

Thanks for helping

答:
It is odd that you are using promises (instead of observables), when you are already working with Angular.

Anyways, when it comes to iterating promises, you can make use of Promise.all. We push the promises into a list, followed by resolving the promises only after all iterations of the for loop have been executed.

```<code>const promisesList = [];
for (let j = 0; j < count; j++) {
  promisesList.push(promise);
}
Promise.all(promises).then(res => {
  // handle the rest here
})
</code>```

As @robert suggested, I will include an implementation of how we can solve the above using observables/forkjoin. You will need to import forkJoin from the rxjs package before using it.

Similar to Promises.all(), forkJoin() waits for the for loop to be completed before returning the observable values.

```<code>import { forkJoin } from 'rxjs';

.
.
.

start() {
  const observablesList = [];
  const sendRequest = this.someService.someRequest(); // observable

  for (let j = 0; j < count; j++) {
    observablesList.push(sendRequest);
  }

  forkJoin(observablesList).subscribe(res => {
    console.log(res);
    //handle the rest
  });
}
</code>```

Body:
I'm trying to make a loop that sends requests.

However, I would like to wait to receive the answer of the request before sending the next one. How can I proceed?

 private start(): Promise<string> {
    return new Promise((resolve, reject) => {
      for (let j = 0, p = Promise.resolve(); j < count; j++) {
        p = p.then(_ => new Promise<null>(res =>
          setTimeout(() => {
            if (j === (count - 1)) {
              resolve();
            } else {
              this.http.get();
              res();
            }
          }, 1000)
        ));
      }
    });
  }

Thanks for helping

Body:
It is odd that you are using promises (instead of observables), when you are already working with Angular.

Anyways, when it comes to iterating promises, you can make use of Promise.all. We push the promises into a list, followed by resolving the promises only after all iterations of the for loop have been executed.

const promisesList = [];
for (let j = 0; j < count; j++) {
  promisesList.push(promise);
}
Promise.all(promises).then(res => {
  // handle the rest here
})

As @robert suggested, I will include an implementation of how we can solve the above using observables/forkjoin. You will need to import forkJoin from the rxjs package before using it.

Similar to Promises.all(), forkJoin() waits for the for loop to be completed before returning the observable values.

import { forkJoin } from 'rxjs';

.
.
.

start() {
  const observablesList = [];
  const sendRequest = this.someService.someRequest(); // observable

  for (let j = 0; j < count; j++) {
    observablesList.push(sendRequest);
  }

  forkJoin(observablesList).subscribe(res => {
    console.log(res);
    //handle the rest
  });
}


问:
HtmlUnit throws many exceptions on clicking one button
I'm trying to create program that signs in to Yahoo account.
I'm using HtmlUnit in Java, but when the program is trying to cick Sign In button it throws a large number of various exceptions.

The button form is:

```<code><form method="post" action="https://login.yahoo.com/config/login?" autocomplete="" name="login_form" onsubmit="return hash2(this)">
    <input type="hidden" name=".tries" value="1"/>
    <input type="hidden" name=".src" value=""/>
    <input type="hidden" name=".md5" value=""/>
    <input type="hidden" name=".hash" value=""/>
    <input type="hidden" name=".js" value=""/>
    <input type="hidden" name=".last" value=""/>
    <input type="hidden" name="promo" value=""/>
    <input type="hidden" name=".intl" value="us"/>
    <input type="hidden" name=".bypass" value=""/>
    <input type="hidden" name=".partner" value=""/>
    <input type="hidden" name=".u" value="eqn7kn96q7irv"/>
    <input type="hidden" name=".v" value="0"/>
    <input type="hidden" name=".challenge" value="rTRqt.vaVyBEJgxmMpkh0sqYx5Mz"/>
    <input type="hidden" name=".yplus" value=""/>
    <input type="hidden" name=".emailCode" value=""/>
    <input type="hidden" name="pkg" value=""/>
    <input type="hidden" name="stepid" value=""/>
    <input type="hidden" name=".ev" value=""/>
    <input type="hidden" name="hasMsgr" value="0"/>
    <input type="hidden" name=".chkP" value="Y"/>
    <input type="hidden" name=".done" value="http://my.yahoo.com"/>
    <input type="hidden" name=".pd" value="_ver=0&c=&ivt=&sg="/>
    <input type="hidden" name="pad" id="pad" value="3"/>
    <input type="hidden" name="aad" id="aad" value="3"/>
    <div id="inputs">
    <div id="fun"/>
    <div id="persistency">
    <div id="submit">
        <button type="submit" id=".save" name=".save" class="primaryCta" tabindex="5"> Sign In </button>
    </div>
</form>
</code>```

and my java code:

```<code>import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.RefreshHandler;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import java.io.IOException;
import java.net.URL;

public class VirtualWebBrowser {

    public static void clickAuthorizeButton(String url, String login, String password) throws Exception {

        WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
        webClient.setThrowExceptionOnScriptError(false);

        webClient.setRefreshHandler(new RefreshHandler() {
            public void handleRefresh(Page page, URL url, int arg) throws IOException {
                System.out.println("handleRefresh");
            }
        });

        HtmlPage loginPage = (HtmlPage) webClient.getPage(url);
        HtmlForm liginForm = loginPage.getFormByName("login_form");

        liginForm.getInputByName("login").setValueAttribute(login);
        liginForm.getInputByName("passwd").setValueAttribute(password);

        HtmlButton signInButton = liginForm.getButtonByName(".save");
        HtmlPage nextPage = (HtmlPage) signInButton.click();

        webClient.closeAllWindows();
    }
}
</code>```

All exceptions is in the line HtmlPage nextPage = (HtmlPage) signInButton.click();

After this line program is logged in Yahoo account but these all exceptions somehow affects all program work that it works unstably.
What should I do to avoid this situation or at least catch all exceptions?

答:
From the errors you pasted it looks like one of those cases where the HTMLUnit Javascript implementation differs from the one in browser. I also wouldn't be surprised if Yahoo didn't want people to perform automatic login into their properties.

Instead of wrestling with Javascript here I would try the following things:

Look at HTTP communication using a sniffer (like HttpFox) and try to send login request using HTTPURLConnection or HTTPClient.

See if you can login using the API. I know Yahoo provides OpenID, they also might provide OAuth authentication, see http://developer.yahoo.com/oauth/

Use Selenium to login using real browser.

Body:
I'm trying to create program that signs in to Yahoo account.
I'm using HtmlUnit in Java, but when the program is trying to cick Sign In button it throws a large number of various exceptions.

The button form is:

<form method="post" action="https://login.yahoo.com/config/login?" autocomplete="" name="login_form" onsubmit="return hash2(this)">
    <input type="hidden" name=".tries" value="1"/>
    <input type="hidden" name=".src" value=""/>
    <input type="hidden" name=".md5" value=""/>
    <input type="hidden" name=".hash" value=""/>
    <input type="hidden" name=".js" value=""/>
    <input type="hidden" name=".last" value=""/>
    <input type="hidden" name="promo" value=""/>
    <input type="hidden" name=".intl" value="us"/>
    <input type="hidden" name=".bypass" value=""/>
    <input type="hidden" name=".partner" value=""/>
    <input type="hidden" name=".u" value="eqn7kn96q7irv"/>
    <input type="hidden" name=".v" value="0"/>
    <input type="hidden" name=".challenge" value="rTRqt.vaVyBEJgxmMpkh0sqYx5Mz"/>
    <input type="hidden" name=".yplus" value=""/>
    <input type="hidden" name=".emailCode" value=""/>
    <input type="hidden" name="pkg" value=""/>
    <input type="hidden" name="stepid" value=""/>
    <input type="hidden" name=".ev" value=""/>
    <input type="hidden" name="hasMsgr" value="0"/>
    <input type="hidden" name=".chkP" value="Y"/>
    <input type="hidden" name=".done" value="http://my.yahoo.com"/>
    <input type="hidden" name=".pd" value="_ver=0&c=&ivt=&sg="/>
    <input type="hidden" name="pad" id="pad" value="3"/>
    <input type="hidden" name="aad" id="aad" value="3"/>

        <button type="submit" id=".save" name=".save" class="primaryCta" tabindex="5"> Sign In </button>

</form>

and my java code:

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.RefreshHandler;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import java.io.IOException;
import java.net.URL;

public class VirtualWebBrowser {

    public static void clickAuthorizeButton(String url, String login, String password) throws Exception {

        WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
        webClient.setThrowExceptionOnScriptError(false);

        webClient.setRefreshHandler(new RefreshHandler() {
            public void handleRefresh(Page page, URL url, int arg) throws IOException {
                System.out.println("handleRefresh");
            }
        });

        HtmlPage loginPage = (HtmlPage) webClient.getPage(url);
        HtmlForm liginForm = loginPage.getFormByName("login_form");

        liginForm.getInputByName("login").setValueAttribute(login);
        liginForm.getInputByName("passwd").setValueAttribute(password);

        HtmlButton signInButton = liginForm.getButtonByName(".save");
        HtmlPage nextPage = (HtmlPage) signInButton.click();

        webClient.closeAllWindows();
    }
}

All exceptions is in the line HtmlPage nextPage = (HtmlPage) signInButton.click();

After this line program is logged in Yahoo account but these all exceptions somehow affects all program work that it works unstably.
What should I do to avoid this situation or at least catch all exceptions?


问:
Create directory on remote hdfs from localhost using java
Create a directory on the remote HDFS from localhost

Written code but don't understand what and where to write the core-site.xml and the hdfs-site.xml.

```<code>public class HadoopCall {

    public void demomkdir(String dir) throws IOException
    {
        Configuration obj = new Configuration();

        obj.set("fs.defaultFS", "http://datlpdsnn01.pds.in.****.com:50070/");
        FileSystem fs = FileSystem.get(obj);

        Path pth = new Path(dir);
        fs.mkdirs(pth);
        System.out.println("created");
        fs.close();
    }

    public static void main(String[] args) throws IOException {
        HadoopCall oj = new HadoopCall();
        oj.demomkdir("user/*******/javacodemkdir");
    }

}
</code>```

答:
Reference : Hadoop Configuration class

As given in the above link:

core-default.xml: Read-only defaults for hadoop.

core-site.xml: Site-specific configuration for a given hadoop
  installation.

Both are files, with configuration specific to the installation and the default ones. You can add the path of any of the above xml with the method addResource(Path path). If the paths are not given, the xml file paths are inferred from classpath variables.

Body:
Create a directory on the remote HDFS from localhost

Written code but don't understand what and where to write the core-site.xml and the hdfs-site.xml.

public class HadoopCall {

    public void demomkdir(String dir) throws IOException
    {
        Configuration obj = new Configuration();

        obj.set("fs.defaultFS", "http://datlpdsnn01.pds.in.****.com:50070/");
        FileSystem fs = FileSystem.get(obj);

        Path pth = new Path(dir);
        fs.mkdirs(pth);
        System.out.println("created");
        fs.close();
    }

    public static void main(String[] args) throws IOException {
        HadoopCall oj = new HadoopCall();
        oj.demomkdir("user/*******/javacodemkdir");
    }

}


问:
How to select number content in element and add commas with jquery or js
I need to simply add commas to numbers in my code. I have tried a lot of hints here but something seems to be wrong.

I have tried with regex and the toLocalString() method and both haven't worked, can someone help me find the correct solution.

```<code><script type="text/javascript">
   $(document).ready(function () {
      // $("#price").toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      $('#price').html.toLocaleString('en');
   });
</script>
</code>```

Here's my element:

```<code><strong id="price"><%# Eval("OfferPrice") %></strong>
</code>```

Everything seems ok, can anyone help please. Thanks a lot!

答:
So, I finally found a 'mix' from the answers; that works. Here's the code. Thanks guys... and I will still need more help

```<code>   $(document).ready(function () {

        var x = parseFloat($('#price').html()).toLocaleString('en-US');
         $('#price').html(x)

   });
</code>```

Works awesome but will render only the first instance; how do I make it run through every instance of id="price" in the DOM? Thanks a lot friends.

Body:
I need to simply add commas to numbers in my code. I have tried a lot of hints here but something seems to be wrong.

I have tried with regex and the toLocalString() method and both haven't worked, can someone help me find the correct solution.

Here's my element:

<%# Eval("OfferPrice") %>

Everything seems ok, can anyone help please. Thanks a lot!

Body:
So, I finally found a 'mix' from the answers; that works. Here's the code. Thanks guys... and I will still need more help

   $(document).ready(function () {

        var x = parseFloat($('#price').html()).toLocaleString('en-US');
         $('#price').html(x)

   });

Works awesome but will render only the first instance; how do I make it run through every instance of id="price" in the DOM? Thanks a lot friends.


问:
Calculate Points from Letters in a Switch Case
I am trying to create a scrabble-like program that calculates the points of letters contained in a word. These word are contained in a .txt file. I can get it to read from the file, but unsure how to get it to calculate the value of each word. I have attached what I have done so far, and am wondering if a switch case is the best way to go, and if so, how do I assign a value to a letter with a switch case. Any help is appreciated.

```<code>/*
 * To change this license header, choose License Headers in Project      Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 package pointsproblem;

/**
 *
 */

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

 public class PointsProblem {

/**
 * @param args the command line arguments
 * @throws java.io.FileNotFoundException
 */
 public static void main(String[] args) throws FileNotFoundException {
    // TODO code application logic here

    //create new object//
    PointsProblem task1 = new PointsProblem();

    File file = new File("dictionary.txt");
    // read the file//
    Scanner input = new Scanner(file);

    //check if file can be found//
    if (!file.isFile()) {
        System.err.println("Cannot open file: " + input);
        System.exit(0);
    }
    else {
        System.out.println("Successfully opened file: " + input + ".");
    }
    //read all the lines in the file//
   {
        while (input.hasNext()) {
            String word = input.nextLine();
            System.out.println(word);
            System.out.println("'" + input + "' is worth " + point + " points");

    int point = "";
    switch(point)  {

    case 'a': = "1":
    case 'e': = "1";
    case 'i': = "1";
    case 'l': = "1";
    case 'n': = "1";
    case 'o': = "1";
    case 'r': = "1";
    case 's': = "1";
    case 't': = "1";
    case 'u': = "1";
    case 'g': = "2";
    case 'g': = "2";
    case 'b': = "3";
    case 'm': = "3";
    case 'c': = "3";
    case 'p': = "3";
    case 'f': = "4";
    case 'h': = "4";
    case 'v': = "4";
    case 'w': = "4";
    case 'y': = "4";
    case 'k': = "5";
    case 'j': = "8";
    case 'x': = "8";
    case 'q': = "10";
    case 'z': = "10";

    return score  =  point + "";
        }//end switch

     }//end point calculation loop

    public int getScore() {
        return score;
    }
    //public boolean containsLetter(Character letter) {
        //return points.contains(letter);//

    }
</code>```

I have tried assigning an int of X to the value as well. I would like it to read the word contained in the file and give a total score.

答:
Use a map to store the values:

```<code>Map<Character, Integer> charValues = new HashMap();
charValues.put('a', 2);
charValues.put('b', 1);
</code>```

You can use the chars() and collect as sum

```<code>int total = word.chars()
                .mapToObj(c -> charValues.get((char)c))
                .mapToInt(i -> (int)i)
                .sum();
</code>```

But according to your use case you can count the chars first and then multiply

```<code>  Map<Character, Integer> counter = new HashMap<>();
  while (input.hasNext()) {
     String word = input.next();
     word.chars().forEach(c -> counter.compute(c, (k, v) -> v == null ? 1 : v + 1));
  }

counter.entrySet()
       .stream()
       .mapToInt(e -> charValues.get(e.getKey())*e.getValue())
       .sum();
</code>```

if you are using switch your code will look like:

```<code>int total = 0;

switch (c){
      case 'a' : total += 1; break;
      case 'b' : total += 2; break;
}
</code>```

Body:
I am trying to create a scrabble-like program that calculates the points of letters contained in a word. These word are contained in a .txt file. I can get it to read from the file, but unsure how to get it to calculate the value of each word. I have attached what I have done so far, and am wondering if a switch case is the best way to go, and if so, how do I assign a value to a letter with a switch case. Any help is appreciated.

/*
 * To change this license header, choose License Headers in Project      Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 package pointsproblem;

/**
 *
 */

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

 public class PointsProblem {

/**
 * @param args the command line arguments
 * @throws java.io.FileNotFoundException
 */
 public static void main(String[] args) throws FileNotFoundException {
    // TODO code application logic here

    //create new object//
    PointsProblem task1 = new PointsProblem();

    File file = new File("dictionary.txt");
    // read the file//
    Scanner input = new Scanner(file);

    //check if file can be found//
    if (!file.isFile()) {
        System.err.println("Cannot open file: " + input);
        System.exit(0);
    }
    else {
        System.out.println("Successfully opened file: " + input + ".");
    }
    //read all the lines in the file//
   {
        while (input.hasNext()) {
            String word = input.nextLine();
            System.out.println(word);
            System.out.println("'" + input + "' is worth " + point + " points");

    int point = "";
    switch(point)  {

    case 'a': = "1":
    case 'e': = "1";
    case 'i': = "1";
    case 'l': = "1";
    case 'n': = "1";
    case 'o': = "1";
    case 'r': = "1";
    case 's': = "1";
    case 't': = "1";
    case 'u': = "1";
    case 'g': = "2";
    case 'g': = "2";
    case 'b': = "3";
    case 'm': = "3";
    case 'c': = "3";
    case 'p': = "3";
    case 'f': = "4";
    case 'h': = "4";
    case 'v': = "4";
    case 'w': = "4";
    case 'y': = "4";
    case 'k': = "5";
    case 'j': = "8";
    case 'x': = "8";
    case 'q': = "10";
    case 'z': = "10";

    return score  =  point + "";
        }//end switch

     }//end point calculation loop

    public int getScore() {
        return score;
    }
    //public boolean containsLetter(Character letter) {
        //return points.contains(letter);//

    }

I have tried assigning an int of X to the value as well. I would like it to read the word contained in the file and give a total score.

Body:
Use a map to store the values:

Map<Character, Integer> charValues = new HashMap();
charValues.put('a', 2);
charValues.put('b', 1);

You can use the chars() and collect as sum

int total = word.chars()
                .mapToObj(c -> charValues.get((char)c))
                .mapToInt(i -> (int)i)
                .sum();

But according to your use case you can count the chars first and then multiply

  Map<Character, Integer> counter = new HashMap<>();
  while (input.hasNext()) {
     String word = input.next();
     word.chars().forEach(c -> counter.compute(c, (k, v) -> v == null ? 1 : v + 1));
  }

counter.entrySet()
       .stream()
       .mapToInt(e -> charValues.get(e.getKey())*e.getValue())
       .sum();

if you are using switch your code will look like:

int total = 0;

switch (c){
      case 'a' : total += 1; break;
      case 'b' : total += 2; break;
}


问:
Length cannot be less than zero Parameter Name: length
I have hunted hi and low to attempt to find a solution to this error.  In Debug and Release mode of VS2015 i do not get any errors and the code generates the desired outcome.  Once the program is compiled and installed, when the email button is pressed to generate the code, the application acts like its going to work and then after about 20 seconds the gives the error "Length cannot be less than zero Parameter Name: length" but the application continues but does not complete the code in question.

I have disabled and attempted the one line of code that references length which made no difference.

I at my limits of what could be causing this so i am looking for help to find the needle in a haystack.

Below is the code in question:

```<code>try
        {
            // Create the Outlook application.
            Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
            // Create a new mail item.
            Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
            // Set HTMLBody.
            //add the body of the email
            oMsg.HTMLBody = DictMailParam["Body"].ToString();
            //Add an attachment.
            String sDisplayName = DictMailParam["AttachmentName"].ToString();
            int iPosition = (int)oMsg.Body.Length + 1;
            int iAttachType = (int)Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue;
            //now attached the file
            //Microsoft.Office.Interop.Outlook.Attachment oAttach = oMsg.Attachments.Add
            //                             (@"C:\\fileName.jpg", iAttachType, iPosition, sDisplayName);

            foreach (string strFile in DictMailParam["Attachments"].ToString().Split(',').ToList())
            {
                Microsoft.Office.Interop.Outlook.Attachment oAttach = oMsg.Attachments.Add
                        (strFile, iAttachType, iPosition, sDisplayName);
            }
            //Subject line
            oMsg.Subject = DictMailParam["Subject"].ToString();
            // Add a recipient.
            Microsoft.Office.Interop.Outlook.Recipients oRecips = (Microsoft.Office.Interop.Outlook.Recipients)oMsg.Recipients;
            Microsoft.Office.Interop.Outlook.Recipient oRecip = null;
            // Change the recipient in the next line if necessary.
            foreach (var MailId in DictMailParam["ToAddress"].ToString().Split(';').ToArray())
            {
                if (!string.IsNullOrEmpty(MailId))
                {
                    oRecip = (Microsoft.Office.Interop.Outlook.Recipient)oRecips.Add(MailId);//DictMailParam["ToAddress"].ToString()
                    oRecip.Resolve();
                    // Send.
                }

            }

            oMsg.Send();
            MessageBox.Show("Purchase Order has been sent to your email." + "\n" + "Please check your mail.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            // Clean up.
            oRecip = null;
            oRecips = null;
            oMsg = null;
            oApp = null;
        }//end of try block
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }//end of catch
    }//end of Email Method
</code>```

答: Change the catch code to MessageBox.Show(ex.ToString()...) instead of ex.Message. This way when error happens you will get a message specifying which line is throwing the exception. Then come back here and tell which line it was. It will be much more easy to solve your problem once we know where it is.</p>

Body:
I have hunted hi and low to attempt to find a solution to this error.  In Debug and Release mode of VS2015 i do not get any errors and the code generates the desired outcome.  Once the program is compiled and installed, when the email button is pressed to generate the code, the application acts like its going to work and then after about 20 seconds the gives the error "Length cannot be less than zero Parameter Name: length" but the application continues but does not complete the code in question.

I have disabled and attempted the one line of code that references length which made no difference.

I at my limits of what could be causing this so i am looking for help to find the needle in a haystack.

Below is the code in question:

try
        {
            // Create the Outlook application.
            Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
            // Create a new mail item.
            Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
            // Set HTMLBody.
            //add the body of the email
            oMsg.HTMLBody = DictMailParam["Body"].ToString();
            //Add an attachment.
            String sDisplayName = DictMailParam["AttachmentName"].ToString();
            int iPosition = (int)oMsg.Body.Length + 1;
            int iAttachType = (int)Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue;
            //now attached the file
            //Microsoft.Office.Interop.Outlook.Attachment oAttach = oMsg.Attachments.Add
            //                             (@"C:\\fileName.jpg", iAttachType, iPosition, sDisplayName);

            foreach (string strFile in DictMailParam["Attachments"].ToString().Split(',').ToList())
            {
                Microsoft.Office.Interop.Outlook.Attachment oAttach = oMsg.Attachments.Add
                        (strFile, iAttachType, iPosition, sDisplayName);
            }
            //Subject line
            oMsg.Subject = DictMailParam["Subject"].ToString();
            // Add a recipient.
            Microsoft.Office.Interop.Outlook.Recipients oRecips = (Microsoft.Office.Interop.Outlook.Recipients)oMsg.Recipients;
            Microsoft.Office.Interop.Outlook.Recipient oRecip = null;
            // Change the recipient in the next line if necessary.
            foreach (var MailId in DictMailParam["ToAddress"].ToString().Split(';').ToArray())
            {
                if (!string.IsNullOrEmpty(MailId))
                {
                    oRecip = (Microsoft.Office.Interop.Outlook.Recipient)oRecips.Add(MailId);//DictMailParam["ToAddress"].ToString()
                    oRecip.Resolve();
                    // Send.
                }

            }

            oMsg.Send();
            MessageBox.Show("Purchase Order has been sent to your email." + "\n" + "Please check your mail.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            // Clean up.
            oRecip = null;
            oRecips = null;
            oMsg = null;
            oApp = null;
        }//end of try block
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }//end of catch
    }//end of Email Method


问:
docker for windows, cannot share drive
```<code>docker:   Version 18.04.0-ce-rc2-win61
windows 10 enterprise
</code>```

I click settings in docker, click on shared drives, select any drive C, D, Z, etc.

Seems like it's about to share, then the drive check boxes un-check.

The logs contain the following:

```<code>[21:12:39.990][SharedDrivesSettings][Info   ] Apply shared drive settings<br>
[21:12:39.992][NamedPipeClient][Info   ] Sending Version()...<br>
[21:12:39.994][NamedPipeClient][Info   ] Received response for Version<br>
[21:12:39.994][NamedPipeClient][Info   ] Sending Unmount(All, C, Docker.Core.Settings)...<br>
[21:12:39.994][NamedPipeServer][Info   ] Version()<br>
[21:12:39.994][NamedPipeServer][Info   ] Version done in 00:00:00.<br>
[21:12:39.996][NamedPipeServer][Info   ] Unmount(All, C, Docker.Core.Settings)<br>
[21:12:39.996][SambaShare     ][Info   ] Unmount C<br>
[21:12:42.185][NamedPipeClient][Info   ] Received response for Unmount<br>
[21:12:42.184][NamedPipeServer][Info   ] Unmount done in 00:00:02.1885041.<br>
[21:12:42.201][NamedPipeClient][Info   ] Sending Version()...<br>
[21:12:42.202][NamedPipeClient][Info   ] Received response for Version<br>
[21:12:42.202][NamedPipeClient][Info   ] Sending Mount(All, Z, NW\ws743e:**********, Docker.Core.Settings)...<br>
[21:12:42.202][NamedPipeServer][Info   ] Version()<br>
[21:12:42.202][NamedPipeServer][Info   ] Version done in 00:00:00.<br>
[21:12:42.204][NamedPipeServer][Info   ] Mount(All, Z, NW\ws743e1234:**********, Docker.Core.Settings)<br>
[21:12:42.543][SambaShare     ][Info   ] Mount Z<br>
[21:12:43.260][Cmd            ][Info   ] This shared resource does not exist.<br>
[21:12:43.260][Cmd            ][Info   ] More help is available by typing NET HELPMSG 2310.<br>
[21:12:43.270][SambaShare     ][Info   ] "Z" is not shared<br>
[21:12:43.270][SambaShare     ][Info   ] Creating share "Z:\" as "Z" with Full Control to "NW\ws743e1234"<br>
[21:12:44.003][Cmd            ][Info   ] Z was shared successfully.<br>
[21:12:44.613][Cmd            ][Info   ] Share name        Z<br>
[21:12:44.613][Cmd            ][Info   ] Path              Z:\<br>
[21:12:44.613][Cmd            ][Info   ] Remark            <br>
[21:12:44.613][Cmd            ][Info   ] Maximum users     No limit<br>
[21:12:44.614][Cmd            ][Info   ] Users         <br>
[21:12:44.614][Cmd            ][Info   ] Caching           Caching disabled<br>
[21:12:44.614][Cmd            ][Info   ] Permission        NW\ws743e1234, FULL<br>
[21:12:44.614][Cmd            ][Info   ] The command completed successfully.<br>
[21:12:44.626][SambaShare     ][Info   ] "Z" is shared<br>
[21:12:44.998][SambaShare     ][Info   ] Username: ws743e1234<br>
[21:12:44.998][SambaShare     ][Info   ] Host IP: 10.0.75.1<br>
[21:12:44.998][SambaShare     ][Info   ] Cifs options: noperm,iocharset=utf8,nobrl,mfsymlinks,vers=3.02,domain=NW,sec=ntlmsspi<br>
[21:12:46.700][SambaShare     ][Error  ] Unable to mount Z drive: C:\Program Files\Docker\Docker\Resources\bin\docker.exe: error during connect: Post http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.37/containers/create: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
See 'C:\Program Files\Docker\Docker\Resources\bin\docker.exe run --help'.<br>

[21:12:46.700][SambaShare     ][Info   ] Removing share Z<br>
[21:12:47.468][SambaShare     ][Info   ] Mount Z<br>
[21:12:48.078][Cmd            ][Info   ] This shared resource does not exist.<br>
[21:12:48.078][Cmd            ][Info   ] More help is available by typing NET HELPMSG 2310.<br>
[21:12:48.095][SambaShare     ][Info   ] "Z" is not shared<br>
[21:12:48.095][SambaShare     ][Info   ] Creating share "Z:\" as "Z" with Full Control to "ws743e1234"<br>
[21:12:48.777][Cmd            ][Info   ] Z was shared successfully.<br>
[21:12:49.408][Cmd            ][Info   ] Share name        Z<br>
[21:12:49.408][Cmd            ][Info   ] Path              Z:\<br>
[21:12:49.408][Cmd            ][Info   ] Remark            <br>
[21:12:49.411][Cmd            ][Info   ] Maximum users     No limit<b<br>r>
[21:12:49.411][Cmd            ][Info   ] Users
[21:12:49.411][Cmd            ][Info   ] Caching           Caching disabled<br>
[21:12:49.411][Cmd            ][Info   ] Permission        NW\ws743e1234, FULL<br>
[21:12:49.411][Cmd            ][Info   ] The command completed successfully.<br>
[21:12:49.422][SambaShare     ][Info   ] "Z" is shared<br>
[21:12:49.428][SambaShare     ][Error  ] Unable to validate cred: Invalid username or password<br>
[21:12:49.428][SambaShare     ][Info   ] Removing share Z<br>
[21:12:49.960][NamedPipeClient][Info   ] Received response for Mount<br>
[21:12:49.960][NamedPipeServer][Info   ] Mount done in 00:00:07.7555290.<br>
[21:13:05.778][CredentialAsker][Info   ] Storing credentials: NW\ws743e1234:***********<br>
[21:13:05.829][NamedPipeClient][Info   ] Sending Version()...<br>
[21:13:05.831][NamedPipeClient][Info   ] Received response for Version<br>
[21:13:05.831][NamedPipeClient][Info   ] Sending Mount(All, Z, NW\ws743e1234:**********, Docker.Core.Settings)...<br>
[21:13:05.831][NamedPipeServer][Info   ] Version()<br>
[21:13:05.831][NamedPipeServer][Info   ] Version done in 00:00:00.<br>
[21:13:05.833][NamedPipeServer][Info   ] Mount(All, Z, NW\ws743e1234:**********, Docker.Core.Settings)<br>
[21:13:06.056][SambaShare     ][Info   ] Mount Z<br>
[21:13:06.799][Cmd            ][Info   ] This shared resource does not exist.<br>
[21:13:06.800][Cmd            ][Info   ] More help is available by typing NET HELPMSG 2310.<br>
[21:13:06.811][SambaShare     ][Info   ] "Z" is not shared<br>
[21:13:06.811][SambaShare     ][Info   ] Creating share "Z:\" as "Z" with Full Control to "NW\ws743e1234"<br>
[21:13:07.438][Cmd            ][Info   ] Z was shared successfully.<br>
[21:13:08.009][Cmd            ][Info   ] Share name        Z<br>
[21:13:08.009][Cmd            ][Info   ] Path              Z:\<br>
[21:13:08.009][Cmd            ][Info   ] Remark            <br>
[21:13:08.009][Cmd            ][Info   ] Maximum users     No limit<br>
[21:13:08.009][Cmd            ][Info   ] Users             <br>
[21:13:08.009][Cmd            ][Info   ] Caching           Caching disabled<br>
[21:13:08.010][Cmd            ][Info   ] Permission        NW\ws743e1234, FULL
[21:13:08.010][Cmd            ][Info   ] The command completed successfully.<br>
[21:13:08.023][SambaShare     ][Info   ] "Z" is shared<br>
[21:13:08.117][SambaShare     ][Info   ] Username: ws743e1234<br>
[21:13:08.117][SambaShare     ][Info   ] Host IP: 10.0.75.1<br>
[21:13:08.117][SambaShare     ][Info   ] Cifs options: noperm,iocharset=utf8,nobrl,mfsymlinks,vers=3.02,domain=NW,sec=ntlmsspi
[21:13:10.052][SambaShare     ][Error  ] Unable to mount Z drive: C:\Program Files\Docker\Docker\Resources\bin\docker.exe: error during connect: Post http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.37/containers/create: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
See 'C:\Program Files\Docker\Docker\Resources\bin\docker.exe run --help'.<br>

[21:13:10.052][SambaShare     ][Info   ] Removing share Z<br><br>
[21:13:10.957][SambaShare     ][Info   ] Mount Z<br>
[21:13:11.632][Cmd            ][Info   ] This shared resource does not exist.<br>
[21:13:11.632][Cmd            ][Info   ] More help is available by typing NET HELPMSG 2310.<br>
[21:13:11.647][SambaShare     ][Info   ] "Z" is not shared<br>
[21:13:11.647][SambaShare     ][Info   ] Creating share "Z:\" as "Z" with Full Control to "ws743e1234"<br>
[21:13:12.306][Cmd            ][Info   ] Z was shared successfully.<br>
[21:13:12.978][Cmd            ][Info   ] Share name        Z<br>
[21:13:12.978][Cmd            ][Info   ] Path              Z:\<br>
[21:13:12.978][Cmd            ][Info   ] Remark            <br>
[21:13:12.978][Cmd            ][Info   ] Maximum users     No limit<br>
[21:13:12.978][Cmd            ][Info   ] Users             <br>
[21:13:12.978][Cmd            ][Info   ] Caching           Caching disabled<br>
[21:13:12.979][Cmd            ][Info   ] Permission        NW\ws743e1234, FULL<br>
[21:13:12.979][Cmd            ][Info   ] The command completed successfully.<br>
[21:13:12.992][SambaShare     ][Info   ] "Z" is shared<br>
[21:13:12.998][SambaShare     ][Error  ] Unable to validate cred: Invalid username or password<br>
[21:13:12.998][SambaShare     ][Info   ] Removing share Z<br>
[21:13:13.629][NamedPipeClient][Info   ] Received response for Mount<br>
[21:13:13.629][NamedPipeServer][Info   ] Mount done in 00:00:07.7959981.<br>
[21:13:13.656][NamedPipeClient][Info   ] Sending Version()...<br>
[21:13:13.657][NamedPipeClient][Info   ] Received response for Version<br>
[21:13:13.657][NamedPipeClient][Info   ] Sending GetDefaultVhdxPath()...<br>
[21:13:13.657][NamedPipeServer][Info   ] Version()<br>
[21:13:13.659][NamedPipeClient][Info   ] Received response for GetDefaultVhdxPath<br>
[21:13:13.657][NamedPipeServer][Info   ] Version done in 00:00:00.<br>
[21:13:13.658][NamedPipeServer][Info   ] GetDefaultVhdxPath()<br>
[21:13:13.670][NamedPipeClient][Info   ] Sending Version()...<br>
[21:13:13.734][NamedPipeClient][Info   ] Received response for Version<br>
[21:13:13.734][NamedPipeClient][Info   ] Sending TryGetVhdxSize(C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\MobyLinuxVM.vhdx)...<br>
[21:13:13.659][NamedPipeServer][Info   ] GetDefaultVhdxPath done in 00:00:00.0010018.<br>
[21:13:13.734][NamedPipeServer][Info   ] Version()<br>
[21:13:13.734][NamedPipeServer][Info   ] Version done in 00:00:00.<br>
[21:13:13.735][NamedPipeServer][Info   ] TryGetVhdxSize(C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\MobyLinuxVM.vhdx)<br>
[21:13:13.735][PowerShell     ][Info   ] Run script...<br>
[21:13:13.874][NamedPipeClient][Info   ] Received response for TryGetVhdxSize<br>
[21:13:13.873][NamedPipeServer][Info   ] TryGetVhdxSize done in 00:00:00.1379989.<br>
[21:13:13.876][NamedPipeClient][Info   ] Sending Version()...<br>
[21:13:13.877][NamedPipeClient][Info   ] Received response for Version<br>
[21:13:13.877][NamedPipeClient][Info   ] Sending TryGetVhdxSize(C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\MobyLinuxVM.vhdx)...<br>
[21:13:13.877][NamedPipeServer][Info   ] Version()<br>
[21:13:13.877][NamedPipeServer][Info   ] Version done in 00:00:00.<br>
[21:13:13.878][NamedPipeServer][Info   ] TryGetVhdxSize(C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\MobyLinuxVM.vhdx)<br>
[21:13:13.878][PowerShell     ][Info   ] Run script...<br>
[21:13:13.977][NamedPipeClient][Info   ] Received response for TryGetVhdxSize<br>
[21:13:13.977][NamedPipeServer][Info   ] TryGetVhdxSize done in 00:00:00.0984980.<br>
</code>```

答:
In my case, I was logged in with my Microsoft Account. Seems that Docker doesn't like that. I had to reconfigure my user to login with a local account and then it worked just fine.

You can do that by :

Open the Windows menu

Type "Your info"

Click the "Sign in with a local account" link

Set a password

Sign-out

Sign-in

Do the Shared Drive thing in Docker

Also make sure your user is in the docker-users group from the Control Panel, Users management.

Title: docker for windows, cannot share drive

Body:
docker:   Version 18.04.0-ce-rc2-win61
windows 10 enterprise

I click settings in docker, click on shared drives, select any drive C, D, Z, etc.

Seems like it's about to share, then the drive check boxes un-check.

The logs contain the following:

[21:12:39.990][SharedDrivesSettings][Info   ] Apply shared drive settings

[21:12:39.992][NamedPipeClient][Info   ] Sending Version()...

[21:12:39.994][NamedPipeClient][Info   ] Received response for Version

[21:12:39.994][NamedPipeClient][Info   ] Sending Unmount(All, C, Docker.Core.Settings)...

[21:12:39.994][NamedPipeServer][Info   ] Version()

[21:12:39.994][NamedPipeServer][Info   ] Version done in 00:00:00.

[21:12:39.996][NamedPipeServer][Info   ] Unmount(All, C, Docker.Core.Settings)

[21:12:39.996][SambaShare     ][Info   ] Unmount C

[21:12:42.185][NamedPipeClient][Info   ] Received response for Unmount

[21:12:42.184][NamedPipeServer][Info   ] Unmount done in 00:00:02.1885041.

[21:12:42.201][NamedPipeClient][Info   ] Sending Version()...

[21:12:42.202][NamedPipeClient][Info   ] Received response for Version

[21:12:42.202][NamedPipeClient][Info   ] Sending Mount(All, Z, NW\ws743e:**********, Docker.Core.Settings)...

[21:12:42.202][NamedPipeServer][Info   ] Version()

[21:12:42.202][NamedPipeServer][Info   ] Version done in 00:00:00.

[21:12:42.204][NamedPipeServer][Info   ] Mount(All, Z, NW\ws743e1234:**********, Docker.Core.Settings)

[21:12:42.543][SambaShare     ][Info   ] Mount Z

[21:12:43.260][Cmd            ][Info   ] This shared resource does not exist.

[21:12:43.260][Cmd            ][Info   ] More help is available by typing NET HELPMSG 2310.

[21:12:43.270][SambaShare     ][Info   ] "Z" is not shared

[21:12:43.270][SambaShare     ][Info   ] Creating share "Z:\" as "Z" with Full Control to "NW\ws743e1234"

[21:12:44.003][Cmd            ][Info   ] Z was shared successfully.

[21:12:44.613][Cmd            ][Info   ] Share name        Z

[21:12:44.613][Cmd            ][Info   ] Path              Z:\

[21:12:44.613][Cmd            ][Info   ] Remark

[21:12:44.613][Cmd            ][Info   ] Maximum users     No limit

[21:12:44.614][Cmd            ][Info   ] Users

[21:12:44.614][Cmd            ][Info   ] Caching           Caching disabled

[21:12:44.614][Cmd            ][Info   ] Permission        NW\ws743e1234, FULL

[21:12:44.614][Cmd            ][Info   ] The command completed successfully.

[21:12:44.626][SambaShare     ][Info   ] "Z" is shared

[21:12:44.998][SambaShare     ][Info   ] Username: ws743e1234

[21:12:44.998][SambaShare     ][Info   ] Host IP: 10.0.75.1

[21:12:44.998][SambaShare     ][Info   ] Cifs options: noperm,iocharset=utf8,nobrl,mfsymlinks,vers=3.02,domain=NW,sec=ntlmsspi

[21:12:46.700][SambaShare     ][Error  ] Unable to mount Z drive: C:\Program Files\Docker\Docker\Resources\bin\docker.exe: error during connect: Post http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.37/containers/create: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
See 'C:\Program Files\Docker\Docker\Resources\bin\docker.exe run --help'.

[21:12:46.700][SambaShare     ][Info   ] Removing share Z

[21:12:47.468][SambaShare     ][Info   ] Mount Z

[21:12:48.078][Cmd            ][Info   ] This shared resource does not exist.

[21:12:48.078][Cmd            ][Info   ] More help is available by typing NET HELPMSG 2310.

[21:12:48.095][SambaShare     ][Info   ] "Z" is not shared

[21:12:48.095][SambaShare     ][Info   ] Creating share "Z:\" as "Z" with Full Control to "ws743e1234"

[21:12:48.777][Cmd            ][Info   ] Z was shared successfully.

[21:12:49.408][Cmd            ][Info   ] Share name        Z

[21:12:49.408][Cmd            ][Info   ] Path              Z:\

[21:12:49.408][Cmd            ][Info   ] Remark

[21:12:49.411][Cmd            ][Info   ] Maximum users     No limit
[21:12:49.411][Cmd            ][Info   ] Users
[21:12:49.411][Cmd            ][Info   ] Caching           Caching disabled

[21:12:49.411][Cmd            ][Info   ] Permission        NW\ws743e1234, FULL

[21:12:49.411][Cmd            ][Info   ] The command completed successfully.

[21:12:49.422][SambaShare     ][Info   ] "Z" is shared

[21:12:49.428][SambaShare     ][Error  ] Unable to validate cred: Invalid username or password

[21:12:49.428][SambaShare     ][Info   ] Removing share Z

[21:12:49.960][NamedPipeClient][Info   ] Received response for Mount

[21:12:49.960][NamedPipeServer][Info   ] Mount done in 00:00:07.7555290.

[21:13:05.778][CredentialAsker][Info   ] Storing credentials: NW\ws743e1234:***********

[21:13:05.829][NamedPipeClient][Info   ] Sending Version()...

[21:13:05.831][NamedPipeClient][Info   ] Received response for Version

[21:13:05.831][NamedPipeClient][Info   ] Sending Mount(All, Z, NW\ws743e1234:**********, Docker.Core.Settings)...

[21:13:05.831][NamedPipeServer][Info   ] Version()

[21:13:05.831][NamedPipeServer][Info   ] Version done in 00:00:00.

[21:13:05.833][NamedPipeServer][Info   ] Mount(All, Z, NW\ws743e1234:**********, Docker.Core.Settings)

[21:13:06.056][SambaShare     ][Info   ] Mount Z

[21:13:06.799][Cmd            ][Info   ] This shared resource does not exist.

[21:13:06.800][Cmd            ][Info   ] More help is available by typing NET HELPMSG 2310.

[21:13:06.811][SambaShare     ][Info   ] "Z" is not shared

[21:13:06.811][SambaShare     ][Info   ] Creating share "Z:\" as "Z" with Full Control to "NW\ws743e1234"

[21:13:07.438][Cmd            ][Info   ] Z was shared successfully.

[21:13:08.009][Cmd            ][Info   ] Share name        Z

[21:13:08.009][Cmd            ][Info   ] Path              Z:\

[21:13:08.009][Cmd            ][Info   ] Remark

[21:13:08.009][Cmd            ][Info   ] Maximum users     No limit

[21:13:08.009][Cmd            ][Info   ] Users

[21:13:08.009][Cmd            ][Info   ] Caching           Caching disabled

[21:13:08.010][Cmd            ][Info   ] Permission        NW\ws743e1234, FULL
[21:13:08.010][Cmd            ][Info   ] The command completed successfully.

[21:13:08.023][SambaShare     ][Info   ] "Z" is shared

[21:13:08.117][SambaShare     ][Info   ] Username: ws743e1234

[21:13:08.117][SambaShare     ][Info   ] Host IP: 10.0.75.1

[21:13:08.117][SambaShare     ][Info   ] Cifs options: noperm,iocharset=utf8,nobrl,mfsymlinks,vers=3.02,domain=NW,sec=ntlmsspi
[21:13:10.052][SambaShare     ][Error  ] Unable to mount Z drive: C:\Program Files\Docker\Docker\Resources\bin\docker.exe: error during connect: Post http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.37/containers/create: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
See 'C:\Program Files\Docker\Docker\Resources\bin\docker.exe run --help'.

[21:13:10.052][SambaShare     ][Info   ] Removing share Z

[21:13:10.957][SambaShare     ][Info   ] Mount Z

[21:13:11.632][Cmd            ][Info   ] This shared resource does not exist.

[21:13:11.632][Cmd            ][Info   ] More help is available by typing NET HELPMSG 2310.

[21:13:11.647][SambaShare     ][Info   ] "Z" is not shared

[21:13:11.647][SambaShare     ][Info   ] Creating share "Z:\" as "Z" with Full Control to "ws743e1234"

[21:13:12.306][Cmd            ][Info   ] Z was shared successfully.

[21:13:12.978][Cmd            ][Info   ] Share name        Z

[21:13:12.978][Cmd            ][Info   ] Path              Z:\

[21:13:12.978][Cmd            ][Info   ] Remark

[21:13:12.978][Cmd            ][Info   ] Maximum users     No limit

[21:13:12.978][Cmd            ][Info   ] Users

[21:13:12.978][Cmd            ][Info   ] Caching           Caching disabled

[21:13:12.979][Cmd            ][Info   ] Permission        NW\ws743e1234, FULL

[21:13:12.979][Cmd            ][Info   ] The command completed successfully.

[21:13:12.992][SambaShare     ][Info   ] "Z" is shared

[21:13:12.998][SambaShare     ][Error  ] Unable to validate cred: Invalid username or password

[21:13:12.998][SambaShare     ][Info   ] Removing share Z

[21:13:13.629][NamedPipeClient][Info   ] Received response for Mount

[21:13:13.629][NamedPipeServer][Info   ] Mount done in 00:00:07.7959981.

[21:13:13.656][NamedPipeClient][Info   ] Sending Version()...

[21:13:13.657][NamedPipeClient][Info   ] Received response for Version

[21:13:13.657][NamedPipeClient][Info   ] Sending GetDefaultVhdxPath()...

[21:13:13.657][NamedPipeServer][Info   ] Version()

[21:13:13.659][NamedPipeClient][Info   ] Received response for GetDefaultVhdxPath

[21:13:13.657][NamedPipeServer][Info   ] Version done in 00:00:00.

[21:13:13.658][NamedPipeServer][Info   ] GetDefaultVhdxPath()

[21:13:13.670][NamedPipeClient][Info   ] Sending Version()...

[21:13:13.734][NamedPipeClient][Info   ] Received response for Version

[21:13:13.734][NamedPipeClient][Info   ] Sending TryGetVhdxSize(C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\MobyLinuxVM.vhdx)...

[21:13:13.659][NamedPipeServer][Info   ] GetDefaultVhdxPath done in 00:00:00.0010018.

[21:13:13.734][NamedPipeServer][Info   ] Version()

[21:13:13.734][NamedPipeServer][Info   ] Version done in 00:00:00.

[21:13:13.735][NamedPipeServer][Info   ] TryGetVhdxSize(C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\MobyLinuxVM.vhdx)

[21:13:13.735][PowerShell     ][Info   ] Run script...

[21:13:13.874][NamedPipeClient][Info   ] Received response for TryGetVhdxSize

[21:13:13.873][NamedPipeServer][Info   ] TryGetVhdxSize done in 00:00:00.1379989.

[21:13:13.876][NamedPipeClient][Info   ] Sending Version()...

[21:13:13.877][NamedPipeClient][Info   ] Received response for Version

[21:13:13.877][NamedPipeClient][Info   ] Sending TryGetVhdxSize(C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\MobyLinuxVM.vhdx)...

[21:13:13.877][NamedPipeServer][Info   ] Version()

[21:13:13.877][NamedPipeServer][Info   ] Version done in 00:00:00.

[21:13:13.878][NamedPipeServer][Info   ] TryGetVhdxSize(C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks\MobyLinuxVM.vhdx)

[21:13:13.878][PowerShell     ][Info   ] Run script...

[21:13:13.977][NamedPipeClient][Info   ] Received response for TryGetVhdxSize

[21:13:13.977][NamedPipeServer][Info   ] TryGetVhdxSize done in 00:00:00.0984980.


问:
ThreadState exception in initialization
It has been a long question, so here is the summary first,

I have a Client class for my messenger project.

My Client class has a Socket.

I use its BeginReceive method to get messages from server.

In async callback of BeginReceive, I get the message using EndReceive.

When I get the message, I fire the MessageReceived event with message itself.

I use this Client class in my message form.

In message form, I can get the received message by attaching a method to Client.MessageReceived.

I use OnMessageReceived method for this purpose.

When I get the message, I can show it on a TextBox (using Control.Invoke) or MessageBox.

I can also add a new tab to my TabControl in OnMessageReceived.

When I try to initialize a WebBrowser control, I get ThreadStateException.

The control I use to display messages derives from WebBrowser control, so I need it.

Threading.Thread.CurrentThread.ThreadState is "Background".

I don't think you'll need the details but you can find the detailed question I first intented to post below.

Many thanks.

I'm working on a messenger project (Server is a Windows Service and Client is a Windows Forms Application) using Net.Socket's async methods.
I fire Client's MessageReceived event in callback of Socket.BeginReceive;
Everything is how I want them to be until here.

I use MessageReceived event in my form (the one that two people writes to each other) I can do anything I want to the UI using Control.Invoke method (if required) with one annoying exception.

I have tabbed conversations in the form so when a message arrives, I check if there is an open conversation (tab) with the sender. If yes, I select that tab and display the message. If no, I create a new ConversationTab.

Now, I'm sorry if it's being a long question than it should be or if I can't explain myself sufficently. English is not my first language and this is my first question in Stack Overflow.
So, here is the ConversationTab:

```<code>public class ConversationTab : TabPage
    {
        public User Friend { get; private set; }
        public MessageBrowser MessageBrowser { get; private set; }

        public ConversationTab(User friend) : base(friend.DisplayName)
        {
            Friend = friend;
            MessageBrowser = new MessageBrowser();
            Controls.Add(MessageBrowser);
            MessageBrowser.Dock = DockStyle.Fill;
        }
    }
</code>```

MessageBrowser derives from WebBrowser and the reason I use this is because I could not apply custom styles (color, font, size) 'per message' using RichTextBox. RichTextBox.SelectedColor doesn't always work or I couldn't make it work as intended. MessageBrowser let's me use CSS instead. Wandering off of the subject? Sorry.

Here is the NewConversation method I call when MessageReceived event fires:

```<code>public void NewConversation(User friend)
    {
        ConversationTab tab = Conversations.FirstOrDefault(c => c.Friend.Id == friend.Id);

        if (tab != null)
            ActiveConversation = tab;
        else
        {
            tab = new ConversationTab(friend);
            // add tab to TabControl
        }

        // bla
    }
</code>```

"Conversations" gets the tab pages of the TabControl and "ActiveConversation" gets or sets the SelectedTab property of the TabControl.
My point in creating these properties are mostly thread-safety logic inside.

So the question: It's throwing ThreadStateException in "tab = new ConversationTab(friend)" part of the above code. It is the "MessageBrowser = new MessageBrowser()" part of the first code and the constructor of MessageBrowser. The reason of why I didn't provide MessageBrowser's constructor code is because the exception is thrown before any line of inner code gets executed (It is about WebBrowser's constructor, I get this exception when I try to initalize a WebBrowser, too.)
Actually I don't even get an exception, the application just closes there without notifying me about anything. I saw the exception when I try to call "MessageBrowser = new MessageBrowser()" on ConversationTab's constructor in Watch window.

I'm kind of new to using threads and asynchronous methods.
MSDN says:

ThreadStateException is thrown by methods that cannot perform the requested operation due to the current state of a thread.

In my case, the thread's state is "Background".
I have no clue about what am I doing wrong.

Thank you very much if you read the whole thing and thank you much more if you can help.

答:
This seems to be related to using COM (web browser control uses COM) in .NET where thread apartment needs to be set to STA.

Try adding [STAThread] to your entry point.

Have a look at this.

Title: ThreadState exception in initialization

Body:
It has been a long question, so here is the summary first,

I have a Client class for my messenger project.

My Client class has a Socket.

I use its BeginReceive method to get messages from server.

In async callback of BeginReceive, I get the message using EndReceive.

When I get the message, I fire the MessageReceived event with message itself.

I use this Client class in my message form.

In message form, I can get the received message by attaching a method to Client.MessageReceived.

I use OnMessageReceived method for this purpose.

When I get the message, I can show it on a TextBox (using Control.Invoke) or MessageBox.

I can also add a new tab to my TabControl in OnMessageReceived.

When I try to initialize a WebBrowser control, I get ThreadStateException.

The control I use to display messages derives from WebBrowser control, so I need it.

Threading.Thread.CurrentThread.ThreadState is "Background".

I don't think you'll need the details but you can find the detailed question I first intented to post below.

Many thanks.

I'm working on a messenger project (Server is a Windows Service and Client is a Windows Forms Application) using Net.Socket's async methods.
I fire Client's MessageReceived event in callback of Socket.BeginReceive;
Everything is how I want them to be until here.

I use MessageReceived event in my form (the one that two people writes to each other) I can do anything I want to the UI using Control.Invoke method (if required) with one annoying exception.

I have tabbed conversations in the form so when a message arrives, I check if there is an open conversation (tab) with the sender. If yes, I select that tab and display the message. If no, I create a new ConversationTab.

Now, I'm sorry if it's being a long question than it should be or if I can't explain myself sufficently. English is not my first language and this is my first question in Stack Overflow.
So, here is the ConversationTab:

public class ConversationTab : TabPage
    {
        public User Friend { get; private set; }
        public MessageBrowser MessageBrowser { get; private set; }

        public ConversationTab(User friend) : base(friend.DisplayName)
        {
            Friend = friend;
            MessageBrowser = new MessageBrowser();
            Controls.Add(MessageBrowser);
            MessageBrowser.Dock = DockStyle.Fill;
        }
    }

MessageBrowser derives from WebBrowser and the reason I use this is because I could not apply custom styles (color, font, size) 'per message' using RichTextBox. RichTextBox.SelectedColor doesn't always work or I couldn't make it work as intended. MessageBrowser let's me use CSS instead. Wandering off of the subject? Sorry.

Here is the NewConversation method I call when MessageReceived event fires:

public void NewConversation(User friend)
    {
        ConversationTab tab = Conversations.FirstOrDefault(c => c.Friend.Id == friend.Id);

        if (tab != null)
            ActiveConversation = tab;
        else
        {
            tab = new ConversationTab(friend);
            // add tab to TabControl
        }

        // bla
    }

"Conversations" gets the tab pages of the TabControl and "ActiveConversation" gets or sets the SelectedTab property of the TabControl.
My point in creating these properties are mostly thread-safety logic inside.

So the question: It's throwing ThreadStateException in "tab = new ConversationTab(friend)" part of the above code. It is the "MessageBrowser = new MessageBrowser()" part of the first code and the constructor of MessageBrowser. The reason of why I didn't provide MessageBrowser's constructor code is because the exception is thrown before any line of inner code gets executed (It is about WebBrowser's constructor, I get this exception when I try to initalize a WebBrowser, too.)
Actually I don't even get an exception, the application just closes there without notifying me about anything. I saw the exception when I try to call "MessageBrowser = new MessageBrowser()" on ConversationTab's constructor in Watch window.

I'm kind of new to using threads and asynchronous methods.
MSDN says:

ThreadStateException is thrown by methods that cannot perform the requested operation due to the current state of a thread.

In my case, the thread's state is "Background".
I have no clue about what am I doing wrong.

Thank you very much if you read the whole thing and thank you much more if you can help.


问:
Auth::id() can't find user id and return null, laravel
I am setting like and unlike options on articles. but in LikeController there is problem. when I push the like button it says ->

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id'
  cannot be null (SQL: insert into likes (user_id, article_id,
  updated_at, created_at) values (?, 5, 2019-05-30 07:58:34,
  2019-05-30 07:58:34))

Updated JWT and Routes

Like model:

```<code>class Like extends Model
{
    public $timestamps = true;
    public $with = ["user"];

    protected $fillable = ["user_id", "article_id"];

    public function article()
    {
        return $this->belongsTo("App\Article");
    }

    public function user()
    {
        return $this->belongsTo("App\User");
    }
}
</code>```

and LikeController:

```<code>use Auth;
use App\Article;
use App\Like;

public function like($id)
{
    $article = Article::find($id);

    $like =  Like::create([
        "user_id" => Auth::id(),
        "article_id" => $article->id
    ]);

    return Like::find($like->id);
}

public function unlike($id)
{
    $article = Article::find($id);

    Like::where("user_id", Auth::id())
        ->where("article_id", $article->id)
        ->first()
        ->delete();

    return 1;
}
</code>```

I am not very sure why Auth::id() can't find the user id and return null?

Using JWT with vue.js

Routes:

```<code>Route::group(['prefix' => 'auth'], function ($router) {

  Route::post('register', 'AuthController@register');
  Route::post('login', 'AuthController@login');
  Route::post('logout', 'AuthController@logout');
  Route::post('refresh', 'AuthController@refresh');
  Route::post('me', 'AuthController@me');

});

Route::get("/like/{id}", [
        "uses" => "LikeController@like"
    ]);
Route::get("/unlike/{id}", [
        "uses" => "LikeController@unlike"
    ]);
</code>```

AuthController and User

to set controller and user model I followed the docs: https://jwt-auth.readthedocs.io/en/develop/quick-start/

答:
You have missed to specify the middleware => api from the route groups. Also include the like related routes Or any protected routes within this routegroup.

config/auth.php shoud be updated as

```<code>'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

...

'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],
</code>```

In routes/api.php

```<code>Route::post('login', 'AuthController@login')->name('login');

Route::group(['middleware' => 'api'], function ($router) {

    Route::group(['prefix' => 'auth'], function ($router) {
        Route::post('register', 'AuthController@register');
        # Route::post('login', 'AuthController@login'); // commented.
        Route::post('logout', 'AuthController@logout');
        Route::post('refresh', 'AuthController@refresh');
        Route::post('me', 'AuthController@me');

    });

    Route::get("/like/{id}", [
        "uses" => "LikeController@like"
    ]);
    Route::get("/unlike/{id}", [
        "uses" => "LikeController@unlike"
    ]);

});
</code>```

Body:
I am setting like and unlike options on articles. but in LikeController there is problem. when I push the like button it says ->

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id'
  cannot be null (SQL: insert into likes (user_id, article_id,
  updated_at, created_at) values (?, 5, 2019-05-30 07:58:34,
  2019-05-30 07:58:34))

Updated JWT and Routes

Like model:

class Like extends Model
{
    public $timestamps = true;
    public $with = ["user"];

    protected $fillable = ["user_id", "article_id"];

    public function article()
    {
        return $this->belongsTo("App\Article");
    }

    public function user()
    {
        return $this->belongsTo("App\User");
    }
}

and LikeController:

use Auth;
use App\Article;
use App\Like;

public function like($id)
{
    $article = Article::find($id);

    $like =  Like::create([
        "user_id" => Auth::id(),
        "article_id" => $article->id
    ]);

    return Like::find($like->id);
}

public function unlike($id)
{
    $article = Article::find($id);

    Like::where("user_id", Auth::id())
        ->where("article_id", $article->id)
        ->first()
        ->delete();

    return 1;
}

I am not very sure why Auth::id() can't find the user id and return null?

Using JWT with vue.js

Routes:

Route::group(['prefix' => 'auth'], function ($router) {

  Route::post('register', 'AuthController@register');
  Route::post('login', 'AuthController@login');
  Route::post('logout', 'AuthController@logout');
  Route::post('refresh', 'AuthController@refresh');
  Route::post('me', 'AuthController@me');

});

Route::get("/like/{id}", [
        "uses" => "LikeController@like"
    ]);
Route::get("/unlike/{id}", [
        "uses" => "LikeController@unlike"
    ]);

AuthController and User

to set controller and user model I followed the docs: https://jwt-auth.readthedocs.io/en/develop/quick-start/

Body:
You have missed to specify the middleware => api from the route groups. Also include the like related routes Or any protected routes within this routegroup.

config/auth.php shoud be updated as

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

...

'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

In routes/api.php

Route::post('login', 'AuthController@login')->name('login');

Route::group(['middleware' => 'api'], function ($router) {

    Route::group(['prefix' => 'auth'], function ($router) {
        Route::post('register', 'AuthController@register');
        # Route::post('login', 'AuthController@login'); // commented.
        Route::post('logout', 'AuthController@logout');
        Route::post('refresh', 'AuthController@refresh');
        Route::post('me', 'AuthController@me');

    });

    Route::get("/like/{id}", [
        "uses" => "LikeController@like"
    ]);
    Route::get("/unlike/{id}", [
        "uses" => "LikeController@unlike"
    ]);

});


问:
Password field not taking keys using Selenium through Python
I am trying to send keys via selenium it is taking for username but not for password.

I have tried clicking and sending keys then.

HTML of password field:

```<code><div>
    <input name="txtPassword" type="password" id="txtPassword" required="" style="margin-bottom:0px;" class="blur">
    <a id="btnSmallForgotPassword" class="smallForgotPassword visible-sm-block" href="javascript:__doPostBack('btnSmallForgotPassword','')">forgot password</a>
</div>
</code>```

```<code>WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID,"txtPassword"))).click()
WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID,"txtPassword"))).send_keys("san")
</code>```

I am getting no error message but it is not sending keys for password

答:
The above code should work.However I have tested following code on chrome browser and working fine.

```<code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver

driver = webdriver.Chrome()
driver.get('http://backgriduk.medialava.com/pages/Staff/Login.aspx?LANGUAGE_ID=3&O=7')
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.ID,'txtUser'))).send_keys("Abhishek")
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'div.divInnerRightControls #txtPassword'))).send_keys("Abhishek")
</code>```

Output:

Body:
I am trying to send keys via selenium it is taking for username but not for password.

I have tried clicking and sending keys then.

HTML of password field:

    <input name="txtPassword" type="password" id="txtPassword" required="" style="margin-bottom:0px;" class="blur">
    forgot password

WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID,"txtPassword"))).click()
WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID,"txtPassword"))).send_keys("san")

I am getting no error message but it is not sending keys for password

Body:
The above code should work.However I have tested following code on chrome browser and working fine.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver

driver = webdriver.Chrome()
driver.get('http://backgriduk.medialava.com/pages/Staff/Login.aspx?LANGUAGE_ID=3&O=7')
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.ID,'txtUser'))).send_keys("Abhishek")
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'div.divInnerRightControls #txtPassword'))).send_keys("Abhishek")

Output:


问:
How to splice an image URL field returned by the server and load the img correctly in the vue?
This is an example,This is the data returned by the server:

```<code>[
{
        "Id":8,
        "Title":"123123",
        "Creatorid":1,
        "ImgUrl":"\upload\images\item\banner\1.jpeg",
        "Content":null
    },
    {
        "Id":9,
        "Title":"123",
        "Creatorid":1,
        "ImgUrl":"\upload\images\item\banner\2.jpeg",
        "Content":null
    },
    {
        "Id":10,
        "Title":"",
        "Creatorid":1,
        "ImgUrl":"\upload\images\item\banner\3.jpeg",
        "Content":null
    }
]
</code>```

this html:

```<code><el-table :data="homeTableData" style="width: 100%">
            <el-table-column label=“image” width="300">
              <template slot-scope="scope">
                <span>{{scope.row.ImgUrl}}</span>
                <img :src="getImage(scope.row.ImgUrl)" alt=“loding” style="width:50px; height:50px;">
              </template>
            </el-table-column>
</el-table>
</code>```

this js:

```<code>  methods: {

    getImage(src) {
      console.log(src);
      let temp = "test:8080/website/" + src;
      this.$axios
        .get(temp)
        .then(res => {
          console.log("ccc",res)
          return res;
        })
        .catch(error => {});
    }
}
</code>```

Now the problem is that img doesn't show images

The reason is that axios doesn't return anything. What should I do? Using synchronization?

but the content of the return is the Request URL:

http://localhost:8080/website/upload/images/item/banner/ [object % 20 promise]

How do you gracefully load images in a vue?

Can you help me?

答:
You are not returning anything from the function. Return the this.$axios request. Also, this request is asynchronous, so it would be best to wait for the function to return the data:

```<code>methods: {
    async getImage(src) {
      console.log(src);
      let temp = "test:8080/website/" + src;
      return await this.$axios
        .get(temp)
        .then(res => {
          console.log("ccc",res)
          return res;
        })
        .catch(error => {});
    }
}
</code>```

Body:
This is an example,This is the data returned by the server:

[
{
        "Id":8,
        "Title":"123123",
        "Creatorid":1,
        "ImgUrl":"\upload\images\item\banner\1.jpeg",
        "Content":null
    },
    {
        "Id":9,
        "Title":"123",
        "Creatorid":1,
        "ImgUrl":"\upload\images\item\banner\2.jpeg",
        "Content":null
    },
    {
        "Id":10,
        "Title":"",
        "Creatorid":1,
        "ImgUrl":"\upload\images\item\banner\3.jpeg",
        "Content":null
    }
]

this html:

<el-table :data="homeTableData" style="width: 100%">
            <el-table-column label=“image” width="300">
              <template slot-scope="scope">
                {{scope.row.ImgUrl}}

              </template>
            </el-table-column>
</el-table>

this js:

  methods: {

    getImage(src) {
      console.log(src);
      let temp = "test:8080/website/" + src;
      this.$axios
        .get(temp)
        .then(res => {
          console.log("ccc",res)
          return res;
        })
        .catch(error => {});
    }
}

Now the problem is that img doesn't show images

The reason is that axios doesn't return anything. What should I do? Using synchronization?

but the content of the return is the Request URL:

http://localhost:8080/website/upload/images/item/banner/ [object % 20 promise]

How do you gracefully load images in a vue?

Can you help me?

Body:
You are not returning anything from the function. Return the this.$axios request. Also, this request is asynchronous, so it would be best to wait for the function to return the data:

methods: {
    async getImage(src) {
      console.log(src);
      let temp = "test:8080/website/" + src;
      return await this.$axios
        .get(temp)
        .then(res => {
          console.log("ccc",res)
          return res;
        })
        .catch(error => {});
    }
}


问:
Unable to delete Apache Atlas Classification
I have a list of Classifications &  Sub-classifications in Apache Atlas. Want to delete them & create a new list.
All the other classifications are getting deleted but one of them with name "PII" giving following error when we select Delete Classification.

Error: Given type PII has references

When we do a search via Rest API using below URL:
http://ip.of.atlas:21000/api/atlas/v2/search/basic?classification=PII

Following Result comes:

```<code>{
    "queryType": "BASIC",
    "searchParameters": {
        "classification": "PII",
        "excludeDeletedEntities": false,
        "includeClassificationAttributes": false,
        "includeSubTypes": true,
        "includeSubClassifications": true,
        "limit": 100,
        "offset": 0
    },
    "entities": [
        {
            "typeName": "hive_table",
            "attributes": {
                "owner": "nifi",
                "createTime": 1557832055000,
                "qualifiedName": "demo.test_table@demopilot",
                "name": "test_table"
            },
            "guid": "ecb7bb24-bdde-448c-b718-07273e5ce572",
            "status": "DELETED",
            "displayText": "test_table",
            "classificationNames": [
                "PII"
            ],
            "meaningNames": [],
            "meanings": []
        },
        {
            "typeName": "hive_table",
            "attributes": {
                "owner": "nifi",
                "createTime": 1557832055000,
                "qualifiedName": "demo.test_table@demopilot",
                "name": "test_table"
            },
            "guid": "ed5a9284-c290-4431-ab76-27b820478e29",
            "status": "DELETED",
            "displayText": "test_table",
            "classificationNames": [
                "PII"
            ],
            "meaningNames": [],
            "meanings": []
        },
        {
            "typeName": "hive_column",
            "attributes": {
                "owner": "nifi",
                "qualifiedName": "demo.test_table.traffic_case@demopilot",
                "name": "traffic_case"
            },
            "guid": "73f75a6c-9f4e-41f0-b0ef-6c05ca132639",
            "status": "DELETED",
            "displayText": "traffic_case",
            "classificationNames": [
                "PII"
            ],
            "meaningNames": [],
            "meanings": []
        }
    ]
}
</code>```

Questions:
1. Is there a API which help to delete all Classifications irrespective of whether they are attached to Entity or not?
2. Delete Single Classification forcefully with Classification Name or GUID?

答:
Running below GET request:
http://ip.of.atlas:21000/api/atlas/v2/types/typedefs

& then Delete the guid attached to the typedefs

Body:
I have a list of Classifications &  Sub-classifications in Apache Atlas. Want to delete them & create a new list.
All the other classifications are getting deleted but one of them with name "PII" giving following error when we select Delete Classification.

Error: Given type PII has references

When we do a search via Rest API using below URL:
http://ip.of.atlas:21000/api/atlas/v2/search/basic?classification=PII

Following Result comes:

{
    "queryType": "BASIC",
    "searchParameters": {
        "classification": "PII",
        "excludeDeletedEntities": false,
        "includeClassificationAttributes": false,
        "includeSubTypes": true,
        "includeSubClassifications": true,
        "limit": 100,
        "offset": 0
    },
    "entities": [
        {
            "typeName": "hive_table",
            "attributes": {
                "owner": "nifi",
                "createTime": 1557832055000,
                "qualifiedName": "demo.test_table@demopilot",
                "name": "test_table"
            },
            "guid": "ecb7bb24-bdde-448c-b718-07273e5ce572",
            "status": "DELETED",
            "displayText": "test_table",
            "classificationNames": [
                "PII"
            ],
            "meaningNames": [],
            "meanings": []
        },
        {
            "typeName": "hive_table",
            "attributes": {
                "owner": "nifi",
                "createTime": 1557832055000,
                "qualifiedName": "demo.test_table@demopilot",
                "name": "test_table"
            },
            "guid": "ed5a9284-c290-4431-ab76-27b820478e29",
            "status": "DELETED",
            "displayText": "test_table",
            "classificationNames": [
                "PII"
            ],
            "meaningNames": [],
            "meanings": []
        },
        {
            "typeName": "hive_column",
            "attributes": {
                "owner": "nifi",
                "qualifiedName": "demo.test_table.traffic_case@demopilot",
                "name": "traffic_case"
            },
            "guid": "73f75a6c-9f4e-41f0-b0ef-6c05ca132639",
            "status": "DELETED",
            "displayText": "traffic_case",
            "classificationNames": [
                "PII"
            ],
            "meaningNames": [],
            "meanings": []
        }
    ]
}

Questions:
1. Is there a API which help to delete all Classifications irrespective of whether they are attached to Entity or not?
2. Delete Single Classification forcefully with Classification Name or GUID?


问:
Regex for ignoring first and last character
Trying to obfuscate an email to this format:

```<code>a***@******m
</code>```

Meaning I need a regex to match everything except first and last character, as well as @.
I can use [^@] for everything but how do I ignore the last and first characters in a String? Anchors seem like the way to go but what is the exact syntax?

答:
There is no language tagged, but if you are using a programming language and you want to make sure that there is an @ sign in the email address and that the first and last character are shown, you might use capturing groups and use replace on the groups that you want to show with an *:

```<code>^(\S)([^@\n]*)(@)([^@\n]*)(\S)$
</code>```

^ Start of string

(\S) Capture group 1, match a non whitespace char

([^@\s]*) Capture group 2, match 0+ times not an @ or a whitespace char

(@) Capture group 3, Match @

([^@\s]*) Capture group 4, match 0+ times not an @ or a whitespace char

(\S) Capture group 5, match a non whitespace char

$ End of string

Regex demo

For example using javascript

let pattern = /^(\S)([^@\s]*)(@)([^@\s]*)(\S)$/;
[
  "test@test.com",
  "te st@te st.com",
  "test@test@test.com",
  "te@nl",
  "t@t",
  "test@",
  "@tes",
  "test"
].forEach(str => {
  let replaced = str.replace(pattern, function(_, g1, g2, g3, g4, g5) {
    return g1 + g2.replace(/./g, "*") + g3 + g4.replace(/./g, "*") + g5;
  });
  console.log(replaced);
});```

Body:
Trying to obfuscate an email to this format:

a***@******m

Meaning I need a regex to match everything except first and last character, as well as @.
I can use [^@] for everything but how do I ignore the last and first characters in a String? Anchors seem like the way to go but what is the exact syntax?

Body:
There is no language tagged, but if you are using a programming language and you want to make sure that there is an @ sign in the email address and that the first and last character are shown, you might use capturing groups and use replace on the groups that you want to show with an *:

^(\S)([^@\n]*)(@)([^@\n]*)(\S)$

^ Start of string

(\S) Capture group 1, match a non whitespace char

([^@\s]*) Capture group 2, match 0+ times not an @ or a whitespace char

(@) Capture group 3, Match @

([^@\s]*) Capture group 4, match 0+ times not an @ or a whitespace char

(\S) Capture group 5, match a non whitespace char

$ End of string

Regex demo

For example using javascript

let pattern = /^(\S)([^@\s]*)(@)([^@\s]*)(\S)$/;
[
  "test@test.com",
  "te st@te st.com",
  "test@test@test.com",
  "te@nl",
  "t@t",
  "test@",
  "@tes",
  "test"
].forEach(str => {
  let replaced = str.replace(pattern, function(_, g1, g2, g3, g4, g5) {
    return g1 + g2.replace(/./g, "*") + g3 + g4.replace(/./g, "*") + g5;
  });
  console.log(replaced);
});