问:
Android - Error in getting user info from facebook login
In my application i am using facebook login to access my application. my problem is am not able to get the user info through facebook login am getting the null value.

Here is my callback

```<code>loginbutton.registerCallback(callback, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {

            Profile profile = Profile.getCurrentProfile();
            if(profile!=null){
            Log.e("User FirstName", profile.getFirstName());
        }
        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {

        }

    });
</code>```

Otherwise everything is working fine.

Can anyone help me out please.

答:
You can get profile details by calling async task from on success of facebook login</p>

```<code>@Override
    public void onSuccess(LoginResult result) {
        fetchProfileDetail(result.getAccessToken());

    }

    public void fetchProfileDetail(final AccessToken fbAccessToken) {
        GraphRequest request = GraphRequest.newMeRequest(fbAccessToken, new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject object, GraphResponse response) {
                try {
                    JSONObject jsonObject = response.getJSONObject();
                    String name = jsonObject.optString("first_name");
                    if(!jsonObject.optString("last_name").isEmpty()){
                        name+=" "+jsonObject.optString("last_name");
                    }
                    String fb_id = jsonObject.optString("id");
                    String emailId = jsonObject.optString("email");
                    String profileUrl = "";
                    if (jsonObject.has("picture")) {
                        JSONObject picture = jsonObject.getJSONObject("picture");
                        JSONObject picData = picture.getJSONObject("data");
                        profileUrl = picData.optString("url");
                    }

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

                }
            }
        });

        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,email,name,first_name,last_name,picture.height(300).width(300)");
        request.setParameters(parameters);
        request.executeAsync();
    }
</code>```

Body:
In my application i am using facebook login to access my application. my problem is am not able to get the user info through facebook login am getting the null value.

Here is my callback

loginbutton.registerCallback(callback, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {

            Profile profile = Profile.getCurrentProfile();
            if(profile!=null){
            Log.e("User FirstName", profile.getFirstName());
        }
        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {

        }

    });

Otherwise everything is working fine.

Can anyone help me out please.

Body:
You can get profile details by calling async task from on success of facebook login

@Override
    public void onSuccess(LoginResult result) {
        fetchProfileDetail(result.getAccessToken());

    }

    public void fetchProfileDetail(final AccessToken fbAccessToken) {
        GraphRequest request = GraphRequest.newMeRequest(fbAccessToken, new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject object, GraphResponse response) {
                try {
                    JSONObject jsonObject = response.getJSONObject();
                    String name = jsonObject.optString("first_name");
                    if(!jsonObject.optString("last_name").isEmpty()){
                        name+=" "+jsonObject.optString("last_name");
                    }
                    String fb_id = jsonObject.optString("id");
                    String emailId = jsonObject.optString("email");
                    String profileUrl = "";
                    if (jsonObject.has("picture")) {
                        JSONObject picture = jsonObject.getJSONObject("picture");
                        JSONObject picData = picture.getJSONObject("data");
                        profileUrl = picData.optString("url");
                    }

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

                }
            }
        });

        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,email,name,first_name,last_name,picture.height(300).width(300)");
        request.setParameters(parameters);
        request.executeAsync();
    }


来源: stackexchange

问:
Google Mail API
I have a google mail API and the users are logging in now by
going to a url like say: mail.xxxxx.edu.in. but i don't want my
users to  go to the login page provided by google (here:
mail.xxxxx.edu.in). Instead I want users to login directly to their
mailbox by entering details in the custom login control i have created
in my home page and then use google interface for email operations.

Can you please tell me if this is possible and if so, how.

答: Yes, it's possible, and here is the information you'll need on how to do it.</p>

ContentLicense: CC BY-SA 2.5

Title: Google Mail API


问:
PhotoEditorSDK : export to server without auto download?
I am using photoeditorsdk in my Angular app. There is an export to server function in the docs:

```<code>editor.export(
  PhotoEditorSDK.RenderType.DATAURL,
  PhotoEditorSDK.ImageFormat.JPEG,
  0.8 // JPEG quality: 80%
).then((dataUrl) => {
  // Upload to server
})
</code>```

I get the image dataUrl, but the image is also downloaded at the browser.  I want to prevent the download.

答: I got help from their support, in the configuration guide : https://docs.photoeditorsdk.com/guides/html5/v4-DesktopUI/introduction/configuration at the bottom is the export object, just need to pass download: false.

ContentLicense: CC BY-SA 4.0

Body:
I am using photoeditorsdk in my Angular app. There is an export to server function in the docs:

editor.export(
  PhotoEditorSDK.RenderType.DATAURL,
  PhotoEditorSDK.ImageFormat.JPEG,
  0.8 // JPEG quality: 80%
).then((dataUrl) => {
  // Upload to server
})

I get the image dataUrl, but the image is also downloaded at the browser.  I want to prevent the download.

ContentLicense: CC BY-SA 3.0


问:
Angular4 deletes entry from database but I have to reload page to see the results
After I press delete button, the message gets deleted from database but I have to refresh the page to see the message disappear from page.

dashboard.component.html

```<code><h2 *ngIf="user"> Hello, {{user.username}} </h2>
<a [routerLink]="['/']">Log Out</a>

<form (submit)="createMessage()">
<label>Message</label>
<input type="text" name="message" [(ngModel)]="message.message">
<input type="submit" value="create new message">
</form>

<div *ngFor="let message of messages">
<h1>{{message.userId.username}}</h1>
<h3>{{message.message}}</h3>
<h2 *ngIf="user.username === message.userId.username">
<form (submit) = "delete(message._id)">
    <button type="submit" name="" value="">DeleteOne</button>
</form>
</h2>
<hr>
</div>
</code>```

dashboard.component.ts

```<code>export class DashboardComponent implements OnInit {
messages: Message[] =[];
user: User;
message: Message = new Message();
currentId;

constructor(public _user: UserService, public _router:Router,private
_route: ActivatedRoute, private _message: MessageService) {
this.user = _user.currentUser;
this._route.params.subscribe((param)=>{
console.log("task details url id is: ", param.id);
this.currentId = param.id;
})
}

delete(val) {
console.log("delete method!", val);
 this._message.delete({id: val})
 .then((data)=>{
})
</code>```

答:
I guess _message.delete returns a promise here? One thing you could do is, when the promise resolves, reload your data (where the deleted record is not present anymore)

Here:

```<code>delete(val) {
console.log("delete method!", val);
 this._message.delete({id: val})
 .then((data)=>{
    // reload your messages
})
</code>```

Body:
After I press delete button, the message gets deleted from database but I have to refresh the page to see the message disappear from page.

dashboard.component.html

 Hello, {{user.username}}

Log Out

<form (submit)="createMessage()">
Message
<input type="text" name="message" [(ngModel)]="message.message">
<input type="submit" value="create new message">
</form>

{{message.userId.username}}

{{message.message}}

<form (submit) = "delete(message._id)">
    <button type="submit" name="" value="">DeleteOne</button>
</form>

dashboard.component.ts

export class DashboardComponent implements OnInit {
messages: Message[] =[];
user: User;
message: Message = new Message();
currentId;

constructor(public _user: UserService, public _router:Router,private
_route: ActivatedRoute, private _message: MessageService) {
this.user = _user.currentUser;
this._route.params.subscribe((param)=>{
console.log("task details url id is: ", param.id);
this.currentId = param.id;
})
}

delete(val) {
console.log("delete method!", val);
 this._message.delete({id: val})
 .then((data)=>{
})

Body:
I guess _message.delete returns a promise here? One thing you could do is, when the promise resolves, reload your data (where the deleted record is not present anymore)

Here:

delete(val) {
console.log("delete method!", val);
 this._message.delete({id: val})
 .then((data)=>{
    // reload your messages
})


问:
Styling Custom Checkbox with Image Not Appearing
I'm trying out HTML and CSS and am relatively new to the entire concept. I'm currently working on styling a custom checkbox using an image I made from Photoshop. I am not able to figure out why my image is not appearing when I set it this way.

HTML

```<code><ul id="myUL" class="ulChecklist">
  <form action="/action_page.php">
    <li><input type="checkbox" name="instruction">
      <label for="Step1">Step 1</label>
    </li>
    <li><input type="checkbox" name="instruction">
      <label for="Step2">Step 2</label>
    </li>
    <li><input type="checkbox" name="instruction">
      <label for="Step3">Step 3</label>
    </li>
  </form>
</ul>
</code>```

CSS

```<code>input[type="checkbox"] {
opacity: 0;
}

input[type="checkbox"] + label {
background: url(check.png) left center no-repeat;
}
</code>```

This is the pre-checked image I want to add.

This is the post-checked image I want to add.

As you can see, it isn't appearing.

Is something wrong with the way I write these codes? I've checked the following Lynda course link: https://www.lynda.com/HTML-tutorials/Styling-radio-buttons-check-boxes-images/612196/646907-4.html

But it isn't working out for me. I would greatly appreciate help from people! Thank you for taking your time to answer a noob's question!

答:
Try this.

ul{
  list-style:none;
}
input[type="checkbox"] {
  opacity: 0;
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: -1;
}

input[type="checkbox"] + label {
  background: url(https://i.stack.imgur.com/eiFBl.png) no-repeat 0 center;
  padding-left:60px;
  line-height:50px;
  display: inline-block;
  cursor:pointer;
}
input[type="checkbox"]:checked + label {
  background: url(https://i.stack.imgur.com/mCst2.png) no-repeat 0 center;
}
.check-wrap{
  position:relative;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="myUL" class="ulChecklist">
  <form action="/action_page.php">
    <li>
      <div class="check-wrap">
        <input type="checkbox" name="instruction" id="Step1">
        <label for="Step1">Step 1</label>
      </div>
    </li>
    <li>
      <div class="check-wrap">
        <input type="checkbox" name="instruction" id="Step2">
        <label for="Step2">Step 2</label>
      </div>
    </li>
    <li>
      <div class="check-wrap">
        <input type="checkbox" name="instruction" id="Step3">
        <label for="Step3">Step 3</label>
      </div>
    </li>
  </form>
</ul></code>```

Body:
I'm trying out HTML and CSS and am relatively new to the entire concept. I'm currently working on styling a custom checkbox using an image I made from Photoshop. I am not able to figure out why my image is not appearing when I set it this way.

HTML

  <form action="/action_page.php">

<input type="checkbox" name="instruction">
      Step 1

<input type="checkbox" name="instruction">
      Step 2

<input type="checkbox" name="instruction">
      Step 3

  </form>

CSS

input[type="checkbox"] {
opacity: 0;
}

input[type="checkbox"] + label {
background: url(check.png) left center no-repeat;
}

This is the pre-checked image I want to add.

This is the post-checked image I want to add.

As you can see, it isn't appearing.

Is something wrong with the way I write these codes? I've checked the following Lynda course link: https://www.lynda.com/HTML-tutorials/Styling-radio-buttons-check-boxes-images/612196/646907-4.html

But it isn't working out for me. I would greatly appreciate help from people! Thank you for taking your time to answer a noob's question!

Body:
Try this.

ul{
  list-style:none;
}
input[type="checkbox"] {
  opacity: 0;
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: -1;
}

input[type="checkbox"] + label {
  background: url(https://i.stack.imgur.com/eiFBl.png) no-repeat 0 center;
  padding-left:60px;
  line-height:50px;
  display: inline-block;
  cursor:pointer;
}
input[type="checkbox"]:checked + label {
  background: url(https://i.stack.imgur.com/mCst2.png) no-repeat 0 center;
}
.check-wrap{
  position:relative;
  display: inline-block;
}

<ul id="myUL" class="ulChecklist">
  <form action="/action_page.php">
    <li>
      <div class="check-wrap">
        <input type="checkbox" name="instruction" id="Step1">
        <label for="Step1">Step 1</label>
      </div>
    </li>
    <li>
      <div class="check-wrap">
        <input type="checkbox" name="instruction" id="Step2">
        <label for="Step2">Step 2</label>
      </div>
    </li>
    <li>
      <div class="check-wrap">
        <input type="checkbox" name="instruction" id="Step3">
        <label for="Step3">Step 3</label>
      </div>
    </li>
  </form>
</ul>


问:
Run Button Grayed out: Android Studio
Why is the run button always grayed out in android studio after I get some errors.
I need to restart/reboot my android studio every time to run it again. I am sure that I am missing something

Run bar:

Run Button:

I also get an error right now :)

```<code>Already disposed: Project (Disposed): Already disposed: Project (Disposed)
java.lang.AssertionError: Already disposed: Project (Disposed)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.getComponent(ComponentManagerImpl.java:186)
    at com.intellij.psi.PsiDocumentManager.getInstance(PsiDocumentManager.java:41)
    at com.intellij.psi.SingleRootFileViewProvider.getLastCommittedText(SingleRootFileViewProvider.java:521)
    at com.intellij.psi.SingleRootFileViewProvider.access$400(SingleRootFileViewProvider.java:63)
    at com.intellij.psi.SingleRootFileViewProvider$DocumentContent.getText(SingleRootFileViewProvider.java:537)
    at com.intellij.psi.SingleRootFileViewProvider.getContents(SingleRootFileViewProvider.java:347)
    at com.intellij.psi.impl.source.PsiFileImpl.loadTreeElement(PsiFileImpl.java:199)
    at com.intellij.psi.impl.source.PsiFileImpl.calcTreeElement(PsiFileImpl.java:776)
    at com.intellij.psi.impl.source.PsiFileImpl.getFirstChild(PsiFileImpl.java:787)
    at com.intellij.psi.impl.source.xml.XmlFileImpl.getDocument(XmlFileImpl.java:47)
    at com.intellij.psi.impl.source.xml.XmlFileImpl.getRootTag(XmlFileImpl.java:58)
    at com.android.tools.idea.rendering.LocalResourceRepository.getViewTag(LocalResourceRepository.java:323)
    at org.jetbrains.android.inspections.lint.IntellijViewTypeDetector.getViewTags(IntellijViewTypeDetector.java:42)
    at com.android.tools.lint.checks.ViewTypeDetector.visitMethod(ViewTypeDetector.java:213)
    at com.android.tools.lint.client.api.JavaVisitor$DelegatingJavaVisitor.visitMethodInvocation(JavaVisitor.java:1189)
    at lombok.ast.MethodInvocation.accept(MethodInvocation.java:114)
    at lombok.ast.Cast.accept(Cast.java:94)
    at lombok.ast.BinaryExpression.accept(BinaryExpression.java:131)
    at lombok.ast.ExpressionStatement.accept(ExpressionStatement.java:63)
    at lombok.ast.Block.accept(Block.java:106)
    at lombok.ast.MethodDeclaration.accept(MethodDeclaration.java:240)
    at lombok.ast.NormalTypeBody.accept(NormalTypeBody.java:57)
    at lombok.ast.ClassDeclaration.accept(ClassDeclaration.java:239)
    at lombok.ast.CompilationUnit.accept(CompilationUnit.java:83)
    at com.android.tools.lint.client.api.JavaVisitor.visitFile(JavaVisitor.java:217)
    at com.android.tools.lint.client.api.LintDriver.checkIndividualJavaFiles(LintDriver.java:1652)
    at com.android.tools.lint.client.api.LintDriver.runFileDetectors(LintDriver.java:986)
    at com.android.tools.lint.client.api.LintDriver.checkProject(LintDriver.java:858)
    at com.android.tools.lint.client.api.LintDriver.analyze(LintDriver.java:425)
    at com.android.tools.lint.client.api.LintDriver.analyze(LintDriver.java:369)
    at org.jetbrains.android.inspections.lint.AndroidLintExternalAnnotator.doAnnotate(AndroidLintExternalAnnotator.java:146)
    at org.jetbrains.android.inspections.lint.AndroidLintExternalAnnotator.doAnnotate(AndroidLintExternalAnnotator.java:56)
    at com.intellij.codeInsight.daemon.impl.ExternalToolPass.doAnnotate(ExternalToolPass.java:222)
    at com.intellij.codeInsight.daemon.impl.ExternalToolPass.access$400(ExternalToolPass.java:43)
    at com.intellij.codeInsight.daemon.impl.ExternalToolPass$2.run(ExternalToolPass.java:133)
    at com.intellij.codeInsight.daemon.impl.ExternalToolPass$3.run(ExternalToolPass.java:170)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:320)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:310)
    at com.intellij.util.ui.update.MergingUpdateQueue$2.run(MergingUpdateQueue.java:254)
    at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:269)
    at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:227)
    at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:217)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
    at com.intellij.util.Alarm$Request$1.run(Alarm.java:327)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at com.intellij.util.concurrency.QueueProcessor$RunnableConsumer.consume(QueueProcessor.java:298)
    at com.intellij.util.concurrency.QueueProcessor$RunnableConsumer.consume(QueueProcessor.java:295)
    at com.intellij.util.concurrency.QueueProcessor$2$1.run(QueueProcessor.java:110)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
    at com.intellij.util.concurrency.QueueProcessor$2.consume(QueueProcessor.java:107)
    at com.intellij.util.concurrency.QueueProcessor$2.consume(QueueProcessor.java:104)
    at com.intellij.util.concurrency.QueueProcessor$3$1.run(QueueProcessor.java:215)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
    at com.intellij.util.concurrency.QueueProcessor$3.run(QueueProcessor.java:212)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:419)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
    at com.intellij.openapi.application.impl.ApplicationImpl$1$1.run(ApplicationImpl.java:149)
</code>```

答:
Go to Run > Edit Configuration then go to Defaults > Android app" then in General tab select App in module then "Apply"
This is working for me.

Title: Run Button Grayed out: Android Studio

Body:
Why is the run button always grayed out in android studio after I get some errors.
I need to restart/reboot my android studio every time to run it again. I am sure that I am missing something

Run bar:

Run Button:

I also get an error right now :)

Already disposed: Project (Disposed): Already disposed: Project (Disposed)
java.lang.AssertionError: Already disposed: Project (Disposed)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.getComponent(ComponentManagerImpl.java:186)
    at com.intellij.psi.PsiDocumentManager.getInstance(PsiDocumentManager.java:41)
    at com.intellij.psi.SingleRootFileViewProvider.getLastCommittedText(SingleRootFileViewProvider.java:521)
    at com.intellij.psi.SingleRootFileViewProvider.access$400(SingleRootFileViewProvider.java:63)
    at com.intellij.psi.SingleRootFileViewProvider$DocumentContent.getText(SingleRootFileViewProvider.java:537)
    at com.intellij.psi.SingleRootFileViewProvider.getContents(SingleRootFileViewProvider.java:347)
    at com.intellij.psi.impl.source.PsiFileImpl.loadTreeElement(PsiFileImpl.java:199)
    at com.intellij.psi.impl.source.PsiFileImpl.calcTreeElement(PsiFileImpl.java:776)
    at com.intellij.psi.impl.source.PsiFileImpl.getFirstChild(PsiFileImpl.java:787)
    at com.intellij.psi.impl.source.xml.XmlFileImpl.getDocument(XmlFileImpl.java:47)
    at com.intellij.psi.impl.source.xml.XmlFileImpl.getRootTag(XmlFileImpl.java:58)
    at com.android.tools.idea.rendering.LocalResourceRepository.getViewTag(LocalResourceRepository.java:323)
    at org.jetbrains.android.inspections.lint.IntellijViewTypeDetector.getViewTags(IntellijViewTypeDetector.java:42)
    at com.android.tools.lint.checks.ViewTypeDetector.visitMethod(ViewTypeDetector.java:213)
    at com.android.tools.lint.client.api.JavaVisitor$DelegatingJavaVisitor.visitMethodInvocation(JavaVisitor.java:1189)
    at lombok.ast.MethodInvocation.accept(MethodInvocation.java:114)
    at lombok.ast.Cast.accept(Cast.java:94)
    at lombok.ast.BinaryExpression.accept(BinaryExpression.java:131)
    at lombok.ast.ExpressionStatement.accept(ExpressionStatement.java:63)
    at lombok.ast.Block.accept(Block.java:106)
    at lombok.ast.MethodDeclaration.accept(MethodDeclaration.java:240)
    at lombok.ast.NormalTypeBody.accept(NormalTypeBody.java:57)
    at lombok.ast.ClassDeclaration.accept(ClassDeclaration.java:239)
    at lombok.ast.CompilationUnit.accept(CompilationUnit.java:83)
    at com.android.tools.lint.client.api.JavaVisitor.visitFile(JavaVisitor.java:217)
    at com.android.tools.lint.client.api.LintDriver.checkIndividualJavaFiles(LintDriver.java:1652)
    at com.android.tools.lint.client.api.LintDriver.runFileDetectors(LintDriver.java:986)
    at com.android.tools.lint.client.api.LintDriver.checkProject(LintDriver.java:858)
    at com.android.tools.lint.client.api.LintDriver.analyze(LintDriver.java:425)
    at com.android.tools.lint.client.api.LintDriver.analyze(LintDriver.java:369)
    at org.jetbrains.android.inspections.lint.AndroidLintExternalAnnotator.doAnnotate(AndroidLintExternalAnnotator.java:146)
    at org.jetbrains.android.inspections.lint.AndroidLintExternalAnnotator.doAnnotate(AndroidLintExternalAnnotator.java:56)
    at com.intellij.codeInsight.daemon.impl.ExternalToolPass.doAnnotate(ExternalToolPass.java:222)
    at com.intellij.codeInsight.daemon.impl.ExternalToolPass.access$400(ExternalToolPass.java:43)
    at com.intellij.codeInsight.daemon.impl.ExternalToolPass$2.run(ExternalToolPass.java:133)
    at com.intellij.codeInsight.daemon.impl.ExternalToolPass$3.run(ExternalToolPass.java:170)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:320)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:310)
    at com.intellij.util.ui.update.MergingUpdateQueue$2.run(MergingUpdateQueue.java:254)
    at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:269)
    at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:227)
    at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:217)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
    at com.intellij.util.Alarm$Request$1.run(Alarm.java:327)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at com.intellij.util.concurrency.QueueProcessor$RunnableConsumer.consume(QueueProcessor.java:298)
    at com.intellij.util.concurrency.QueueProcessor$RunnableConsumer.consume(QueueProcessor.java:295)
    at com.intellij.util.concurrency.QueueProcessor$2$1.run(QueueProcessor.java:110)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
    at com.intellij.util.concurrency.QueueProcessor$2.consume(QueueProcessor.java:107)
    at com.intellij.util.concurrency.QueueProcessor$2.consume(QueueProcessor.java:104)
    at com.intellij.util.concurrency.QueueProcessor$3$1.run(QueueProcessor.java:215)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
    at com.intellij.util.concurrency.QueueProcessor$3.run(QueueProcessor.java:212)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:419)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
    at com.intellij.openapi.application.impl.ApplicationImpl$1$1.run(ApplicationImpl.java:149)


问:
Liferay 7: hidden aui input won't set value based on parameter
I have an entity with a primary key and two other fields.
I am able to display them in a Search Container in my primary View JSP, and I want to implement an edit/update function, so I created a different JSP for that. I pass the properties of the entity I wish to edit in portlet:renderURL portlet:param tags just like this:

```<code><portlet:renderURL var="editEntity">
    <portlet:param name="jspPage" value="/update-page.jsp" />
    <portlet:param name="primaryKey" value="<%= entityId %>" />
    <portlet:param name="name" value="<%= entityName%>" />
    <portlet:param name="description" value="<%= entityDesc%>" />
</portlet:renderURL>
</code>```

In the update-page JSP if I set any input field hidden, the parameter based values disappear, so the controller cannot process the fields' values.

i.e.:

```<code><aui:input name="primaryKey" type="hidden" value="${primaryKey}" />
<aui:input name="primaryKey" type="hidden" value="${name}" />
<aui:input name="primaryKey" type="hidden" value="${description}" />
</code>```

Note: I only want to hide the primary key field, the controller servlet should be able to process it and update my entity based on the primary key, like this:

```<code><aui:input name="primaryKey" type="text" value="${name}" />
<aui:input name="primaryKey" type="text" value="${description}" />
</code>```

The funny thing is, that everything just works when I set the input fields text type, but I wouldn't want the users to enter the primary key, duh...

Any ideas how could I fix this?

答:
I found a solution to the problem.

So, after long hours of testing I found out that I just could not get the values stored in parameters just as ${paramName} anywhere in a simple HTML tag, but I still don't know why.

What I did was request for the needed values stored within the parameters inside a JSP scriptlet just like this:

```<code><%
String primaryKey = request.getParameter("primaryKey");
String name = request.getParameter("name");
String description = request.getParameter("description");
%>
</code>```

Then I was good to go with my form:

```<code><aui:form action="<%= updateAbbreviationURL %>" method="post">
    <aui:input name="primaryKey" type="hidden" value="<%= primaryKey %>" />
    <aui:input name="entityName" label="Name" type="text" value="<%= name %>" />
    <aui:input name="entityDesc" label="Description" type="text" value="<%= description %>" />
    <aui:button name="submit" value="submit" type="submit" />
    <aui:button name="cancel" value="cancel" type="button" onClick="<%= viewURL %>" />
</aui:form>
</code>```

I'd be really grateful if someone told me why my initial implementation didn't work, I mean referring to the parameter values as mentioned above, ${paramName}

Thanks in advance!

Body:
I have an entity with a primary key and two other fields.
I am able to display them in a Search Container in my primary View JSP, and I want to implement an edit/update function, so I created a different JSP for that. I pass the properties of the entity I wish to edit in portlet:renderURL portlet:param tags just like this:

<portlet:renderURL var="editEntity">
    <portlet:param name="jspPage" value="/update-page.jsp" />
    <portlet:param name="primaryKey" value="<%= entityId %>" />
    <portlet:param name="name" value="<%= entityName%>" />
    <portlet:param name="description" value="<%= entityDesc%>" />
</portlet:renderURL>

In the update-page JSP if I set any input field hidden, the parameter based values disappear, so the controller cannot process the fields' values.

i.e.:

<aui:input name="primaryKey" type="hidden" value="${primaryKey}" />
<aui:input name="primaryKey" type="hidden" value="${name}" />
<aui:input name="primaryKey" type="hidden" value="${description}" />

Note: I only want to hide the primary key field, the controller servlet should be able to process it and update my entity based on the primary key, like this:

<aui:input name="primaryKey" type="text" value="${name}" />
<aui:input name="primaryKey" type="text" value="${description}" />

The funny thing is, that everything just works when I set the input fields text type, but I wouldn't want the users to enter the primary key, duh...

Any ideas how could I fix this?

Body:
I found a solution to the problem.

So, after long hours of testing I found out that I just could not get the values stored in parameters just as ${paramName} anywhere in a simple HTML tag, but I still don't know why.

What I did was request for the needed values stored within the parameters inside a JSP scriptlet just like this:

<%
String primaryKey = request.getParameter("primaryKey");
String name = request.getParameter("name");
String description = request.getParameter("description");
%>

Then I was good to go with my form:

<aui:form action="<%= updateAbbreviationURL %>" method="post">
    <aui:input name="primaryKey" type="hidden" value="<%= primaryKey %>" />
    <aui:input name="entityName" label="Name" type="text" value="<%= name %>" />
    <aui:input name="entityDesc" label="Description" type="text" value="<%= description %>" />
    <aui:button name="submit" value="submit" type="submit" />
    <aui:button name="cancel" value="cancel" type="button" onClick="<%= viewURL %>" />
</aui:form>

I'd be really grateful if someone told me why my initial implementation didn't work, I mean referring to the parameter values as mentioned above, ${paramName}

Thanks in advance!


问:
Android Development: Save
In my webview there is no long click and show up a context menu where i can save link as save image and so on.

Here is my work so far:

```<code>registerForContextMenu(mWebView);

public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Menu");
        menu.add(0, v.getId(), 0, "Save As... Or save image");

}

@Override
public boolean onContextItemSelected(MenuItem item) {
        if(item.getTitle()=="Action 1"){function1(item.getItemId());}

    else {return false;}
return true;
}
public void function1(int id){
    // HOW DO I SAVE??
    }
</code>```

SO i cannot really find a working code how to save the selected online image...!
Can you guys help me out?
And have i done the context menu wrong??

Thank you!

答:
When you register for a context menu you need to specify which element in your view you're registering your context view for. mWebView could be referring to the entire view in general and not solely the links on the page. Have you checked this?

For example consider this:

```<code>    GridView gridView = (GridView) findViewById(R.id.gridview);
    registerForContextMenu(gridView);
</code>```

In this example, i am  registering the GridView part of my entire view to the context menu, so only when the items in the GridView are pressed for long enough, the context menu appears.

Title: Android Development: Save

Body:
In my webview there is no long click and show up a context menu where i can save link as save image and so on.

Here is my work so far:

registerForContextMenu(mWebView);

public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Menu");
        menu.add(0, v.getId(), 0, "Save As... Or save image");

}

@Override
public boolean onContextItemSelected(MenuItem item) {
        if(item.getTitle()=="Action 1"){function1(item.getItemId());}

    else {return false;}
return true;
}
public void function1(int id){
    // HOW DO I SAVE??
    }

SO i cannot really find a working code how to save the selected online image...!
Can you guys help me out?
And have i done the context menu wrong??

Thank you!

Body:
When you register for a context menu you need to specify which element in your view you're registering your context view for. mWebView could be referring to the entire view in general and not solely the links on the page. Have you checked this?

For example consider this:

    GridView gridView = (GridView) findViewById(R.id.gridview);
    registerForContextMenu(gridView);

In this example, i am  registering the GridView part of my entire view to the context menu, so only when the items in the GridView are pressed for long enough, the context menu appears.


问:
How to link my static library to my c++ project CMake?
I'm using CLion with CMake. I have my own static library "libxxx.a".
I'm trying to link it this way in CMakeLists.txt:
target_link_libraries(myProject ./lib/libxxx.a)
And this way I'm including library to my main.cpp.
#include "xxx.h".
But I have error fatal error: xxx.h: No such file or directory.
What should I do?

答:
CMake include a prebuilt static library

As a sketch you need your project to look something like this

```<code>project( myProject )

set( SOURCE_FILES main.cpp )

add_library( myLibrary STATIC IMPORTED )
set_property( TARGET myLibrary PROPERTY IMPORTED_LOCATION /path/to/lib/libxxx.a )
include_directories( /path/to/headers/ )

add_executable( myProject ${SOURCE_FILES} )
target_link_libraries( myProject myLibrary )
</code>```

You might be able to replace include_directories with:

```<code>set_property( TARGET myLibrary PROPERTY INCLUDE_DIRECTORIES /path/to/headers/ )
</code>```

A better way to go is to compile the static library from source and then use

```<code>target_include_directories( myLibrary PUBLIC /path/to/headers/ )
</code>```

And then they get handled automatically.

Body:
CMake include a prebuilt static library

As a sketch you need your project to look something like this

project( myProject )

set( SOURCE_FILES main.cpp )

add_library( myLibrary STATIC IMPORTED )
set_property( TARGET myLibrary PROPERTY IMPORTED_LOCATION /path/to/lib/libxxx.a )
include_directories( /path/to/headers/ )

add_executable( myProject ${SOURCE_FILES} )
target_link_libraries( myProject myLibrary )

You might be able to replace include_directories with:

set_property( TARGET myLibrary PROPERTY INCLUDE_DIRECTORIES /path/to/headers/ )

A better way to go is to compile the static library from source and then use

target_include_directories( myLibrary PUBLIC /path/to/headers/ )

And then they get handled automatically.


问:
How do I fetch the value from a key in firebase for my android app?
I am very new to firebase and I am unable to fetch the content of the key value. I tried out few things but all were unsuccessful.

Can anyone help me out in fetching the data please?

My firebase database - Firebase Database Structure:

My code -

```<code>public class Dashboard extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private Toolbar dashboard_toolbar;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mActionBarDrawerToggle;
    private FirebaseAuth mAuth;
    DatabaseReference rootRef, teacher, teacherPost;

    String str;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);

      /*  str = (String) getIntent().getExtras().get("temp");*/
        textView = (TextView) findViewById(R.id.institute_news);

        mAuth = FirebaseAuth.getInstance();
        dashboard_toolbar = (Toolbar) findViewById(R.id.dashboard_toolbar);
        setSupportActionBar(dashboard_toolbar);
        getSupportActionBar().setTitle("Dashboard");
        dashboard_toolbar.setTitleTextColor(0xFFFFFFFF);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawable);
        mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, dashboard_toolbar, R.string.open, R.string.close);
        mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
        mDrawerLayout.addDrawerListener(mActionBarDrawerToggle);
        mActionBarDrawerToggle.syncState();

        dashboard_toolbar.post(new Runnable() {
            @Override
            public void run() {
                Drawable d = ResourcesCompat.getDrawable(getResources(), R.drawable.actionmenu, null);
                dashboard_toolbar.setNavigationIcon(d);
            }
        });

        NavigationView navigationView = (NavigationView) mDrawerLayout.findViewById(R.id.navigationView);
        navigationView.setNavigationItemSelectedListener(this);

        rootRef = FirebaseDatabase.getInstance().getReference();
        teacher = rootRef.child("admin").child("classPost");
        teacherPost = teacher.child("post");

        String mGroupId = teacherPost.push().getKey();
        Toast.makeText(this, "" + teacherPost, Toast.LENGTH_SHORT).show();
        textView.setText(mGroupId);

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawable);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.nav_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mActionBarDrawerToggle.onOptionsItemSelected(item))
            return  true;
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.aboutUs) {

        } else if (id == R.id.help) {

        } else if (id == R.id.report) {

        } else if (id == R.id.logoutmenu) {

            mAuth.signOut();
            sendToStart();
        } else if (id == R.id.setting) {

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawable);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void getAttendance(View view) {
        Toast.makeText(this, "Attendance Details Apk Fire here", Toast.LENGTH_LONG).show();
    }

    public void trackChild(View view) {

        Toast.makeText(this, "child tracker apk fire here Here", Toast.LENGTH_LONG).show();
    }

    public void getEwallet(View view) {

        Toast.makeText(this, "Ewallet Apk Fire Here", Toast.LENGTH_LONG).show();

    }

    public void getHealth(View view) {
        Toast.makeText(this, "Health apk fire here", Toast.LENGTH_LONG).show();

    }

    public void getMessageBoardDetails(View view) {
        startActivity(new Intent(this,MessageBoard.class));
    }

    public void startChat(View view) {

        startActivity(new Intent(this,Chat.class));
    }

    private void sendToStart() {
        startActivity(new Intent(Dashboard.this,Start.class));
        finish();
    }

    public void readMore(View view) {

        startActivity(new Intent(this,InstituteMessageBoard.class));
    }
}
</code>```

答:
To achieve this, please use the following code:</p>

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference classPostRef = rootRef.child("admin").child("classPost");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String post = ds.child("post").getValue(String.class);
            Log.d("TAG", post);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
classPostRef.addListenerForSingleValueEvent(eventListener);
</code>```

Body:
I am very new to firebase and I am unable to fetch the content of the key value. I tried out few things but all were unsuccessful.

Can anyone help me out in fetching the data please?

My firebase database - Firebase Database Structure:

My code -

public class Dashboard extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private Toolbar dashboard_toolbar;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mActionBarDrawerToggle;
    private FirebaseAuth mAuth;
    DatabaseReference rootRef, teacher, teacherPost;

    String str;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);

      /*  str = (String) getIntent().getExtras().get("temp");*/
        textView = (TextView) findViewById(R.id.institute_news);

        mAuth = FirebaseAuth.getInstance();
        dashboard_toolbar = (Toolbar) findViewById(R.id.dashboard_toolbar);
        setSupportActionBar(dashboard_toolbar);
        getSupportActionBar().setTitle("Dashboard");
        dashboard_toolbar.setTitleTextColor(0xFFFFFFFF);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawable);
        mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, dashboard_toolbar, R.string.open, R.string.close);
        mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
        mDrawerLayout.addDrawerListener(mActionBarDrawerToggle);
        mActionBarDrawerToggle.syncState();

        dashboard_toolbar.post(new Runnable() {
            @Override
            public void run() {
                Drawable d = ResourcesCompat.getDrawable(getResources(), R.drawable.actionmenu, null);
                dashboard_toolbar.setNavigationIcon(d);
            }
        });

        NavigationView navigationView = (NavigationView) mDrawerLayout.findViewById(R.id.navigationView);
        navigationView.setNavigationItemSelectedListener(this);

        rootRef = FirebaseDatabase.getInstance().getReference();
        teacher = rootRef.child("admin").child("classPost");
        teacherPost = teacher.child("post");

        String mGroupId = teacherPost.push().getKey();
        Toast.makeText(this, "" + teacherPost, Toast.LENGTH_SHORT).show();
        textView.setText(mGroupId);

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawable);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.nav_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mActionBarDrawerToggle.onOptionsItemSelected(item))
            return  true;
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.aboutUs) {

        } else if (id == R.id.help) {

        } else if (id == R.id.report) {

        } else if (id == R.id.logoutmenu) {

            mAuth.signOut();
            sendToStart();
        } else if (id == R.id.setting) {

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawable);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void getAttendance(View view) {
        Toast.makeText(this, "Attendance Details Apk Fire here", Toast.LENGTH_LONG).show();
    }

    public void trackChild(View view) {

        Toast.makeText(this, "child tracker apk fire here Here", Toast.LENGTH_LONG).show();
    }

    public void getEwallet(View view) {

        Toast.makeText(this, "Ewallet Apk Fire Here", Toast.LENGTH_LONG).show();

    }

    public void getHealth(View view) {
        Toast.makeText(this, "Health apk fire here", Toast.LENGTH_LONG).show();

    }

    public void getMessageBoardDetails(View view) {
        startActivity(new Intent(this,MessageBoard.class));
    }

    public void startChat(View view) {

        startActivity(new Intent(this,Chat.class));
    }

    private void sendToStart() {
        startActivity(new Intent(Dashboard.this,Start.class));
        finish();
    }

    public void readMore(View view) {

        startActivity(new Intent(this,InstituteMessageBoard.class));
    }
}

Body:
To achieve this, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference classPostRef = rootRef.child("admin").child("classPost");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String post = ds.child("post").getValue(String.class);
            Log.d("TAG", post);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
classPostRef.addListenerForSingleValueEvent(eventListener);


问:
Centering the navbar links
I have tried most of the approach, but I'm unable to center align the links in my navbar.

.navbar-nav {
  margin: 30px 20px !important;
}

a {
  /* color: #fff !important;*/
  font-family: 'Caesar Dressing';
  font-size: 18px;
  padding: 10px 30px !important;
}

a:hover {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

.active {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<body>
  <div class="container-fluid bg">
    <nav class="navbar">
      <div class="container-fluid">
        <ul class="nav navbar-nav">
          <li class="active">Home</li>
          <li>About</li>
          <li>Education</li>
          <li>Contact</li>
        </ul>
      </div>
    </nav>
  </div>
</body></code>```

this is what I'm getting

But I want all the 4 links to be vertically centered on the screen

答:
Use this CSS,

```<code> .navbar-nav{
   position: relative;
   left: 50%;
   transform: translateX(-50%);
 }
 .navbar-nav > li{
   margin: 0 5px;
   display: inline-block;
   vertical-align: top;
 }
 .navbar-nav > li > a {
   margin: 5px 0;
   background-color: #ccc;
 }
</code>```

https://jsbin.com/qovilonagu/1/edit?html,css,output

Title: Centering the navbar links

Body:
I have tried most of the approach, but I'm unable to center align the links in my navbar.

.navbar-nav {
  margin: 30px 20px !important;
}

a {
  /* color: #fff !important;*/
  font-family: 'Caesar Dressing';
  font-size: 18px;
  padding: 10px 30px !important;
}

a:hover {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

.active {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

Home

About

Education

Contact

this is what I'm getting

But I want all the 4 links to be vertically centered on the screen

Body:
Use this CSS,

 .navbar-nav{
   position: relative;
   left: 50%;
   transform: translateX(-50%);
 }
 .navbar-nav > li{
   margin: 0 5px;
   display: inline-block;
   vertical-align: top;
 }
 .navbar-nav > li > a {
   margin: 5px 0;
   background-color: #ccc;
 }

https://jsbin.com/qovilonagu/1/edit?html,css,output


问:
Appbar not hiding when recyclerview scrolled
I am trying to hide appbar when user scrolled recyclerview layout code as per follows:

```<code> <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/my_appbar_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <include
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                layout="@layout/plp_header_card_view"
                app:layout_scrollFlags="scroll|enterAlways" />
        </LinearLayout>
    </android.support.design.widget.AppBarLayout>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/item_list_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:scrollbars="none" />
</android.support.design.widget.CoordinatorLayout>
</code>```

I want to hide appbar when this screen intialize & show appbar when user scroll the recyclerview. Please help me to do this one.

答:
The below code is proper way to make toolbar hide when the scroll down.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/tabanim_appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/tabanim_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways|snap"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
</code>```

Body:
I am trying to hide appbar when user scrolled recyclerview layout code as per follows:

 <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/my_appbar_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <include
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                layout="@layout/plp_header_card_view"
                app:layout_scrollFlags="scroll|enterAlways" />
        </LinearLayout>
    </android.support.design.widget.AppBarLayout>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/item_list_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:scrollbars="none" />
</android.support.design.widget.CoordinatorLayout>

I want to hide appbar when this screen intialize & show appbar when user scroll the recyclerview. Please help me to do this one.

Body:
The below code is proper way to make toolbar hide when the scroll down.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/tabanim_appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/tabanim_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways|snap"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>


问:
Raw Input an alternative keyboard hook?
Quick question --

I was reading about keyboard hooks and one suggested using Raw Input to do this, yet I havn't found any example of it.
For example I am using

```<code>RAWINPUTDEVICE rid[1];
rid[0].usUsagePage = 0x01;
rid[0].usUsage = 0x06;
rid[0].hwndTarget = hWnd;
rid[0].dwFlags = 0;
RegisterRawInputDevices(rid, 1, sizeof(rid[0]));
</code>```

And catchign WM_INPUT fine in the applications own window, but not outside the application. Is this possible outside the application or do you have to use WH_KEYBOARD or WH_KEYBOARD_LL? MSDN didn't make it clear if Raw Input could be made globally.

EDIT: I know about Hooks but I want to know if you can do it with Raw input too!

Cheers

答: A Windows hook is mechanism that one can use to intercept events before they reach an application. Filter functions (functions that receive events) are classified according to the event type. If one wants to attach to a Windows hook, the filter function has to be installed using SetWindowsHookEx. I have to mention that global hooks must be in a separate dll file. You can read more about hooks in MSDN.

Title: Raw Input an alternative keyboard hook?

Body:
Quick question --

I was reading about keyboard hooks and one suggested using Raw Input to do this, yet I havn't found any example of it.
For example I am using

RAWINPUTDEVICE rid[1];
rid[0].usUsagePage = 0x01;
rid[0].usUsage = 0x06;
rid[0].hwndTarget = hWnd;
rid[0].dwFlags = 0;
RegisterRawInputDevices(rid, 1, sizeof(rid[0]));

And catchign WM_INPUT fine in the applications own window, but not outside the application. Is this possible outside the application or do you have to use WH_KEYBOARD or WH_KEYBOARD_LL? MSDN didn't make it clear if Raw Input could be made globally.

EDIT: I know about Hooks but I want to know if you can do it with Raw input too!

Cheers


问:
How to use IF with And and OR in Excell?
I am using a FIFA 8 dataset for a project. There are various fields like age, rating, value and wage. Now I want to make a column of whether the player should be bought or not. I want to make this in Excel. I want to use a condition such as:

```<code>IF(Age<30 & Rating >90 & Value>100) OR If (Age<25 & Rating >85 & Value >70 ) then buy
</code>```

How can I use this kind of different situations in one formula in Excel?

答:
For Excel you can try following formula.

Column A is Age

Column B is Rating

Column C is Value

=IF(OR(AND(A2>30,B2>90,C2>100),AND(A2<25,B2>85,C2>70)),"buy","not buy")

Or visit https://www.extendoffice.com/documents/excel/2523-excel-if-and-or-not.html

Body:
I am using a FIFA 8 dataset for a project. There are various fields like age, rating, value and wage. Now I want to make a column of whether the player should be bought or not. I want to make this in Excel. I want to use a condition such as:

IF(Age<30 & Rating >90 & Value>100) OR If (Age<25 & Rating >85 & Value >70 ) then buy

How can I use this kind of different situations in one formula in Excel?


问:
Angular2 reflect-metadata shim is required when using class decorators
I’m trying to use the universal starter example to learn more about server rendering with Angular2, I want to use gulp instead of webpack.
The problem is when the server start I have :

```<code>/Users/jaumard/IdeaProjects/trails-angular2-isomorphic/node_modules/@angular/core/src/util/decorators.js:165
        throw 'reflect-metadata shim is required when using class decorators';
        ^
reflect-metadata shim is required when using class decorators
</code>```

I see some posts who said to add import 'reflect-metadata'; but that doesn’t fix the issue for me :( I think I miss something but can’t figure what it is...
Here is the code I use https://github.com/jaumard/trails-angular2-isomorphic

答:
This error is because, just like directive, your component HTML should be enclosed in a div.

```<code><div>
//html
</div>
</code>```

I got the same issue. When I enclose the HTML inside the div, it's working fine.

Body:
I’m trying to use the universal starter example to learn more about server rendering with Angular2, I want to use gulp instead of webpack.
The problem is when the server start I have :

/Users/jaumard/IdeaProjects/trails-angular2-isomorphic/node_modules/@angular/core/src/util/decorators.js:165
        throw 'reflect-metadata shim is required when using class decorators';
        ^
reflect-metadata shim is required when using class decorators

I see some posts who said to add import 'reflect-metadata'; but that doesn’t fix the issue for me :( I think I miss something but can’t figure what it is...
Here is the code I use https://github.com/jaumard/trails-angular2-isomorphic

Body:
This error is because, just like directive, your component HTML should be enclosed in a div.

<div>
//html
</div>

I got the same issue. When I enclose the HTML inside the div, it's working fine.


问:
Diffie-Hellman Parameters and safety
I Want to create my own safe connection for a VOIP app.

Now I am looking into key exchange which seems to be much more Tricky than encrypting/decrypting.

Are there any better approaches than Diffie-Hellman in practice ?

I understand the concept of Diffie-Hellman but I think it needs the right values to be safe since with natural numbers it could be easily be guessed. How can I get those values using python, what are they and is it really safe from key guessing?

Please help me with some background informations / inspiring.

答: Diffie-Hellman is a key exchange algorithm. So Anyone can access your public parameters. You can use safety except declassified private parameters. It's so important create sharedkey safety. If you want to more secure system, try forward-secrecy</p>

Title: Diffie-Hellman Parameters and safety


问:
BASH: Find number in text -> variable
I need little help from the community:

I have these two lines in a large text file:

```<code>Connected clients: 42
4 ACTIVE CLIENTS IN LAST 20 SECONDS
</code>```

How I can find, extract and assign the numbers to variables?

```<code>clients=42
active=4
</code>```

SED, AWK, GREP? Which one should I use?

答:
```<code>clients=$(grep -Po '^(?<=Connected clients: )([0-9]+)$' filename)
active=$(grep -Po '^([0-9]+)(?= ACTIVE CLIENTS IN LAST [0-9]+ SECONDS$)' filename)
</code>```

or

```<code>clients=$(sed -n 's/^Connected clients: \([0-9]\+\)$/\1/p' filename)
active=$(sed -n 's/^\([0-9]\+\) ACTIVE CLIENTS IN LAST [0-9]\+ SECONDS$/\1/p' filename)
</code>```

Title: BASH: Find number in text -> variable

Body:
I need little help from the community:

I have these two lines in a large text file:

Connected clients: 42
4 ACTIVE CLIENTS IN LAST 20 SECONDS

How I can find, extract and assign the numbers to variables?

clients=42
active=4

SED, AWK, GREP? Which one should I use?

Body:
clients=$(grep -Po '^(?<=Connected clients: )([0-9]+)$' filename)
active=$(grep -Po '^([0-9]+)(?= ACTIVE CLIENTS IN LAST [0-9]+ SECONDS$)' filename)

or

clients=$(sed -n 's/^Connected clients: \([0-9]\+\)$/\1/p' filename)
active=$(sed -n 's/^\([0-9]\+\) ACTIVE CLIENTS IN LAST [0-9]\+ SECONDS$/\1/p' filename)


问:
Unable to get the "Text" of the "element" using "Protractor"
Hi I am writing Protractor automation scripts for "Angular 4" application .

The development code is below.

```<code><!--Byndd Title div-->
            <div class="ui-g-12 ui-md-8 ui-lg-10">
                <div class="bynndTitleClass"  i18n="@@introductionBynddHeader">
                    BynddYour Information Together And CONNECT to the world  in an EFFICIENT way
                </div>
            </div>
</code>```

my protractor test script is below.

Page Object code :

```<code>//to return login page heading
    getLoginPageMainHeading(){
              return element(by.css('div[class="bynndTitleClass"]')).getText();
    }
</code>```

Spec code :

```<code> //Testcase1 : To open the "Login page" of the application
    it('should open the Login page' , ()=>{
        //To open the Login page
        page.loginPageDisplay();

        // to verify whether the Current page is Login page or not by comparing with Login page Main heading
        expect(page.getLoginPageMainHeading().toString()).toBe('BynddYour Information Together And CONNECT to the world  in an EFFICIENT way');
    });
</code>```

After execution it is displaying below error message.
W

```<code>1) should test certificate tab should open the Login page
  - Expected '[object Object]' to be 'BynddYour Information Together And CONNECT to the world  in an EFFICIENT way'.
</code>```

Can anyone help me how to solve this issue

答:
This solves my issue </p>

```<code>page.getLoginPageMainHeading().getText().then(function(value){
            expect(value).toEqual('BynddYour Information Together And CONNECT to the world in an EFFICIENT way');
        })
</code>```

Body:
Hi I am writing Protractor automation scripts for "Angular 4" application .

The development code is below.

                    BynddYour Information Together And CONNECT to the world  in an EFFICIENT way

my protractor test script is below.

Page Object code :

//to return login page heading
    getLoginPageMainHeading(){
              return element(by.css('div[class="bynndTitleClass"]')).getText();
    }

Spec code :

 //Testcase1 : To open the "Login page" of the application
    it('should open the Login page' , ()=>{
        //To open the Login page
        page.loginPageDisplay();

        // to verify whether the Current page is Login page or not by comparing with Login page Main heading
        expect(page.getLoginPageMainHeading().toString()).toBe('BynddYour Information Together And CONNECT to the world  in an EFFICIENT way');
    });

After execution it is displaying below error message.
W

1) should test certificate tab should open the Login page
  - Expected '[object Object]' to be 'BynddYour Information Together And CONNECT to the world  in an EFFICIENT way'.

Can anyone help me how to solve this issue

Body:
This solves my issue

page.getLoginPageMainHeading().getText().then(function(value){
            expect(value).toEqual('BynddYour Information Together And CONNECT to the world in an EFFICIENT way');
        })


问:
Django disabled field with initial data raises validation errors
I have a field in my form that is given an initial data and disabled if a user is staff (admin can choose from a list). I have this field disabled for staff with the code line below.

```<code>self.fields[''].disabled = True
</code>```

After uprading to django 1.11.7 it started raising validation errors. I tried making it read only with

self.fields[''].widget.attrs['readonly'] = True

Css becomes read only, but i can still make changes.

Is this a 1.11.7 bug or something has happened in the changes on how the disabled function works. I couldn't find anything new in the documentation

答: Not the best workaround but i managed to make it work. On the model field i made it  blank=True so it doesn't raise me empty field validation with disabled=True, then in the save method, i assigned the value i needed one more time.

Body:
I have a field in my form that is given an initial data and disabled if a user is staff (admin can choose from a list). I have this field disabled for staff with the code line below.

self.fields[''].disabled = True

After uprading to django 1.11.7 it started raising validation errors. I tried making it read only with

self.fields[''].widget.attrs['readonly'] = True

Css becomes read only, but i can still make changes.

Is this a 1.11.7 bug or something has happened in the changes on how the disabled function works. I couldn't find anything new in the documentation


问:
Cannot resolve rxjava2 with gradle 3.0
Hare is my app gradle:

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

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.atumanin.testandroidannotations"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.1.18"

        javaCompileOptions {
            annotationProcessorOptions {
                includeCompileClasspath true
            }
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'io.reactivex.rxjava2:rxjava:2.1.6'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
}
</code>```

and this is my project gradle:

```<code>buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

If I try to build project, I get error:

```<code>Could not resolve io.reactivex.rxjava2:rxjava:2.1.6.
</code>```

and

```<code>Could not resolve io.reactivex.rxjava2:rxandroid:2.0.1.
</code>```

I tried to clean, to rebuild the project and to invalidate cache. Nothing helps. I also tried to use compile instead of implementation. I also tried different versions of both libraries, also without success.

答:
It will give error because official release for rxjava is 2.1.5.

simply change below lines of code

```<code>implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.1.5'
</code>```

Official documentation

Title: Cannot resolve rxjava2 with gradle 3.0

Body:
Hare is my app gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.atumanin.testandroidannotations"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.1.18"

        javaCompileOptions {
            annotationProcessorOptions {
                includeCompileClasspath true
            }
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'io.reactivex.rxjava2:rxjava:2.1.6'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
}

and this is my project gradle:

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

If I try to build project, I get error:

Could not resolve io.reactivex.rxjava2:rxjava:2.1.6.

and

Could not resolve io.reactivex.rxjava2:rxandroid:2.0.1.

I tried to clean, to rebuild the project and to invalidate cache. Nothing helps. I also tried to use compile instead of implementation. I also tried different versions of both libraries, also without success.

Body:
It will give error because official release for rxjava is 2.1.5.

simply change below lines of code

implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.1.5'

Official documentation


问:
Meaning of H/5 in cron Jenkins
I have a job with as cron:

```<code>5 3,21 * * 1-5
</code>```

This will run my job at 03:05AM and 09:05PM. Now I read it's a best practice to use H.

I try:

```<code>H/5 3,21 * * 1-5
</code>```

What is the meaning now? Will this schedule a build in a range of 5 minutes or 5 minutes after 3AM and 21PM?

答:
The H will take a numeric hash of the Job name and use this to ensure that different jobs with the same cron settings do not all trigger at the same time. This is a form of Scheduling Jitter

H/5 in the first field means Every five minutes starting at some time between 0 and 4 minutes past the hour

So H/5 3,21 * * 1-5

is Every five minutes between 03:00 and 03:59 and then between 21:00 and 21:59 on Mon -> Fri but starting at some 'random' time between 03:00 and 03:04 and then the same number of minutes after 21:00

If you want to run once per hour between 03:00-03:59 and 21:00-21:59 on Mon -> Fri, you can use H 3,21 * * 1-5 where H will be replaced by some number between 0-59 depending on job name.

The user interface will tell you when the job will last have triggered and will next trigger

Title: Meaning of H/5 in cron Jenkins

Body:
I have a job with as cron:

5 3,21 * * 1-5

This will run my job at 03:05AM and 09:05PM. Now I read it's a best practice to use H.

I try:

H/5 3,21 * * 1-5

What is the meaning now? Will this schedule a build in a range of 5 minutes or 5 minutes after 3AM and 21PM?


问:
get rid of blank space around widgets in tkinter
I put widgets on a window with .grid and noticed that the widgets have space around them. I fixed that on canvas widget with highlightthickness but this doesn't work with button widgets. It doesn't look cool when you have grey window background and there's white space around buttons.
P.S. I use python3 on macos Sierra

```<code>root = Tk()
root.configure(bg='grey')

w = Canvas(root, width=150, height=150, highlightthickness=0)
w.grid(row=1, column=1, sticky="nsew")

clear_btn = Button(text="Clear", width=15, command=lambda: w.delete("all"))
clear_btn.grid(row=2, column=1)

root.mainloop()
</code>```

P.S. TKinter leaving borders around widgets that's what it looks like. The guy was advised to use highlightbackground, but when I screenshot widgets, I still have that blank space around the widget.

答:
I don't have OSX, so I cannot check, but I think that if you use ttk and a style different from the default one (like 'clam'), you might be able to configure things like you want.

```<code>import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.configure(bg='grey')

style = ttk.Style(root)
style.theme_use('clam')

w = tk.Canvas(root, width=150, height=150, highlightthickness=0)
w.grid(row=1, column=1, sticky="nsew")

clear_btn = ttk.Button(text="Clear", width=15, command=lambda: w.delete("all"))
clear_btn.grid(row=2, column=1)

root.mainloop()
</code>```

Body:
I put widgets on a window with .grid and noticed that the widgets have space around them. I fixed that on canvas widget with highlightthickness but this doesn't work with button widgets. It doesn't look cool when you have grey window background and there's white space around buttons.
P.S. I use python3 on macos Sierra

root = Tk()
root.configure(bg='grey')

w = Canvas(root, width=150, height=150, highlightthickness=0)
w.grid(row=1, column=1, sticky="nsew")

clear_btn = Button(text="Clear", width=15, command=lambda: w.delete("all"))
clear_btn.grid(row=2, column=1)

root.mainloop()

P.S. TKinter leaving borders around widgets that's what it looks like. The guy was advised to use highlightbackground, but when I screenshot widgets, I still have that blank space around the widget.

Body:
I don't have OSX, so I cannot check, but I think that if you use ttk and a style different from the default one (like 'clam'), you might be able to configure things like you want.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.configure(bg='grey')

style = ttk.Style(root)
style.theme_use('clam')

w = tk.Canvas(root, width=150, height=150, highlightthickness=0)
w.grid(row=1, column=1, sticky="nsew")

clear_btn = ttk.Button(text="Clear", width=15, command=lambda: w.delete("all"))
clear_btn.grid(row=2, column=1)

root.mainloop()


问:
Appium/Selenium TestNG Gradle DexArchiveBulderException Build Errors
I am an intermediate level tester who is currently exploring options for mobile automation. I am familiar with Appium/Selenium and am now attempting to introduce TestNG to manage test suites.

I have run into an error when attempting to build a simple project to begin mobile testing using TestNG and Appium/Selenium. I am unable to figure out how to fix this error.

Here is my build.gradle:

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

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.mikejohnson.testngtest"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9' // added this to resolve initial build conflict
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.0.1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'org.testng:testng:6.11' //added this
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'org.seleniumhq.selenium:selenium-java:3.7.1' //added this
    implementation 'io.appium:java-client:5.0.4' //added this
}
</code>```

Here is the error:

```<code>Information:Gradle tasks [clean, :app:assembleDebug]
Warning:Ignoring InnerClasses attribute for an anonymous inner class
Error:com.android.builder.dexing.DexArchiveBuilderException: Failed to process C:\Users\Mike.Johnson\.gradle\caches\modules-2\files-2.1\org.seleniumhq.selenium\selenium-firefox-driver\3.7.1\460c39abe149b7c649dd05dd71ab64ca80f738aa\selenium-firefox-driver-3.7.1.jar
Error:com.android.builder.dexing.DexArchiveBuilderException: Error while dexing org/openqa/selenium/firefox/FirefoxBinary.class
Error:com.android.dx.cf.code.SimException: invalid opcode ba (invokedynamic requires --min-sdk-version >= 26)
Error:Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process C:\Users\Mike.Johnson\.gradle\caches\modules-2\files-2.1\org.seleniumhq.selenium\selenium-firefox-driver\3.7.1\460c39abe149b7c649dd05dd71ab64ca80f738aa\selenium-firefox-driver-3.7.1.jar
Information:BUILD FAILED in 10s
Information:4 errors
Information:1 warning
Information:See complete output in console
</code>```

To get to this point all I have done is create a basic android project and attempted to add the required dependencies for TestNG and Appium/Selenium to build.gradle

The errors are introduced when combining the dependencies for TestNG and Appium/Selenium. The project is able to successfully build with just TestNG dependencies, or just Appium/Selenium dependencies. As soon as I combine TestNG along with Appium/Selenium, errors begin to appear.

I have searched and tried many possible solutions, however it always ends with a DexArchiveBulderException. I  do not have the experience to deduce what is going wrong with the dependencies, and there is very little information available on 'DexArchiveBuilderException' when searching.

If there is any other information I can provide, please let me know. Thank you for the assistance in advance.

答:
The initial problem is that you are trying to create Selenium tests inside Android project, at least it looks like you are adding dependencies to build.gradle in Android project.

And that is really strange way to start. Take look at official Appium java-client tests to get understanding how to design project

Body:
I am an intermediate level tester who is currently exploring options for mobile automation. I am familiar with Appium/Selenium and am now attempting to introduce TestNG to manage test suites.

I have run into an error when attempting to build a simple project to begin mobile testing using TestNG and Appium/Selenium. I am unable to figure out how to fix this error.

Here is my build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.mikejohnson.testngtest"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9' // added this to resolve initial build conflict
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.0.1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'org.testng:testng:6.11' //added this
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'org.seleniumhq.selenium:selenium-java:3.7.1' //added this
    implementation 'io.appium:java-client:5.0.4' //added this
}

Here is the error:

Information:Gradle tasks [clean, :app:assembleDebug]
Warning:Ignoring InnerClasses attribute for an anonymous inner class
Error:com.android.builder.dexing.DexArchiveBuilderException: Failed to process C:\Users\Mike.Johnson\.gradle\caches\modules-2\files-2.1\org.seleniumhq.selenium\selenium-firefox-driver\3.7.1\460c39abe149b7c649dd05dd71ab64ca80f738aa\selenium-firefox-driver-3.7.1.jar
Error:com.android.builder.dexing.DexArchiveBuilderException: Error while dexing org/openqa/selenium/firefox/FirefoxBinary.class
Error:com.android.dx.cf.code.SimException: invalid opcode ba (invokedynamic requires --min-sdk-version >= 26)
Error:Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.dexing.DexArchiveBuilderException: com.android.builder.dexing.DexArchiveBuilderException: Failed to process C:\Users\Mike.Johnson\.gradle\caches\modules-2\files-2.1\org.seleniumhq.selenium\selenium-firefox-driver\3.7.1\460c39abe149b7c649dd05dd71ab64ca80f738aa\selenium-firefox-driver-3.7.1.jar
Information:BUILD FAILED in 10s
Information:4 errors
Information:1 warning
Information:See complete output in console

To get to this point all I have done is create a basic android project and attempted to add the required dependencies for TestNG and Appium/Selenium to build.gradle

The errors are introduced when combining the dependencies for TestNG and Appium/Selenium. The project is able to successfully build with just TestNG dependencies, or just Appium/Selenium dependencies. As soon as I combine TestNG along with Appium/Selenium, errors begin to appear.

I have searched and tried many possible solutions, however it always ends with a DexArchiveBulderException. I  do not have the experience to deduce what is going wrong with the dependencies, and there is very little information available on 'DexArchiveBuilderException' when searching.

If there is any other information I can provide, please let me know. Thank you for the assistance in advance.


问:
how to show wordpress site title and tagline?
I'm trying to put site title and tagline in child theme header. I searched about it and find these two different wordpress functions get_bloginfo() and bloginfo().

get_bloginfo() doesn't showing the tagline, and bloginfo() showing both site title and tagline. Problem is that bloginfo() is removing the : and space between site title and description.

```<code><title><?php bloginfo( 'name' ) . ' : '. bloginfo( 'description' ); ?></title>
</code>```

Title: WebsiteThis is example website.

You can see there is no space between Website and This.

So is this possible that i show the site title and tagline with properly space and :?

答:
This will help you.

<title>
<?php
 $site_description = get_bloginfo( 'description', 'display' );
 $site_name = get_bloginfo( 'name' );
    //for home page
 if ( $site_description && ( is_home() || is_front_page() ) ):
  echo $site_name;echo ' | '; echo  $site_description;
 endif;
 // for other post pages
 if (!( is_home() ) && ! is_404() ):
 the_title(); echo ' | '; echo $site_name;
 endif;
 ?>
</title>```

Body:
I'm trying to put site title and tagline in child theme header. I searched about it and find these two different wordpress functions get_bloginfo() and bloginfo().

get_bloginfo() doesn't showing the tagline, and bloginfo() showing both site title and tagline. Problem is that bloginfo() is removing the : and space between site title and description.

<title><?php bloginfo( 'name' ) . ' : '. bloginfo( 'description' ); ?></title>

Title: WebsiteThis is example website.

You can see there is no space between Website and This.

So is this possible that i show the site title and tagline with properly space and :?


问:
How to get current module object from model in Yii2
I have module ticket.

Module class has propery UserClassName (string).

In this module I have model called Dialog.

Within this model, I want to get access to the module property UserClassName.

How I can get module object from my model Dialog?

P.S. From controllers I can do next: $this->module.

答:
I found a solution (I need same for me too). To get module object - very simple:</p>

```<code>\Yii::$app->getModule('moduleName')->propertyOrMethod;
</code>```

Body:
I found a solution (I need same for me too). To get module object - very simple:

\Yii::$app->getModule('moduleName')->propertyOrMethod;


问:
Correct way to display errors when a record cannot be found in the database
Currently, I have a model that has a method called getEmails($id=NULL).
If $id == NULL getEmails() uses fetchAll($select)->toArray() to return all the records in the email table. In the view I have an if statement that checks to see if the array returned is an empty array. If it is, it displays an error letting the user know that there are no emails to display, otherwise it goes through a foreach() loop to display all the emails.

In this case, is it correct to be using the the if statement to check if the email array is emapty? Or should I be doing it another way?

If $id != NULL getEmails uses the following code to return just one record:

```<code>        $select->where('id=?',$id);
        $row = $this->fetchRow($select)
        if(!$row) throw new Exception('Could not find email with ID '.$id);
        else return $row->toArray();
</code>```

As you can see, it throws an exception if the record could not be found.

I feel like there is a more unified way of displaying errors to the user when necessary.

Is it correct to throw an exception in the event that email with id $id cannot be found?

I'm trying to learn the "proper" way of doing things so thank you for all your help :-)

答:
You could use the Zend Framework Flash Messenger to display that error message to the user.

In the controller you could use the following code:

```<code>$this->_helper->flashMessenger->addMessage("Could not find email with ID $id");
</code>```

To display the message you could do the following:

In the controller you have to retrieve the messages:

```<code>$this->view->messages = $this->_helper->flashMessenger->getMessages();
</code>```

In the view script you want to display them:

```<code><?php if (count($this->messages)) : ?>
<ul id="messages">
<?php foreach ($this->messages as $message) : ?>
    <li><?php echo $this->escape($message); ?></li>
<?php endforeach; ?>
</div>
<?php endif; ?>
</code>```

This is a VERY basic example of how to use the flash messenger, but this would certainly get you on your way.

EDIT: After re-reading your question I realized (as I should have immediately) you were generating the error/exception from the model. You could test for null return value in the controller and send the message from there or you could create a session and store messages in there to be picked up and put into the flash messenger by the controller.

Body:
Currently, I have a model that has a method called getEmails($id=NULL).
If $id == NULL getEmails() uses fetchAll($select)->toArray() to return all the records in the email table. In the view I have an if statement that checks to see if the array returned is an empty array. If it is, it displays an error letting the user know that there are no emails to display, otherwise it goes through a foreach() loop to display all the emails.

In this case, is it correct to be using the the if statement to check if the email array is emapty? Or should I be doing it another way?

If $id != NULL getEmails uses the following code to return just one record:

        $select->where('id=?',$id);
        $row = $this->fetchRow($select)
        if(!$row) throw new Exception('Could not find email with ID '.$id);
        else return $row->toArray();

As you can see, it throws an exception if the record could not be found.

I feel like there is a more unified way of displaying errors to the user when necessary.

Is it correct to throw an exception in the event that email with id $id cannot be found?

I'm trying to learn the "proper" way of doing things so thank you for all your help :-)

Body:
You could use the Zend Framework Flash Messenger to display that error message to the user.

In the controller you could use the following code:

$this->_helper->flashMessenger->addMessage("Could not find email with ID $id");

To display the message you could do the following:

In the controller you have to retrieve the messages:

$this->view->messages = $this->_helper->flashMessenger->getMessages();

In the view script you want to display them:

<?php if (count($this->messages)) : ?>
<ul id="messages">
<?php foreach ($this->messages as $message) : ?>
    <li><?php echo $this->escape($message); ?></li>
<?php endforeach; ?>
</div>
<?php endif; ?>

This is a VERY basic example of how to use the flash messenger, but this would certainly get you on your way.

EDIT: After re-reading your question I realized (as I should have immediately) you were generating the error/exception from the model. You could test for null return value in the controller and send the message from there or you could create a session and store messages in there to be picked up and put into the flash messenger by the controller.


问:
Find high value transaction
I have a table structure as below -

```<code>Account Number | Transaction Type | Amount | Date
</code>```

Transaction type can be Credit or Debit. I need to check if either Credit or Debit transaction Amount is greater than some threshold value. If yes, check if the Amount is greater than Income * 10 (which is stored in some other table).

There could be multiple scenarios (Consider Credit threshold >= 10000, Debit Threshold >= 20000, Income = 1000) -

```<code>1. Account Number | Transaction Type | Amount | Date
   A1             | Credit           | 10000   | 11-11-2017
</code>```

No Debit row exists in this example, but A1 satisfies all conditions

```<code>2. Account Number | Transaction Type | Amount | Date
   A2             | Debit            | 20000   | 12-11-2017
</code>```

No Credit row exists in this example, but A2 satisfies all conditions

```<code>3. Account Number | Transaction Type | Amount | Date
   A3             | Credit           | 10000   | 13-11-2017
   A3             | Debit            | 5000    | 13-11-2017
</code>```

Both Credit and Debit row exists in this example, but A3 satisfies Credit conditions

```<code>4. Account Number | Transaction Type | Amount | Date
   A4             | Credit           | 5000   | 14-11-2017
   A4             | Debit            | 20000  | 14-11-2017
</code>```

Both Credit and Debit row exists in this example, but A4 satisfies Debit conditions

```<code>5. Account Number | Transaction Type | Amount | Date
   A5             | Credit           | 10000   | 15-11-2017
   A5             | Debit            | 20000   | 15-11-2017
</code>```

Both Credit and Debit row exists in this example, but A5 should satisfy Debit condition, as it has greater value (max needs to be taken in this case)

```<code>6. Account Number | Transaction Type | Amount | Date
   A6             | Credit           | 10000   | 16-11-2017
   A6             | Debit            | 20000   | 16-11-2017
</code>```

Consider Income = 3000 in this example, both Credit and Debit row exists in this example, but A6 should not satisfy any condition, as Income *10 is greater value than Credit/Debit transaction values.

I have already used UNION with LEFT & RIGHT joins to find both Credit/Debit values but finding if there is any better way to write this script. In case any Credit/Debit value do not exists, take it as zero. I am using SQL server 2012.

Script developed (on a high level) so far:

```<code>SELECT
temp.Number as Number,
temp.Amount1 as CrAmt,
temp.Amount2 as DrAmt
FROM
(
SELECT
    t1.Account_Number AS Number,
    t1.Amount AS Amount1,
    isnull(t2.Amount, 0) as Amount2
FROM
    TableName AS t1 WITH (NOLOCK) LEFT JOIN
    TableName AS t2 WITH (NOLOCK) on isnull(t2.Transaction_Type, 'Debit') = 'Debit' and isnull(t2.Account_Number,t1.Account_Number) = t1.Account_Number
WHERE
    t1.Transaction_Type = 'Credit'

UNION

SELECT
    t1.Account_Number AS Number,
    t1.Amount AS Amount1,
    isnull(t2.Amount, 0) as Amount2
FROM
    TableName AS t1 WITH (NOLOCK) RIGHT JOIN
    TableName AS t2 WITH (NOLOCK) on isnull(t2.Transaction_Type, 'Debit') = 'Debit' and isnull(t2.Account_Number,t1.Account_Number) = t1.Account_Number
WHERE
    t1.Transaction_Type = 'Credit'
) temp
where
(temp.Amount1 >= 10000 and temp.Amount1>= Income * 10) OR (temp.Amount2 >= 20000 and temp.Amount2>= Income * 10)
</code>```

答:
Here is a cleaner approach</p>

```<code>DECLARE @income       decimal(18, 2) = 1000*10,
        @CrThreshold  decimal(18, 2) = 10000,
        @DrThreshold  decimal(18, 2) = 20000

SELECT AccountNumber, CrAmt, DrAmt
FROM (
  SELECT AccountNumber,
         CrAmt = SUM(CASE WHEN TransactionType = 'Credit' THEN Amount ELSE 0 END),
         DrAmt = SUM(CASE WHEN TransactionType = 'Debit' THEN Amount ELSE 0 END)
  FROM TableName
  GROUP BY AccountNumber, [Date]) T
WHERE (CrAmt >= @CrThreshold AND CrAmt >= @income)
OR (DrAmt >= @DrThreshold AND DrAmt >= @income)
</code>```

Title: Find high value transaction

Body:
I have a table structure as below -

Account Number | Transaction Type | Amount | Date

Transaction type can be Credit or Debit. I need to check if either Credit or Debit transaction Amount is greater than some threshold value. If yes, check if the Amount is greater than Income * 10 (which is stored in some other table).

There could be multiple scenarios (Consider Credit threshold >= 10000, Debit Threshold >= 20000, Income = 1000) -

1. Account Number | Transaction Type | Amount | Date
   A1             | Credit           | 10000   | 11-11-2017

No Debit row exists in this example, but A1 satisfies all conditions

2. Account Number | Transaction Type | Amount | Date
   A2             | Debit            | 20000   | 12-11-2017

No Credit row exists in this example, but A2 satisfies all conditions

3. Account Number | Transaction Type | Amount | Date
   A3             | Credit           | 10000   | 13-11-2017
   A3             | Debit            | 5000    | 13-11-2017

Both Credit and Debit row exists in this example, but A3 satisfies Credit conditions

4. Account Number | Transaction Type | Amount | Date
   A4             | Credit           | 5000   | 14-11-2017
   A4             | Debit            | 20000  | 14-11-2017

Both Credit and Debit row exists in this example, but A4 satisfies Debit conditions

5. Account Number | Transaction Type | Amount | Date
   A5             | Credit           | 10000   | 15-11-2017
   A5             | Debit            | 20000   | 15-11-2017

Both Credit and Debit row exists in this example, but A5 should satisfy Debit condition, as it has greater value (max needs to be taken in this case)

6. Account Number | Transaction Type | Amount | Date
   A6             | Credit           | 10000   | 16-11-2017
   A6             | Debit            | 20000   | 16-11-2017

Consider Income = 3000 in this example, both Credit and Debit row exists in this example, but A6 should not satisfy any condition, as Income *10 is greater value than Credit/Debit transaction values.

I have already used UNION with LEFT & RIGHT joins to find both Credit/Debit values but finding if there is any better way to write this script. In case any Credit/Debit value do not exists, take it as zero. I am using SQL server 2012.

Script developed (on a high level) so far:

SELECT
temp.Number as Number,
temp.Amount1 as CrAmt,
temp.Amount2 as DrAmt
FROM
(
SELECT
    t1.Account_Number AS Number,
    t1.Amount AS Amount1,
    isnull(t2.Amount, 0) as Amount2
FROM
    TableName AS t1 WITH (NOLOCK) LEFT JOIN
    TableName AS t2 WITH (NOLOCK) on isnull(t2.Transaction_Type, 'Debit') = 'Debit' and isnull(t2.Account_Number,t1.Account_Number) = t1.Account_Number
WHERE
    t1.Transaction_Type = 'Credit'

UNION

SELECT
    t1.Account_Number AS Number,
    t1.Amount AS Amount1,
    isnull(t2.Amount, 0) as Amount2
FROM
    TableName AS t1 WITH (NOLOCK) RIGHT JOIN
    TableName AS t2 WITH (NOLOCK) on isnull(t2.Transaction_Type, 'Debit') = 'Debit' and isnull(t2.Account_Number,t1.Account_Number) = t1.Account_Number
WHERE
    t1.Transaction_Type = 'Credit'
) temp
where
(temp.Amount1 >= 10000 and temp.Amount1>= Income * 10) OR (temp.Amount2 >= 20000 and temp.Amount2>= Income * 10)

Body:
Here is a cleaner approach

DECLARE @income       decimal(18, 2) = 1000*10,
        @CrThreshold  decimal(18, 2) = 10000,
        @DrThreshold  decimal(18, 2) = 20000

SELECT AccountNumber, CrAmt, DrAmt
FROM (
  SELECT AccountNumber,
         CrAmt = SUM(CASE WHEN TransactionType = 'Credit' THEN Amount ELSE 0 END),
         DrAmt = SUM(CASE WHEN TransactionType = 'Debit' THEN Amount ELSE 0 END)
  FROM TableName
  GROUP BY AccountNumber, [Date]) T
WHERE (CrAmt >= @CrThreshold AND CrAmt >= @income)
OR (DrAmt >= @DrThreshold AND DrAmt >= @income)