问:
*ngIf/else not working Angular4
I'm having trouble getting using *ngIf/else statements to work. Here is the setup:

```<code><div *ngFor="let sub of day">
   <p>{{ sub.subject }}</p>
   <button type="button" *ngIf="sub.subject; else showElse" routerLink="/day" (click)="viewIndividual(day)" class="btn btn-{{colors[i]}}">View {{ daysBetween[i] | date:'EEEE' }}'s Plan</button>
   <ng-template #showElse>
      <a type="button" class="btn btn-primary">Add a Lesson</a>
   </ng-template>
</div>
</code>```

The issue is my truthy statement is rendering (the button with View {{ daysBetween[i] | date:'EEEE' }}'s Plan) on it, but my falsy value (the ng-template) is not. I've looked at a couple tutorials and I thought I am doing it right, but I've only been studying Angular4 for a few days now. Please help!

答:
You could either use a ngSwitch or, as you only have two cases, go directly for two ngIf:

```<code><div *ngFor="let sub of day">
   <p>{{ sub.subject }}</p>
   <button *ngIf="sub.subject" type="button" routerLink="/day" (click)="viewIndividual(day)" class="btn btn-{{colors[i]}}">View {{ daysBetween[i] | date:'EEEE' }}'s Plan</button>
   <a *ngIf="!sub.subject" type="button" class="btn btn-primary">Add a Lesson</a>
</div>
</code>```

Title: *ngIf/else not working Angular4

Body:
I'm having trouble getting using *ngIf/else statements to work. Here is the setup:

{{ sub.subject }}

   <button type="button" *ngIf="sub.subject; else showElse" routerLink="/day" (click)="viewIndividual(day)" class="btn btn-{{colors[i]}}">View {{ daysBetween[i] | date:'EEEE' }}'s Plan</button>
   <ng-template #showElse>
      Add a Lesson
   </ng-template>

The issue is my truthy statement is rendering (the button with View {{ daysBetween[i] | date:'EEEE' }}'s Plan) on it, but my falsy value (the ng-template) is not. I've looked at a couple tutorials and I thought I am doing it right, but I've only been studying Angular4 for a few days now. Please help!

Body:
You could either use a ngSwitch or, as you only have two cases, go directly for two ngIf:

<div *ngFor="let sub of day">
   <p>{{ sub.subject }}</p>
   <button *ngIf="sub.subject" type="button" routerLink="/day" (click)="viewIndividual(day)" class="btn btn-{{colors[i]}}">View {{ daysBetween[i] | date:'EEEE' }}'s Plan</button>
   <a *ngIf="!sub.subject" type="button" class="btn btn-primary">Add a Lesson</a>
</div>


来源: stackexchange

问:
Couldn't display buttons on hovering
I want to display a set of buttons when user hover over a particular button (Settings), I was able to do it when user hover over the current div element hide the particular button(Settings) and show the other buttons,

```<code><div class="md-card container">
    <p matLine><b>{{message.artifactId}}</b></p>
    <p matLine>
        {{message.groupId}}    {{message.version}}
        <button type="submit" class="btn btn-danger pull-right settingsbtn">
            <i class="material-icons">settings</i>
        </button>
        <a routerLink="/baseline-errors/{{message.id}}">
            <button type="submit" class="btn btn-danger pull-right listbtn">
                <i class="material-icons">content_paste</i>
            </button>
        </a>
        <button *ngIf="isScanning" type="submit" class="btn btn-danger pull-right spaceTest listbtn"
                (click)="rescanBaseline(message)">
            <i class="material-icons">refresh</i>
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="deleteBaseline(message)">
            <i class="material-icons">delete</i>
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="editBaseline(message)"><i
                class="material-icons">mode_edit</i>
        </button>
    </p>
    <mat-divider></mat-divider>
</div>
</code>```

CSS

```<code>.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

.container:hover .listbtn {
    opacity: 1;
}

.settingsbtn {
    opacity: 1;
    transition: opacity .35s ease;
}

.container:hover .settingsbtn {
    opacity: 0;
}
</code>```

This code works for div element but I want to change it to when user hover over the settings button rest will be shown, So I changed the code as this.

```<code><div class="md-card container">
    <p matLine><b>{{message.artifactId}}</b></p>
    <p matLine>
        {{message.groupId}}    {{message.version}}
        <span class="sd">
        <button type="submit" class="btn btn-danger pull-right settingsbtn">
        <i class="material-icons">settings</i>
        </button>
        <a routerLink="/baseline-errors/{{message.id}}">
            <button type="submit" class="btn btn-danger pull-right listbtn">
                <i class="material-icons">content_paste</i>
            </button>
        </a>
        <button *ngIf="isScanning" type="submit" class="btn btn-danger pull-right spaceTest listbtn"
                (click)="rescanBaseline(message)">
            <i class="material-icons">refresh</i>
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="deleteBaseline(message)">
            <i class="material-icons">delete</i>
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="editBaseline(message)"><i
                class="material-icons">mode_edit</i>
        </button>
        </span>
    </p>
    <mat-divider></mat-divider>
</div>
</code>```

CSS

```<code>.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

.sd:hover .listbtn {
    opacity: 1;
}

.settingsbtn {
    opacity: 1;
    transition: opacity .35s ease;
}

.sd:hover .settingsbtn {
    opacity: 0;
}
</code>```

But it didn't work, what is the mistake I am making here?

EDIT

I want to display the settings button initially and when user hovers over settings button it should be hidden and other buttons should be visible but when user hovers over other buttons initially it shouldn't show those buttons. My current code snippet will work as when user hovers over any button either settings or hidden it will show the  buttons.

答:
your code is working correctly, is this you want?

.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

.sd .settingsbtn:hover ~ .listbtn {
    opacity: 1;
}

.settingsbtn {
    opacity: 1;
    transition: opacity .35s ease;
}

.sd .settingsbtn:hover {
    opacity: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="sd">
<button type="submit" class="btn btn-danger pull-right settingsbtn">
<i class="material-icons">settings</i>
</button>
<button type="submit" class="btn btn-danger pull-right listbtn">
<i class="material-icons">content_paste</i>
</button>
<button type="submit" class="btn btn-danger pull-right listbtn">
<i class="material-icons">refresh</i>
</button>
<button type="submit" class="btn btn-danger pull-right listbtn">
<i class="material-icons">delete</i>
</button>
<button type="submit" class="btn btn-danger pull-right listbtn">
<i class="material-icons">mode_edit</i>
</button>
</span></code>```

ContentLicense: CC BY-SA 3.0

Title: Couldn't display buttons on hovering

Body:
I want to display a set of buttons when user hover over a particular button (Settings), I was able to do it when user hover over the current div element hide the particular button(Settings) and show the other buttons,

{{message.artifactId}}

        {{message.groupId}}    {{message.version}}
        <button type="submit" class="btn btn-danger pull-right settingsbtn">
            settings
        </button>

            <button type="submit" class="btn btn-danger pull-right listbtn">
                content_paste
            </button>

        <button *ngIf="isScanning" type="submit" class="btn btn-danger pull-right spaceTest listbtn"
                (click)="rescanBaseline(message)">
            refresh
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="deleteBaseline(message)">
            delete
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="editBaseline(message)">mode_edit
        </button>

    <mat-divider></mat-divider>

CSS

.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

.container:hover .listbtn {
    opacity: 1;
}

.settingsbtn {
    opacity: 1;
    transition: opacity .35s ease;
}

.container:hover .settingsbtn {
    opacity: 0;
}

This code works for div element but I want to change it to when user hover over the settings button rest will be shown, So I changed the code as this.

{{message.artifactId}}

        {{message.groupId}}    {{message.version}}

        <button type="submit" class="btn btn-danger pull-right settingsbtn">
        settings
        </button>

            <button type="submit" class="btn btn-danger pull-right listbtn">
                content_paste
            </button>

        <button *ngIf="isScanning" type="submit" class="btn btn-danger pull-right spaceTest listbtn"
                (click)="rescanBaseline(message)">
            refresh
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="deleteBaseline(message)">
            delete
        </button>
        <button type="submit" class="btn btn-danger pull-right listbtn"
                (click)="editBaseline(message)">mode_edit
        </button>

    <mat-divider></mat-divider>

CSS

.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

.sd:hover .listbtn {
    opacity: 1;
}

.settingsbtn {
    opacity: 1;
    transition: opacity .35s ease;
}

.sd:hover .settingsbtn {
    opacity: 0;
}

But it didn't work, what is the mistake I am making here?

EDIT

I want to display the settings button initially and when user hovers over settings button it should be hidden and other buttons should be visible but when user hovers over other buttons initially it shouldn't show those buttons. My current code snippet will work as when user hovers over any button either settings or hidden it will show the  buttons.

Body:
your code is working correctly, is this you want?

.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

.sd .settingsbtn:hover ~ .listbtn {
    opacity: 1;
}

.settingsbtn {
    opacity: 1;
    transition: opacity .35s ease;
}

.sd .settingsbtn:hover {
    opacity: 0;
}

<span class="sd">
<button type="submit" class="btn btn-danger pull-right settingsbtn">
<i class="material-icons">settings</i>
</button>
<button type="submit" class="btn btn-danger pull-right listbtn">
<i class="material-icons">content_paste</i>
</button>
<button type="submit" class="btn btn-danger pull-right listbtn">
<i class="material-icons">refresh</i>
</button>
<button type="submit" class="btn btn-danger pull-right listbtn">
<i class="material-icons">delete</i>
</button>
<button type="submit" class="btn btn-danger pull-right listbtn">
<i class="material-icons">mode_edit</i>
</button>
</span>


问:
How to find S3 connected to a cloudfront URL
The client has a site running on PHP deployed over AWS infrastructure. I have access to AWS console of a client.

There are some images in his site that is loading from cloudfront (which I understand is mapped to an S3 bucket). I need to update these images, but I do not know which S3 bucket they are in, since client has a lot of S3 buckets configured. How do I figure this one from the console?

答: also to add on John's answer; after you have changed the image in origin S3 bucket; you will have to invalidate the cache for those images in CloudFront .. otherwise even though origin has changed u will keep seeing old images</p>


问:
SEGV_MAPERR since Android 7
Our app gets crash reports on Android 7.0 and 7.1 only.

```<code>signal 11 (SIGSEGV), code 1 (SEGV_MAPERR)
_ZN7android6Parcel14freeDataNoInitEv
</code>```

Our app is using the map and GPS, which may be unrelated, but since I've seen a similar bug report on a different forum - with no answer - I thought I'd point this out.

backtrace:

```<code>  native: pc 000000000005ce64  /system/lib64/libbinder.so (_ZN7android6Parcel14freeDataNoInitEv+16)
  native: pc 00000000000f8004  /system/lib64/libandroid_runtime.so
  native: pc 0000000002977564  /system/framework/arm64/boot-framework.oat (android.os.Parcel.nativeDestroy+128)
  native: pc 0000000002976950  /system/framework/arm64/boot-framework.oat (android.os.Parcel.destroy+76)
  native: pc 000000000297b4ac  /system/framework/arm64/boot-framework.oat (android.os.Parcel.finalize+40)
  native: pc 000000000068a3a0  /system/framework/arm64/boot-core-libart.oat (java.lang.Daemons$FinalizerDaemon.doFinalize+140)
  native: pc 000000000068a67c  /system/framework/arm64/boot-core-libart.oat (java.lang.Daemons$FinalizerDaemon.run+520)
  native: pc 000000000065fb00  /system/framework/arm64/boot.oat (java.lang.Thread.run+60)
  native: pc 00000000000d1c34  /system/lib64/libart.so (art_quick_invoke_stub+580)
  native: pc 00000000000de970  /system/lib64/libart.so (_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+208)
  native: pc 000000000042e238  /system/lib64/libart.so (_ZN3artL18InvokeWithArgArrayERKNS_33ScopedObjectAccessAlreadyRunnableEPNS_9ArtMethodEPNS_8ArgArrayEPNS_6JValueEPKc+108)
  native: pc 000000000042f508  /system/lib64/libart.so (_ZN3art35InvokeVirtualOrInterfaceWithJValuesERKNS_33ScopedObjectAccessAlreadyRunnableEP8_jobjectP10_jmethodIDP6jvalue+372)
  native: pc 000000000044ecbc  /system/lib64/libart.so (_ZN3art6Thread14CreateCallbackEPv+1100)
  native: pc 000000000006958c  /system/lib64/libc.so (_ZL15__pthread_startPv+196)
  native: pc 000000000001dbf0  /system/lib64/libc.so (__start_thread+16)
</code>```

答:
This has been fixed by someone else on my project.

TLDR; The bug occurred when we sent to the Map a location built on Resume from the standard Location class and GSON serialization.

Using nothing but standard Google objects, we would store the location in case the app would get terminated. On resume, the app would reload the location object and send it to the map. The way the GSON is built, some fields may be missing, and the Map would crash.

We implemented our own Location object to deal with this.

Title: SEGV_MAPERR since Android 7

Body:
Our app gets crash reports on Android 7.0 and 7.1 only.

signal 11 (SIGSEGV), code 1 (SEGV_MAPERR)
_ZN7android6Parcel14freeDataNoInitEv

Our app is using the map and GPS, which may be unrelated, but since I've seen a similar bug report on a different forum - with no answer - I thought I'd point this out.

backtrace:

  native: pc 000000000005ce64  /system/lib64/libbinder.so (_ZN7android6Parcel14freeDataNoInitEv+16)
  native: pc 00000000000f8004  /system/lib64/libandroid_runtime.so
  native: pc 0000000002977564  /system/framework/arm64/boot-framework.oat (android.os.Parcel.nativeDestroy+128)
  native: pc 0000000002976950  /system/framework/arm64/boot-framework.oat (android.os.Parcel.destroy+76)
  native: pc 000000000297b4ac  /system/framework/arm64/boot-framework.oat (android.os.Parcel.finalize+40)
  native: pc 000000000068a3a0  /system/framework/arm64/boot-core-libart.oat (java.lang.Daemons$FinalizerDaemon.doFinalize+140)
  native: pc 000000000068a67c  /system/framework/arm64/boot-core-libart.oat (java.lang.Daemons$FinalizerDaemon.run+520)
  native: pc 000000000065fb00  /system/framework/arm64/boot.oat (java.lang.Thread.run+60)
  native: pc 00000000000d1c34  /system/lib64/libart.so (art_quick_invoke_stub+580)
  native: pc 00000000000de970  /system/lib64/libart.so (_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+208)
  native: pc 000000000042e238  /system/lib64/libart.so (_ZN3artL18InvokeWithArgArrayERKNS_33ScopedObjectAccessAlreadyRunnableEPNS_9ArtMethodEPNS_8ArgArrayEPNS_6JValueEPKc+108)
  native: pc 000000000042f508  /system/lib64/libart.so (_ZN3art35InvokeVirtualOrInterfaceWithJValuesERKNS_33ScopedObjectAccessAlreadyRunnableEP8_jobjectP10_jmethodIDP6jvalue+372)
  native: pc 000000000044ecbc  /system/lib64/libart.so (_ZN3art6Thread14CreateCallbackEPv+1100)
  native: pc 000000000006958c  /system/lib64/libc.so (_ZL15__pthread_startPv+196)
  native: pc 000000000001dbf0  /system/lib64/libc.so (__start_thread+16)


问:
Class 'Device' does not exist or has syntax error

can anyone helping me?
im stuck

答:
You need to add full namesapce of Device class:

```<code>backend\models\Device
</code>```

Body:
can anyone helping me?
im stuck

Body:
You need to add full namesapce of Device class:

backend\models\Device


问:
Update center Y and center X constraints in a UIView
I have created a UIVIew and add it into center X and Y;

The keyboard will overlap the View if the keyboard appear.

How do I update the constraint and make sure the view always in the center:

```<code>@IBOutlet weak var addViewConstraintX: NSLayoutConstraint!
@IBOutlet weak var addViewConstraintY: NSLayoutConstraint!
@IBOutlet weak var addView: UIView!
@IBOutlet weak var english: UITextField!
@IBOutlet weak var chinese: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    addView.layer.cornerRadius = 10.0;
    addView.layer.masksToBounds = true;
    NotificationCenter.default.addObserver(self, selector: #selector(FirstViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}

@objc func keyboardWillShow(_ notification:Notification) {
    print("keyboardWillShow")
}
</code>```

答:
In your viewDidLoad method

```<code>NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
</code>```

Elsewhere

```<code>func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardHeight = keyboardSize.height
        addView.center = CGPoint(x: self.view.center.x, y: self.view.center.y - keyboardHeight/2)
    }
}
</code>```

Body:
I have created a UIVIew and add it into center X and Y;

The keyboard will overlap the View if the keyboard appear.

How do I update the constraint and make sure the view always in the center:

@IBOutlet weak var addViewConstraintX: NSLayoutConstraint!
@IBOutlet weak var addViewConstraintY: NSLayoutConstraint!
@IBOutlet weak var addView: UIView!
@IBOutlet weak var english: UITextField!
@IBOutlet weak var chinese: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    addView.layer.cornerRadius = 10.0;
    addView.layer.masksToBounds = true;
    NotificationCenter.default.addObserver(self, selector: #selector(FirstViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}

@objc func keyboardWillShow(_ notification:Notification) {
    print("keyboardWillShow")
}

Body:
In your viewDidLoad method

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)

Elsewhere

func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardHeight = keyboardSize.height
        addView.center = CGPoint(x: self.view.center.x, y: self.view.center.y - keyboardHeight/2)
    }
}


问:
aws charging me for dns query
I have an ec2 instance under the free tier of aws and I am using route 53 hosting with it. In my bills, I am seeing charges for DNS-queries. But I don't get these on other servers I own on other accounts. Is it because I have configured it wrong? Please help</p>

答:
If you are using an A-record, then there is a charge ($0.40 per million queries).

However, as per the Route 53 pricing page:

Queries to Alias records that are mapped to Elastic Load Balancers, Amazon CloudFront distributions, AWS Elastic Beanstalk environments, and Amazon S3 website buckets are free.

To use this, select "Alias = Yes" and point to one of those resources. (But it appears an EC2 instance is not one of them, unless fronted by a Load Balancer.)

Worst case... pay the 40c!

Title: aws charging me for dns query


问:
How to set cookies in a Jenkins plugin?
I want to set cookies for my Jenkins parameterized plugin.

For example:

I have one string parameter called Git_Repo and everytime I need to copy/paste/manually edit/write the value in the parameter.

How can I set the cookie so that user will get option in the parameter?

I am attaching a screenshot:

.

答:
You have many options:

On chrome , You can enable auto-fill settings for forms to save your last entered data at different URLs.

On firefox, cookies are enabled by default.However, You can control the content according to the cache memory allotted for saving forms.

Using Autocomplete parameter plugin for Jenkins.

Title: How to set cookies in a Jenkins plugin?


问:
Check duplicate values and compare array in PHP
I have an array which contains details about "yahoo" and "google".

```<code>$initial= Array ( [0] => Array ( [user] => Yahoo [total] => 1 [day] => Monday)
    [1] => Array ( [user] => Google [total] => 2 [day] => Monday)
    [2] => Array ( [user] => Google [total] => 1 [day] => Tuesday )
    [3] => Array ( [user] => Google [total] => 3 [day] => Monday ) )
</code>```

I want to check array such that the conditions are:

```<code>1. from each array take 'day' and comapre with all arrays for particular day
2. if  'day' is same then compare user
3. if "users" are same for particular day then "count total" i.e.,5 for "Google" on monday
4. if "users' are different for particular day then keep "total" as it is.
</code>```

Final resultant array should look like this.

```<code>$result=Array([0]=>Array([day]=>Monday [user]=>[Google,Yahoo] [total]=>[5,1])
    [1]=>Array([day]=>Tuesday [user]=>[Google] [total]=>[1]))
</code>```

I have tried this for comparing but i am not able to obtain desired output.

```<code> $result= [];
 foreach($initial as $key => $value)
 {
    if(!in_array($value['day'], $match))
    {
      $result[] = $value['day'];
      continue;
    }

 }
</code>```

Is there any possible ways to solve this?

答:
If you make days the key of your result array then you can use the following loop:</p>

```<code>foreach($initial as $key => $value)
 {
     $day=$initial[$key]["day"];

     $result[$day]["user"][]=$initial[$key]["user"];
     $result[$day]["total"][]=$initial[$key]["total"];
 }
</code>```

Body:
I have an array which contains details about "yahoo" and "google".

$initial= Array ( [0] => Array ( [user] => Yahoo [total] => 1 [day] => Monday)
    [1] => Array ( [user] => Google [total] => 2 [day] => Monday)
    [2] => Array ( [user] => Google [total] => 1 [day] => Tuesday )
    [3] => Array ( [user] => Google [total] => 3 [day] => Monday ) )

I want to check array such that the conditions are:

1. from each array take 'day' and comapre with all arrays for particular day
2. if  'day' is same then compare user
3. if "users" are same for particular day then "count total" i.e.,5 for "Google" on monday
4. if "users' are different for particular day then keep "total" as it is.

Final resultant array should look like this.

$result=Array([0]=>Array([day]=>Monday [user]=>[Google,Yahoo] [total]=>[5,1])
    [1]=>Array([day]=>Tuesday [user]=>[Google] [total]=>[1]))

I have tried this for comparing but i am not able to obtain desired output.

 $result= [];
 foreach($initial as $key => $value)
 {
    if(!in_array($value['day'], $match))
    {
      $result[] = $value['day'];
      continue;
    }

 }

Is there any possible ways to solve this?

Body:
If you make days the key of your result array then you can use the following loop:

foreach($initial as $key => $value)
 {
     $day=$initial[$key]["day"];

     $result[$day]["user"][]=$initial[$key]["user"];
     $result[$day]["total"][]=$initial[$key]["total"];
 }


问:
Changing json to java pojo
Let's say I have a JSON file example.json

```<code>example.json

    {
      "BaggageMaxSize" : {
            "mesurement" : "sum",
            "width" : 70,
            "height" : 50,
            "depth" : 40
        }
    }
</code>```

And create the POJO class:

```<code>    public class pojoexample{
      private BaggageMaxSize BaggageMaxSize;
      // getter
      // setter
    }
</code>```

And then:

```<code>public class BaggageMaxSize
{
    private String height;

    private String width;

    private String depth;

    private String mesurement;

    // getter
    // setter
}
</code>```

Now, I want to use the mapper.readValue to change file to BaggageInfoPolicy.class:

```<code>BaggageInfoPolicy bip = mapper.readValue(file, BaggageInfoPolicy.class);
</code>```

But bip.getBaggageMaxSize().getMesurement() returns null value. Any suggestions?

答:
Try using mapper.writeValue first and check how your resulting JSON object will look like. Very likely, there's an issue with int -> string conversion in your BaggageMaxSize when deserialized from JSON.

Also, check your getters/setters to be publicly visible and be available both on pojoexample and BaggageMaxSize.

Title: Changing json to java pojo

Body:
Let's say I have a JSON file example.json

example.json

    {
      "BaggageMaxSize" : {
            "mesurement" : "sum",
            "width" : 70,
            "height" : 50,
            "depth" : 40
        }
    }

And create the POJO class:

    public class pojoexample{
      private BaggageMaxSize BaggageMaxSize;
      // getter
      // setter
    }

And then:

public class BaggageMaxSize
{
    private String height;

    private String width;

    private String depth;

    private String mesurement;

    // getter
    // setter
}

Now, I want to use the mapper.readValue to change file to BaggageInfoPolicy.class:

BaggageInfoPolicy bip = mapper.readValue(file, BaggageInfoPolicy.class);

But bip.getBaggageMaxSize().getMesurement() returns null value. Any suggestions?


问:
How the parameters in Gradient Descent are initialized, when we build a model using Linear Regression?
When I build a linear regression model in python or R, I just use the fit method. This method does not ask for initializing the learning rate, or starting point while this is required in gradient descent (as far as I know). So if I assume that the model is using Gradient descent to optimize, how these parameters are choosen by the linear model when using fit method?

Or, if the model does not use gradient descent (or its any type), then which algorithm it uses (and how) to optimize?

答: I assume you are using lm.fit() method. This method uses QR Decomposition technique for the regression. This technique doesn't require setting learning rate and starting point parameters.</p>


问:
Wicked_pdf working fine in development, but not in production
I've been working with wicked_pdf to generate some PDFs in Rails, and it's been working fine in my dev environment, but I get a 500 error (but no specific errors in my log) when I try and generate one on my production environment. The first thing I noticed was that the wkhtmltopdf binary was in a different location on my production box, so I've added the following to my wicked_pdf.rb initializer:

```<code>if Rails.env == "production"
    WickedPdf.config = {
        :exe_path => '/usr/bin/wkhtmltopdf'
    }
end
</code>```

Here's how I'm calling it in my controller:

```<code>  def certificate
    @inspection = Inspection.find(params[:id])
    @council = Council.find(@inspection.councilid)
    respond_to do |format|
        format.pdf do
            render :pdf => @inspection.slug,
                   :show_as_html => params[:debug].present?,
                   :margin => {:top            => 0,
                               :bottom         => 0,
                               :left           => 0,
                               :right          => 0}
        end
    end
  end
</code>```

And here's the contents of my view:

```<code># certificate.pdf.erb

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <style type="text/css">
        body {
            margin: 0;
            padding: 0;
            font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif;
        }

        img#bg {
            width: 800px;
            height: 1130px;
            position: absolute;
        }

        #date p, #council p {
            line-height: 17px;
            font-size: 12px;
        }

        #council {
            position: absolute;
            top: 650px;
            left: 445px;
        }

        #logo {
            position: absolute;
            top: 965px;
            left: 98px;
        }

        #logo img {
            height: 65px;
        }

        #address {
            position: absolute;
            top: 425px;
            left: 300px;
        }

        #address p {
            font-size: 22px;
            line-height: 27px;
        }

        #date {
            position: absolute;
            top: 650px;
            left: 98px;
        }

    </style>
  </head>
  <body>
      <%= wicked_pdf_image_tag "certificate#{@inspection.rating}.jpg", :id => "bg" %>

      <div id="address">
      <p><%= @inspection.name %><br />
      <%= @inspection.address("<br />").html_safe %>      </p>
      </div>

      <div id="date">
      <p><%= @inspection.date.strftime("%B %d %Y") %></p>
      </div>

      <div id="council">
      <p><%= @council.address.html_safe %><br /><br />
      <strong>Tel: </strong><%= @council.tel %></p>
      </div>

      <div id="logo">
      <%= wicked_pdf_image_tag "certificates/#{@council.logo}.png" %>
      </div>

  </body>
</html>
</code>```

When I add debug=true to the query string it seems to generate OK (and the wicked_pdf_image_tag helper seems to generate the correct location, which seemed to be a gotcha in Rails 3.1). Any ideas? I am pretty new to Ruby / Rails, so please be gentle!

答:
If still image not showing in production environment then please try</p>

```<code>image_tag wicked_pdf_asset_base64('image.png')
</code>```

Body:
I've been working with wicked_pdf to generate some PDFs in Rails, and it's been working fine in my dev environment, but I get a 500 error (but no specific errors in my log) when I try and generate one on my production environment. The first thing I noticed was that the wkhtmltopdf binary was in a different location on my production box, so I've added the following to my wicked_pdf.rb initializer:

if Rails.env == "production"
    WickedPdf.config = {
        :exe_path => '/usr/bin/wkhtmltopdf'
    }
end

Here's how I'm calling it in my controller:

  def certificate
    @inspection = Inspection.find(params[:id])
    @council = Council.find(@inspection.councilid)
    respond_to do |format|
        format.pdf do
            render :pdf => @inspection.slug,
                   :show_as_html => params[:debug].present?,
                   :margin => {:top            => 0,
                               :bottom         => 0,
                               :left           => 0,
                               :right          => 0}
        end
    end
  end

And here's the contents of my view:

# certificate.pdf.erb

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

      <%= wicked_pdf_image_tag "certificate#{@inspection.rating}.jpg", :id => "bg" %>

<%= @inspection.name %>

      <%= @inspection.address("
").html_safe %>

<%= @inspection.date.strftime("%B %d %Y") %>

<%= @council.address.html_safe %>

      Tel: <%= @council.tel %>

      <%= wicked_pdf_image_tag "certificates/#{@council.logo}.png" %>

When I add debug=true to the query string it seems to generate OK (and the wicked_pdf_image_tag helper seems to generate the correct location, which seemed to be a gotcha in Rails 3.1). Any ideas? I am pretty new to Ruby / Rails, so please be gentle!

Body:
If still image not showing in production environment then please try

image_tag wicked_pdf_asset_base64('image.png')


问:
Using Javascript in CSS
Is it possible to use Javascript inside CSS?

If it is, can you give a simple example?

答:
I think what you may be thinking of is expressions or "dynamic properties", which are only supported by IE and let you set a property to the result of a javascript expression. Example:

```<code>width:expression(document.body.clientWidth > 800? "800px": "auto" );
</code>```

This code makes IE emulate the max-width property it doesn't support.

All things considered, however, avoid using these. They are a bad, bad thing.

OwnerDisplayName: HelpMe

Title: Using Javascript in CSS

Body:
I think what you may be thinking of is expressions or "dynamic properties", which are only supported by IE and let you set a property to the result of a javascript expression. Example:

width:expression(document.body.clientWidth > 800? "800px": "auto" );

This code makes IE emulate the max-width property it doesn't support.

All things considered, however, avoid using these. They are a bad, bad thing.

OwnerDisplayName: Paolo Bergantino

LastEditorDisplayName: Paolo Bergantino


问:
RuntimeException: Unable to instantiate application
When I run my application, everytime I am getting the below exception in my logcat:

```<code> 04-14 09:29:53.965: W/dalvikvm(1020): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
    04-14 09:29:53.985: E/AndroidRuntime(1020): FATAL EXCEPTION: main
    04-14 09:29:53.985: E/AndroidRuntime(1020): java.lang.RuntimeException: Unable to instantiate application   android.app.Application: java.lang.NullPointerException
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.LoadedApk.makeApplication(LoadedApk.java:482)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.ActivityThread.handleBindApplication(ActivityThread.java:3938)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.ActivityThread.access$1300(ActivityThread.java:123)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1185)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.os.Handler.dispatchMessage(Handler.java:99)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.os.Looper.loop(Looper.java:137)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.ActivityThread.main(ActivityThread.java:4424)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at java.lang.reflect.Method.invokeNative(Native Method)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at java.lang.reflect.Method.invoke(Method.java:511)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at dalvik.system.NativeStart.main(Native Method)
    04-14 09:29:53.985: E/AndroidRuntime(1020): Caused by: java.lang.NullPointerException
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.LoadedApk.initializeJavaContextClassLoader(LoadedApk.java:362)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.LoadedApk.getClassLoader(LoadedApk.java:305)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.LoadedApk.makeApplication(LoadedApk.java:474)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     ... 11 more
</code>```

Note: When I uninstall the app from the emulator and run it, then I don't get this exception but when I re-run the installed application in emulator, I am getting this. Please help.

答:
I meet this question.
When use gradle clean,gradle installDebug it work ok!

```<code>   AndroidRuntime  D  Shutting down VM
E  FATAL EXCEPTION: main
E  Process: tv.panda.live.broadcast, PID: 4685
E  java.lang.RuntimeException: Unable to instantiate application tv.panda.live.broadcast.PandaApplication: java.lang.ClassNotFoundException: Didn't find class "tv.panda.live.broadcast.PandaApplication" o
   n path: DexPathList[[zip file "/data/app/tv.panda.live.broadcast-1/base.apk"],nativeLibraryDirectories=[/data/app/tv.panda.live.broadcast-1/lib/arm, /vendor/lib, /system/lib]]
E      at android.app.LoadedApk.makeApplication(LoadedApk.java:572)
E      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4883)
E      at android.app.ActivityThread.access$1500(ActivityThread.java:178)
E      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1573)
E      at android.os.Handler.dispatchMessage(Handler.java:111)
E      at android.os.Looper.loop(Looper.java:194)
E      at android.app.ActivityThread.main(ActivityThread.java:5691)
E      at java.lang.reflect.Method.invoke(Native Method)
E      at java.lang.reflect.Method.invoke(Method.java:372)
E      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
E      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
E  Caused by: java.lang.ClassNotFoundException: Didn't find class "tv.panda.live.broadcast.PandaApplication" on path: DexPathList[[zip file "/data/app/tv.panda.live.broadcast-1/base.apk"],nativeLibraryDi
   rectories=[/data/app/tv.panda.live.broadcast-1/lib/arm, /vendor/lib, /system/lib]]
E      at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
E      at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
E      at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
E      at android.app.Instrumentation.newApplication(Instrumentation.java:988)
E      at android.app.LoadedApk.makeApplication(LoadedApk.java:567)
E      ... 10 more
E      Suppressed: java.lang.ClassNotFoundException: tv.panda.live.broadcast.PandaApplication
E          at java.lang.Class.classForName(Native Method)
E          at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
E          at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
E          at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
E          ... 13 more
E      Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
</code>```

Body:
When I run my application, everytime I am getting the below exception in my logcat:

 04-14 09:29:53.965: W/dalvikvm(1020): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
    04-14 09:29:53.985: E/AndroidRuntime(1020): FATAL EXCEPTION: main
    04-14 09:29:53.985: E/AndroidRuntime(1020): java.lang.RuntimeException: Unable to instantiate application   android.app.Application: java.lang.NullPointerException
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.LoadedApk.makeApplication(LoadedApk.java:482)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.ActivityThread.handleBindApplication(ActivityThread.java:3938)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.ActivityThread.access$1300(ActivityThread.java:123)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1185)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.os.Handler.dispatchMessage(Handler.java:99)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.os.Looper.loop(Looper.java:137)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.ActivityThread.main(ActivityThread.java:4424)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at java.lang.reflect.Method.invokeNative(Native Method)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at java.lang.reflect.Method.invoke(Method.java:511)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at dalvik.system.NativeStart.main(Native Method)
    04-14 09:29:53.985: E/AndroidRuntime(1020): Caused by: java.lang.NullPointerException
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.LoadedApk.initializeJavaContextClassLoader(LoadedApk.java:362)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.LoadedApk.getClassLoader(LoadedApk.java:305)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.LoadedApk.makeApplication(LoadedApk.java:474)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     ... 11 more

Note: When I uninstall the app from the emulator and run it, then I don't get this exception but when I re-run the installed application in emulator, I am getting this. Please help.

Body:
I meet this question.
When use gradle clean,gradle installDebug it work ok!

   AndroidRuntime  D  Shutting down VM
E  FATAL EXCEPTION: main
E  Process: tv.panda.live.broadcast, PID: 4685
E  java.lang.RuntimeException: Unable to instantiate application tv.panda.live.broadcast.PandaApplication: java.lang.ClassNotFoundException: Didn't find class "tv.panda.live.broadcast.PandaApplication" o
   n path: DexPathList[[zip file "/data/app/tv.panda.live.broadcast-1/base.apk"],nativeLibraryDirectories=[/data/app/tv.panda.live.broadcast-1/lib/arm, /vendor/lib, /system/lib]]
E      at android.app.LoadedApk.makeApplication(LoadedApk.java:572)
E      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4883)
E      at android.app.ActivityThread.access$1500(ActivityThread.java:178)
E      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1573)
E      at android.os.Handler.dispatchMessage(Handler.java:111)
E      at android.os.Looper.loop(Looper.java:194)
E      at android.app.ActivityThread.main(ActivityThread.java:5691)
E      at java.lang.reflect.Method.invoke(Native Method)
E      at java.lang.reflect.Method.invoke(Method.java:372)
E      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
E      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
E  Caused by: java.lang.ClassNotFoundException: Didn't find class "tv.panda.live.broadcast.PandaApplication" on path: DexPathList[[zip file "/data/app/tv.panda.live.broadcast-1/base.apk"],nativeLibraryDi
   rectories=[/data/app/tv.panda.live.broadcast-1/lib/arm, /vendor/lib, /system/lib]]
E      at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
E      at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
E      at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
E      at android.app.Instrumentation.newApplication(Instrumentation.java:988)
E      at android.app.LoadedApk.makeApplication(LoadedApk.java:567)
E      ... 10 more
E      Suppressed: java.lang.ClassNotFoundException: tv.panda.live.broadcast.PandaApplication
E          at java.lang.Class.classForName(Native Method)
E          at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
E          at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
E          at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
E          ... 13 more
E      Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available


问:
How to show all entry y value in the same x line in Swift?
I'm making a line chart by using iOS-charts framework. I have 3 line or set. Sometimes it will overlay each other so I made a balloon marker. It will show the value when hover the point but it only show 1 y value. How to show all the y value in the same x line?

similar question but no solve yet : https://github.com/danielgindi/Charts/issues/2173

This code is on BalloonMarker.swift, it is for edit the marker value.

```<code>public override func refreshContent(entry: ChartDataEntry, highlight: Highlight) {
    setLabel(String(entry.y))
}
</code>```

答:
My solution</p>

```<code>public override func refreshContent(entry: ChartDataEntry, highlight: Highlight) {
    let set = chartView?.data?.dataSets[0]
    let set1 = chartView?.data?.dataSets[1]
    let setEntry = set?.entryForIndex(Int(entry.x))
    let setEntry2 = set1?.entryForIndex(Int(entry.x))
    let month = Int(entry.x + 1.0)

    setLabel(String("\(month)月\n 收入：\(setEntry?.y ?? 0.0)\n 支出：\(setEntry2?.y ?? 0.0)"))
}
</code>```

Body:
I'm making a line chart by using iOS-charts framework. I have 3 line or set. Sometimes it will overlay each other so I made a balloon marker. It will show the value when hover the point but it only show 1 y value. How to show all the y value in the same x line?

similar question but no solve yet : https://github.com/danielgindi/Charts/issues/2173

This code is on BalloonMarker.swift, it is for edit the marker value.

public override func refreshContent(entry: ChartDataEntry, highlight: Highlight) {
    setLabel(String(entry.y))
}

Body:
My solution

public override func refreshContent(entry: ChartDataEntry, highlight: Highlight) {
    let set = chartView?.data?.dataSets[0]
    let set1 = chartView?.data?.dataSets[1]
    let setEntry = set?.entryForIndex(Int(entry.x))
    let setEntry2 = set1?.entryForIndex(Int(entry.x))
    let month = Int(entry.x + 1.0)

    setLabel(String("\(month)月\n 收入：\(setEntry?.y ?? 0.0)\n 支出：\(setEntry2?.y ?? 0.0)"))
}


问:
How to show current url in EditText - android studio
I'm trying to make an web browser but I'm facing an problem that is i can't show current url in EditText..Showing currrent url from Webview. How can i do this. please tell me where should i put code and what code i need to put. please help me.

Here my code:

```<code>public class MainActivity extends AppCompatActivity {

    WebView browser;
    EditText urlbox;
    Button go,forward,backward,refresh,clear;
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        browser= (WebView)findViewById(R.id.browser);
        urlbox = (EditText)findViewById(R.id.urlbox);
        go = (Button)findViewById(R.id.go);
        forward = (Button)findViewById(R.id.f);
        backward = (Button)findViewById(R.id.b);
        refresh = (Button)findViewById(R.id.r);
        clear = (Button)findViewById(R.id.c);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);

        browser.setWebViewClient(new ourviewclient());

        browser.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                progressBar.setProgress(newProgress);
                if(newProgress == 100){
                    progressBar.setVisibility(view.GONE);
                }else {
                    progressBar.setVisibility(view.VISIBLE);
                }
            }
        });

        WebSettings javascript = browser.getSettings();
        browser.getSettings().setJavaScriptEnabled(true);

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

               String editextvalue = urlbox.getText().toString();

               if(!editextvalue.startsWith("http://"))
                   editextvalue = "http://" + editextvalue;

               String url = editextvalue;

               browser.loadUrl(url);

               //for keyboard hide
                InputMethodManager keyboard = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                keyboard.hideSoftInputFromWindow(urlbox.getWindowToken(),0);
            }
        });

        forward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (browser.canGoForward())
                    browser.goForward();
            }
        });

        backward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (browser.canGoBack())
                    browser.goBack();
            }
        });

        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                browser.reload();
            }
        });

        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                browser.clearHistory();
            }
        });

    }
}
</code>```

答:
Try this</p>

```<code>browser.setWebViewClient(new WebViewClient() {
      @Override
      public void onPageStarted(WebView view, String url, Bitmap favicon) {
           super.onPageStarted(view, url, favicon);

           // set here your URL in Your EditText
            urlbox.setText(url);

       }

       @Override
       public boolean shouldOverrideUrlLoading(WebView view, String url) {
           view.loadUrl(url);
           return true;
       }

       @Override
       public void onPageFinished(WebView view, String url) {

       }
  });
</code>```

Body:
I'm trying to make an web browser but I'm facing an problem that is i can't show current url in EditText..Showing currrent url from Webview. How can i do this. please tell me where should i put code and what code i need to put. please help me.

Here my code:

public class MainActivity extends AppCompatActivity {

    WebView browser;
    EditText urlbox;
    Button go,forward,backward,refresh,clear;
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        browser= (WebView)findViewById(R.id.browser);
        urlbox = (EditText)findViewById(R.id.urlbox);
        go = (Button)findViewById(R.id.go);
        forward = (Button)findViewById(R.id.f);
        backward = (Button)findViewById(R.id.b);
        refresh = (Button)findViewById(R.id.r);
        clear = (Button)findViewById(R.id.c);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);

        browser.setWebViewClient(new ourviewclient());

        browser.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                progressBar.setProgress(newProgress);
                if(newProgress == 100){
                    progressBar.setVisibility(view.GONE);
                }else {
                    progressBar.setVisibility(view.VISIBLE);
                }
            }
        });

        WebSettings javascript = browser.getSettings();
        browser.getSettings().setJavaScriptEnabled(true);

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

               String editextvalue = urlbox.getText().toString();

               if(!editextvalue.startsWith("http://"))
                   editextvalue = "http://" + editextvalue;

               String url = editextvalue;

               browser.loadUrl(url);

               //for keyboard hide
                InputMethodManager keyboard = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                keyboard.hideSoftInputFromWindow(urlbox.getWindowToken(),0);
            }
        });

        forward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (browser.canGoForward())
                    browser.goForward();
            }
        });

        backward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (browser.canGoBack())
                    browser.goBack();
            }
        });

        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                browser.reload();
            }
        });

        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                browser.clearHistory();
            }
        });

    }
}

Body:
Try this

browser.setWebViewClient(new WebViewClient() {
      @Override
      public void onPageStarted(WebView view, String url, Bitmap favicon) {
           super.onPageStarted(view, url, favicon);

           // set here your URL in Your EditText
            urlbox.setText(url);

       }

       @Override
       public boolean shouldOverrideUrlLoading(WebView view, String url) {
           view.loadUrl(url);
           return true;
       }

       @Override
       public void onPageFinished(WebView view, String url) {

       }
  });


问:
Getting MediaCodec decoder provide video frames in RGBA
I am trying to use a MediaCodec decoder (via the NDK API) to fetch video frames (for further processing) from a .mp4 file. Here is the sample code that sets up the decoder to render to a surface (owned by an ImageReader):

```<code>// Omitting most error handling for clarity

AMediaExtractor* ex = AMediaExtractor_new();
media_status_t err = AMediaExtractor_setDataSourceFd(ex, fd /*opened previously*/, outStart, outLen);
close(fd);

int numtracks = AMediaExtractor_getTrackCount(ex);
AMediaCodec* decoder = NULL;

for (int i = 0; i < numtracks; i++) {
    AMediaFormat *format = AMediaExtractor_getTrackFormat(ex, i);
    const char *s = AMediaFormat_toString(format);
    LOGV("track %d format: %s", i, s);
    const char *mime;
    if (!AMediaFormat_getString(format, AMEDIAFORMAT_KEY_MIME, &mime)) {
        LOGV("no mime type");
        return JNI_FALSE;
    } else if (!strncmp(mime, "video/", 6)) {
        AMediaExtractor_selectTrack(ex, i);
        decoder = AMediaCodec_createDecoderByType(mime);

        AImageReader* imageReader;
        ANativeWindow* surface;

        // This setting doesn’t works
        media_status_t status = AImageReader_new(480, 360, AIMAGE_FORMAT_RGBA_8888, 1, &imageReader);

        // This setting works
        //media_status_t status = AImageReader_new(480, 360, AIMAGE_FORMAT_YUV_420_888, 1, &imageReader);

        status = AImageReader_getWindow(imageReader, &surface);

        // Configure the decoder to render to a surface
        AMediaCodec_configure(codec, format, surface, NULL, 0);

        AMediaCodec_start(codec);
    }

    AMediaFormat_delete(format);
}
</code>```

Elsewhere, here below is how I am setting up the callback for the ImageReader:

```<code>AImageReader_ImageListener* imageListener = new AImageReader_ImageListener();
imageListener->onImageAvailable = &imageCallback;
AImageReader_setImageListener(imageReader, imageListener);
</code>```

And finally, here below is how the callback looks like:

```<code>void imageCallback(void *context, AImageReader *reader) {

    int32_t format;
    media_status_t status = AImageReader_getFormat (reader, &format);

    AImage* image;
    status = AImageReader_acquireLatestImage(reader, &image);

    status = AImage_getFormat(image, &format);

    // further processing to follow
    ...
}
</code>```

The issue that I have been facing is that if I configure the ImageReader with RGBA format, the image in the callback always comes out to be NULL:

```<code>// Always NULL for ImageReader configured with RGBA
// OK for ImageReader configured with YUV_420_888
AImage* image;
status = AImageReader_acquireLatestImage(reader, &image);
</code>```

Am I using the NDK API correctly here? One thing I would like to mention is that the RGBA doesn't appears in the list of decoder capabilities as fetched via the following API (not provided via NDK, tried it in the Java layer):

```<code> getCodecInfo().getCapabilitiesForType(…).colorFormats
</code>```

答:
Video decoders normally don't support outputting in RGB format (as you noticed in the colorformats codec info), so that's why this won't work.

The video decoder output can be transparently converted into RGB if you use a surface texture as the output for the decoder - then the decoded video data is available within an OpenGL context. If you then just do a plain 1:1 copy/rendering of the surface texture and have the OpenGL context set up to render into an ImageReader, I would expect you to get the RGB data you need.

It is a bit roundabout (and I'm not sure how easily accessible all the APIs are in a native code context), but should be doable as far as I know.

Body:
I am trying to use a MediaCodec decoder (via the NDK API) to fetch video frames (for further processing) from a .mp4 file. Here is the sample code that sets up the decoder to render to a surface (owned by an ImageReader):

// Omitting most error handling for clarity

AMediaExtractor* ex = AMediaExtractor_new();
media_status_t err = AMediaExtractor_setDataSourceFd(ex, fd /*opened previously*/, outStart, outLen);
close(fd);

int numtracks = AMediaExtractor_getTrackCount(ex);
AMediaCodec* decoder = NULL;

for (int i = 0; i < numtracks; i++) {
    AMediaFormat *format = AMediaExtractor_getTrackFormat(ex, i);
    const char *s = AMediaFormat_toString(format);
    LOGV("track %d format: %s", i, s);
    const char *mime;
    if (!AMediaFormat_getString(format, AMEDIAFORMAT_KEY_MIME, &mime)) {
        LOGV("no mime type");
        return JNI_FALSE;
    } else if (!strncmp(mime, "video/", 6)) {
        AMediaExtractor_selectTrack(ex, i);
        decoder = AMediaCodec_createDecoderByType(mime);

        AImageReader* imageReader;
        ANativeWindow* surface;

        // This setting doesn’t works
        media_status_t status = AImageReader_new(480, 360, AIMAGE_FORMAT_RGBA_8888, 1, &imageReader);

        // This setting works
        //media_status_t status = AImageReader_new(480, 360, AIMAGE_FORMAT_YUV_420_888, 1, &imageReader);

        status = AImageReader_getWindow(imageReader, &surface);

        // Configure the decoder to render to a surface
        AMediaCodec_configure(codec, format, surface, NULL, 0);

        AMediaCodec_start(codec);
    }

    AMediaFormat_delete(format);
}

Elsewhere, here below is how I am setting up the callback for the ImageReader:

AImageReader_ImageListener* imageListener = new AImageReader_ImageListener();
imageListener->onImageAvailable = &imageCallback;
AImageReader_setImageListener(imageReader, imageListener);

And finally, here below is how the callback looks like:

void imageCallback(void *context, AImageReader *reader) {

    int32_t format;
    media_status_t status = AImageReader_getFormat (reader, &format);

    AImage* image;
    status = AImageReader_acquireLatestImage(reader, &image);

    status = AImage_getFormat(image, &format);

    // further processing to follow
    ...
}

The issue that I have been facing is that if I configure the ImageReader with RGBA format, the image in the callback always comes out to be NULL:

// Always NULL for ImageReader configured with RGBA
// OK for ImageReader configured with YUV_420_888
AImage* image;
status = AImageReader_acquireLatestImage(reader, &image);

Am I using the NDK API correctly here? One thing I would like to mention is that the RGBA doesn't appears in the list of decoder capabilities as fetched via the following API (not provided via NDK, tried it in the Java layer):

 getCodecInfo().getCapabilitiesForType(…).colorFormats


问:
How to create a set vlan flow?
I want to do the equivalent of the following :

```<code>sudo ovs-ofctl add-flow s1 table=2,metadata=1379878762,actions=push_vlan:0x8100,mod_vlan_vid:4000,output:6,goto_table:4 -O openflow13
</code>```

How can I do this in opendaylight java code? I tried based on some examples I could find,  but no flows appeared or sometimes with enough tweaking I could get a part of the flow to appear (I could never see the output action). I am using Carbon (the latest version of carbon) for my development. Is it worth switching to the nightly snapshot?

When I do this with opendaylight, I find that any actions having to do with vlan do not appear in my flow.  Only the goto appears in the flow.

=== UPDATE ===

I use the following java code to set and create the vlan tag (suggested by answer below):

```<code>    private static Instruction createSetVlanAndOutputToPortInstructions( int vlanId,
        String outputPortUri) {

    List<Action> actionList = new ArrayList<>();
    ActionBuilder ab = new ActionBuilder();

    Integer VLAN_ETHERTYPE = 0x8100;
    ActionBuilder actionBuilder = new ActionBuilder();

    //push vlan
    Action pushVlanAction = actionBuilder
        .setOrder(0).setAction(new PushVlanActionCaseBuilder()
            .setPushVlanAction(new PushVlanActionBuilder()
                .setEthernetType(VLAN_ETHERTYPE)
                    .build())
                    .build())
                .build();
    actionList.add(pushVlanAction);

    //set vlan id

    SetVlanIdActionBuilder tab = new SetVlanIdActionBuilder();
    tab.setVlanId(new VlanId((int) vlanId));
    SetVlanIdActionCaseBuilder vidcb = new SetVlanIdActionCaseBuilder();
    vidcb.setSetVlanIdAction(tab.build());
    Action setVlanIdAction = actionBuilder.setOrder(1).setAction(vidcb.build()).build();

    OutputActionBuilder output = new OutputActionBuilder();
    output.setMaxLength(Integer.valueOf(0xffff));

    Uri controllerPort = new Uri(outputPortUri);
    output.setOutputNodeConnector(controllerPort);

    ab = new ActionBuilder();
    ab.setKey(new ActionKey(0));
    ab.setAction(new OutputActionCaseBuilder().setOutputAction(output.build()).build());
    ab.setOrder(2);
    actionList.add(ab.build());

    ApplyActionsBuilder aab = new ApplyActionsBuilder();

    aab.setAction(actionList);

    InstructionBuilder ib = new InstructionBuilder();
    ib.setKey(new InstructionKey(0));
    ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());

    return ib.build();
}
</code>```

The code that creates a flow rule is here:

```<code> FlowBuilder tagPacketFlow = new FlowBuilder().setTableId((short) tableId)
            .setFlowName("metadataMatchSetVlanTagSendToPortAndGoToStripVlanTagTable").setId(flowId)
            .setKey(new FlowKey(flowId)).setCookie(flowCookie);
    MatchBuilder matchBuilder = new MatchBuilder();
    createMetadataMatch(matchBuilder, flowCookie.getValue());

    InstructionBuilder ib = new InstructionBuilder();
    Instruction createVlanTag = FlowUtils.createSetVlanAndOutputToPortInstructions(
            SdnMudConstants.MUD_RULE_HIT_LABEL, outputPortUri);

    InstructionsBuilder insb = new InstructionsBuilder();
    ArrayList<Instruction> instructions = new ArrayList<Instruction>();
    instructions.add(createVlanTag);
    Instruction gotoInstruction = ib.setInstruction(new GoToTableCaseBuilder()
            .setGoToTable(new GoToTableBuilder().setTableId(SdnMudConstants.STRIP_VLAN_RULE_TABLE).build()).build())
            .setOrder(3)
            .setKey(new InstructionKey(0)).build();
    instructions.add(gotoInstruction);

    insb.setInstruction(instructions);
    tagPacketFlow.setMatch(matchBuilder.build()).setInstructions(insb.build())
            .setPriority(35).setBufferId(OFConstants.ANY)
            .setHardTimeout(time).setIdleTimeout(0).setFlags(new FlowModFlags(false, false, false, false, false));
</code>```

Upon invoking the code I see this in openvswitch:

```<code> cookie=0x523f476a, duration=0.012s, table=2, n_packets=0, n_bytes=0, hard_timeout=30000, priority=35,metadata=0x523f476a actions=goto_table:3
</code>```

And here's the dump from the config datastore corresponding to this flow:

```<code>    {
                        "buffer_id": 4294967295,
                        "cookie": 1379878762,
                        "flags": "",
                        "flow-name": "metadataMatchSetVlanTagSendToPortAndGoToStripVlanTagTable",
                        "hard-timeout": 30000,
                        "id": "toaster.nist.gov/42",
                        "idle-timeout": 0,
                        "instructions": {
                            "instruction": [
                                {
                                    "go-to-table": {
                                        "table_id": 3
                                    },
                                    "order": 0
                                }
                            ]
                        },
                        "match": {
                            "metadata": {
                                "metadata": 1379878762
                            }
                        },
                        "priority": 35,
                        "table_id": 2
                    }
</code>```

So the Vlan Setting just disappeared.

==== End UPDATE ====

==== UPDATE 1 ====

I logged the flow before committing the transaction. Here's the set VLAN instruction :

```<code>   ApplyActionsCase [_applyActions=ApplyActions
      [_action=[Action [_action=PushVlanActionCase
      [_pushVlanAction=PushVlanAction [_ethernetType=33024,
      _vlanId=VlanId [_value=1001], augmentation=[]], augmentation=[]],
     _key=ActionKey [_order=0], _order=0, augmentation=[]],
      Action [_action=SetVlanIdActionCase[_setVlanIdAction=SetVlanIdAction
     [_vlanId=VlanId [_value=1001], augmentation=[]],
     augmentation=[]], _key=ActionKey [_order=1], _order=1,
     augmentation=[]], Action [_action=OutputActionCase
     [_outputAction=OutputAction [_maxLength=65535,
     _outputNodeConnector=Uri [_value=openflow:1:6],
      augmentation=[]], augmentation=[]],
     _key=ActionKey [_order=2], _order=2,
      augmentation=[]]], augmentation=[]], augmentation=[]]
</code>```

I can't see anything wrong with it.

=== End UPDATE 1 ===

=== Update 2 ===

When I remove the goto and follow the pattern of the xml here:
https://wiki.opendaylight.org/view/Editing_OpenDaylight_OpenFlow_Plugin:End_to_End_Flows:Example_Flows#Push_VLAN

it only works WITHOUT the goto. In other words if I remove the goto I can see the push flow in the config datastore. If I put the goto in, ONLY the goto appears.

==== End Update 2 ====

I see an issue in the issue tracker about vlan flows in opendaylight soutbound being broken but it appears to have been fixed in 2014 (?).

Is this fixed in nitrogen and how can I go about filing a bug against opendaylight?

答:
Try this :

```<code>Integer VLAN_ETHERTYPE = 0x8100;
ActionBuilder actionBuilder = new ActionBuilder();
List<Action> actions = new ArrayList<>();

//push vlan
Action pushVlanAction = actionBuilder
    .setOrder(0).setAction(new PushVlanActionCaseBuilder()
        .setPushVlanAction(new PushVlanActionBuilder()
            .setEthernetType(VLAN_ETHERTYPE)
                .build())
                .build())
            .build();
actions.add(pushVlanAction);

//set vlan id
Action setVlanIdAction = actionBuilder
    .setOrder(1).setAction(new SetFieldCaseBuilder()
        .setSetField(new SetFieldBuilder()
            .setVlanMatch(new VlanMatchBuilder()
                .setVlanId(new VlanIdBuilder()
                    .setVlanId(new VlanId(vlanID))
                     .setVlanIdPresent(true)
                .build())
            .build())
        .build())
    .build())
    .build();
actions.add(setVlanIdAction);
</code>```

Then, you need to add your actions into your instructions in the following way:

```<code>//ApplyActions
ApplyActions applyActions = new ApplyActionsBuilder().setAction(actions).build();

//Instruction
Instruction applyActionsInstruction = new InstructionBuilder()
        .setOrder(0).setInstruction(new ApplyActionsCaseBuilder()
                .setApplyActions(applyActions)
                .build())
            .build();
</code>```

Also take a look here.

Title: How to create a set vlan flow?

Body:
I want to do the equivalent of the following :

sudo ovs-ofctl add-flow s1 table=2,metadata=1379878762,actions=push_vlan:0x8100,mod_vlan_vid:4000,output:6,goto_table:4 -O openflow13

How can I do this in opendaylight java code? I tried based on some examples I could find,  but no flows appeared or sometimes with enough tweaking I could get a part of the flow to appear (I could never see the output action). I am using Carbon (the latest version of carbon) for my development. Is it worth switching to the nightly snapshot?

When I do this with opendaylight, I find that any actions having to do with vlan do not appear in my flow.  Only the goto appears in the flow.

=== UPDATE ===

I use the following java code to set and create the vlan tag (suggested by answer below):

    private static Instruction createSetVlanAndOutputToPortInstructions( int vlanId,
        String outputPortUri) {

    List<Action> actionList = new ArrayList<>();
    ActionBuilder ab = new ActionBuilder();

    Integer VLAN_ETHERTYPE = 0x8100;
    ActionBuilder actionBuilder = new ActionBuilder();

    //push vlan
    Action pushVlanAction = actionBuilder
        .setOrder(0).setAction(new PushVlanActionCaseBuilder()
            .setPushVlanAction(new PushVlanActionBuilder()
                .setEthernetType(VLAN_ETHERTYPE)
                    .build())
                    .build())
                .build();
    actionList.add(pushVlanAction);

    //set vlan id

    SetVlanIdActionBuilder tab = new SetVlanIdActionBuilder();
    tab.setVlanId(new VlanId((int) vlanId));
    SetVlanIdActionCaseBuilder vidcb = new SetVlanIdActionCaseBuilder();
    vidcb.setSetVlanIdAction(tab.build());
    Action setVlanIdAction = actionBuilder.setOrder(1).setAction(vidcb.build()).build();

    OutputActionBuilder output = new OutputActionBuilder();
    output.setMaxLength(Integer.valueOf(0xffff));

    Uri controllerPort = new Uri(outputPortUri);
    output.setOutputNodeConnector(controllerPort);

    ab = new ActionBuilder();
    ab.setKey(new ActionKey(0));
    ab.setAction(new OutputActionCaseBuilder().setOutputAction(output.build()).build());
    ab.setOrder(2);
    actionList.add(ab.build());

    ApplyActionsBuilder aab = new ApplyActionsBuilder();

    aab.setAction(actionList);

    InstructionBuilder ib = new InstructionBuilder();
    ib.setKey(new InstructionKey(0));
    ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());

    return ib.build();
}

The code that creates a flow rule is here:

 FlowBuilder tagPacketFlow = new FlowBuilder().setTableId((short) tableId)
            .setFlowName("metadataMatchSetVlanTagSendToPortAndGoToStripVlanTagTable").setId(flowId)
            .setKey(new FlowKey(flowId)).setCookie(flowCookie);
    MatchBuilder matchBuilder = new MatchBuilder();
    createMetadataMatch(matchBuilder, flowCookie.getValue());

    InstructionBuilder ib = new InstructionBuilder();
    Instruction createVlanTag = FlowUtils.createSetVlanAndOutputToPortInstructions(
            SdnMudConstants.MUD_RULE_HIT_LABEL, outputPortUri);

    InstructionsBuilder insb = new InstructionsBuilder();
    ArrayList<Instruction> instructions = new ArrayList<Instruction>();
    instructions.add(createVlanTag);
    Instruction gotoInstruction = ib.setInstruction(new GoToTableCaseBuilder()
            .setGoToTable(new GoToTableBuilder().setTableId(SdnMudConstants.STRIP_VLAN_RULE_TABLE).build()).build())
            .setOrder(3)
            .setKey(new InstructionKey(0)).build();
    instructions.add(gotoInstruction);

    insb.setInstruction(instructions);
    tagPacketFlow.setMatch(matchBuilder.build()).setInstructions(insb.build())
            .setPriority(35).setBufferId(OFConstants.ANY)
            .setHardTimeout(time).setIdleTimeout(0).setFlags(new FlowModFlags(false, false, false, false, false));

Upon invoking the code I see this in openvswitch:

 cookie=0x523f476a, duration=0.012s, table=2, n_packets=0, n_bytes=0, hard_timeout=30000, priority=35,metadata=0x523f476a actions=goto_table:3

And here's the dump from the config datastore corresponding to this flow:

    {
                        "buffer_id": 4294967295,
                        "cookie": 1379878762,
                        "flags": "",
                        "flow-name": "metadataMatchSetVlanTagSendToPortAndGoToStripVlanTagTable",
                        "hard-timeout": 30000,
                        "id": "toaster.nist.gov/42",
                        "idle-timeout": 0,
                        "instructions": {
                            "instruction": [
                                {
                                    "go-to-table": {
                                        "table_id": 3
                                    },
                                    "order": 0
                                }
                            ]
                        },
                        "match": {
                            "metadata": {
                                "metadata": 1379878762
                            }
                        },
                        "priority": 35,
                        "table_id": 2
                    }

So the Vlan Setting just disappeared.

==== End UPDATE ====

==== UPDATE 1 ====

I logged the flow before committing the transaction. Here's the set VLAN instruction :

   ApplyActionsCase [_applyActions=ApplyActions
      [_action=[Action [_action=PushVlanActionCase
      [_pushVlanAction=PushVlanAction [_ethernetType=33024,
      _vlanId=VlanId [_value=1001], augmentation=[]], augmentation=[]],
     _key=ActionKey [_order=0], _order=0, augmentation=[]],
      Action [_action=SetVlanIdActionCase[_setVlanIdAction=SetVlanIdAction
     [_vlanId=VlanId [_value=1001], augmentation=[]],
     augmentation=[]], _key=ActionKey [_order=1], _order=1,
     augmentation=[]], Action [_action=OutputActionCase
     [_outputAction=OutputAction [_maxLength=65535,
     _outputNodeConnector=Uri [_value=openflow:1:6],
      augmentation=[]], augmentation=[]],
     _key=ActionKey [_order=2], _order=2,
      augmentation=[]]], augmentation=[]], augmentation=[]]

I can't see anything wrong with it.

=== End UPDATE 1 ===

=== Update 2 ===

When I remove the goto and follow the pattern of the xml here:
https://wiki.opendaylight.org/view/Editing_OpenDaylight_OpenFlow_Plugin:End_to_End_Flows:Example_Flows#Push_VLAN

it only works WITHOUT the goto. In other words if I remove the goto I can see the push flow in the config datastore. If I put the goto in, ONLY the goto appears.

==== End Update 2 ====

I see an issue in the issue tracker about vlan flows in opendaylight soutbound being broken but it appears to have been fixed in 2014 (?).

Is this fixed in nitrogen and how can I go about filing a bug against opendaylight?

Body:
Try this :

Integer VLAN_ETHERTYPE = 0x8100;
ActionBuilder actionBuilder = new ActionBuilder();
List<Action> actions = new ArrayList<>();

//push vlan
Action pushVlanAction = actionBuilder
    .setOrder(0).setAction(new PushVlanActionCaseBuilder()
        .setPushVlanAction(new PushVlanActionBuilder()
            .setEthernetType(VLAN_ETHERTYPE)
                .build())
                .build())
            .build();
actions.add(pushVlanAction);

//set vlan id
Action setVlanIdAction = actionBuilder
    .setOrder(1).setAction(new SetFieldCaseBuilder()
        .setSetField(new SetFieldBuilder()
            .setVlanMatch(new VlanMatchBuilder()
                .setVlanId(new VlanIdBuilder()
                    .setVlanId(new VlanId(vlanID))
                     .setVlanIdPresent(true)
                .build())
            .build())
        .build())
    .build())
    .build();
actions.add(setVlanIdAction);

Then, you need to add your actions into your instructions in the following way:

//ApplyActions
ApplyActions applyActions = new ApplyActionsBuilder().setAction(actions).build();

//Instruction
Instruction applyActionsInstruction = new InstructionBuilder()
        .setOrder(0).setInstruction(new ApplyActionsCaseBuilder()
                .setApplyActions(applyActions)
                .build())
            .build();

Also take a look here.


问:
How to add fact in CLIPS
I found function CLIPS Validate Text Entry there and I want to extend it this way:

```<code>(deffunction ask-question (?mark ?question $?allowed-values)
      (printout t ?question)
      (bind ?answer (read))
      (if (lexemep ?answer)
            then (bind ?answer (lowcase ?answer))
      **(assert car-mark(name ?mark))**
    )    (while (not (member ?answer ?allowed-values)) do
      (printout t ?question)
      (bind ?answer (read))
      (if (lexemep ?answer)
          then (bind ?answer (lowcase ?answer))
          **(assert car-mark(name ?mark))**
       )
    )    ?answer)
</code>```

So, I plan to add new car-mark in my facts if user input yes/y - else - not to add facts. But clips gives the error:

[PRNTUTIL2] Syntax Error:  Check appropriate syntax for RHS patterns.

ERROR:

```<code>(deffunction MAIN::ask-question
   (?mark ?question $?allowed-values)
   (printout t ?question)
   (bind ?answer (read))
   (if (lexemep ?answer)
      then
      (bind ?answer (lowcase ?answer))
      (assert car-mark
</code>```

There is my template for car-mark:

(deftemplate car-mark
    (slot name)
)

How to correctly add new fact and consider user input (yes - add, no - no add)?

答:
```<code>(assert (car-mark (name "foo")))
</code>```

Title: How to add fact in CLIPS

Body:
I found function CLIPS Validate Text Entry there and I want to extend it this way:

(deffunction ask-question (?mark ?question $?allowed-values)
      (printout t ?question)
      (bind ?answer (read))
      (if (lexemep ?answer)
            then (bind ?answer (lowcase ?answer))
      **(assert car-mark(name ?mark))**
    )    (while (not (member ?answer ?allowed-values)) do
      (printout t ?question)
      (bind ?answer (read))
      (if (lexemep ?answer)
          then (bind ?answer (lowcase ?answer))
          **(assert car-mark(name ?mark))**
       )
    )    ?answer)

So, I plan to add new car-mark in my facts if user input yes/y - else - not to add facts. But clips gives the error:

[PRNTUTIL2] Syntax Error:  Check appropriate syntax for RHS patterns.

ERROR:

(deffunction MAIN::ask-question
   (?mark ?question $?allowed-values)
   (printout t ?question)
   (bind ?answer (read))
   (if (lexemep ?answer)
      then
      (bind ?answer (lowcase ?answer))
      (assert car-mark

There is my template for car-mark:

(deftemplate car-mark
    (slot name)
)

How to correctly add new fact and consider user input (yes - add, no - no add)?

Body: (assert (car-mark (name "foo")))


问:
Show Date outside of defined MinDate MaxDate restrictions
I have googled and tried to find out, but was unable to get a solution on this problem. On page load I am Restricting datePicker with following min and max values:

```<code>$("#<%=txtboxDate.ClientID%>").datepicker({
minDate: new Date(2017, 2, 21),
 maxDate: new Date(2023, 07, 11) });
</code>```

But I also have data before 2017-2-21 <-(format of date given is yyyy-mm-dd)
Such as datePicker takes this format mm/dd/yy. So the date it receives is '2/1/2017'. It is out of minDate restriction.

How can I show these kind of dates or just this date 2/1/2017 on datePicker calender with same defined restrictions above jquery?

答:
Try This</p>

```<code><input id="dp" />

var d = $.datepicker.parseDate("mm/dd/yy", "12/21/2017");
$('#dp').datepicker({

    beforeShowDay: function (date) {
        return [date >= d, ''];
    }
});
$('#dp').datepicker("setDate", "12/10/2017");
</code>```

Body:
I have googled and tried to find out, but was unable to get a solution on this problem. On page load I am Restricting datePicker with following min and max values:

$("#<%=txtboxDate.ClientID%>").datepicker({
minDate: new Date(2017, 2, 21),
 maxDate: new Date(2023, 07, 11) });

But I also have data before 2017-2-21 <-(format of date given is yyyy-mm-dd)
Such as datePicker takes this format mm/dd/yy. So the date it receives is '2/1/2017'. It is out of minDate restriction.

How can I show these kind of dates or just this date 2/1/2017 on datePicker calender with same defined restrictions above jquery?

Body:
Try This

<input id="dp" />

var d = $.datepicker.parseDate("mm/dd/yy", "12/21/2017");
$('#dp').datepicker({

    beforeShowDay: function (date) {
        return [date >= d, ''];
    }
});
$('#dp').datepicker("setDate", "12/10/2017");


问:
Why cannot I format the font color as white

Please refer to the screenshot below, I need to change the font of the accordion heading to white. The code works well in "fiddle",but when I embedded the CSS snippet to a SharePoint 2013 page, the font color is not rendered correctly.

```<code>.accordionTitle,
.accordion__Heading {
  background-color: #00008B;
  text-align: center;
  font-weight: 700;
  padding: 2em;
  display: block;
  text-decoration: none;
  color:white;
  -webkit-transition: background-color 0.5s ease-in-out;
  transition: background-color 0.5s ease-in-out;
  border-bottom: 1px solid #8000000;
}
</code>```

答:
You have style overriding yours so you can be more specific like this :

```<code>a.accordionTitle,
a.accordion__Heading {
  background-color: #00008B;
  text-align: center;
  font-weight: 700;
  padding: 2em;
  display: block;
  text-decoration: none;
  color:white;
  -webkit-transition: background-color 0.5s ease-in-out;
  transition: background-color 0.5s ease-in-out;
  border-bottom: 1px solid #8000000;
}
</code>```

Or use important like this :

```<code>.accordionTitle,
.accordion__Heading {
  background-color: #00008B;
  text-align: center;
  font-weight: 700;
  padding: 2em;
  display: block;
  text-decoration: none;
  color:white!important;
  -webkit-transition: background-color 0.5s ease-in-out;
  transition: background-color 0.5s ease-in-out;
  border-bottom: 1px solid #8000000;
}
</code>```

You may read more about Specifity

Body:
Please refer to the screenshot below, I need to change the font of the accordion heading to white. The code works well in "fiddle",but when I embedded the CSS snippet to a SharePoint 2013 page, the font color is not rendered correctly.

.accordionTitle,
.accordion__Heading {
  background-color: #00008B;
  text-align: center;
  font-weight: 700;
  padding: 2em;
  display: block;
  text-decoration: none;
  color:white;
  -webkit-transition: background-color 0.5s ease-in-out;
  transition: background-color 0.5s ease-in-out;
  border-bottom: 1px solid #8000000;
}

Body:
You have style overriding yours so you can be more specific like this :

a.accordionTitle,
a.accordion__Heading {
  background-color: #00008B;
  text-align: center;
  font-weight: 700;
  padding: 2em;
  display: block;
  text-decoration: none;
  color:white;
  -webkit-transition: background-color 0.5s ease-in-out;
  transition: background-color 0.5s ease-in-out;
  border-bottom: 1px solid #8000000;
}

Or use important like this :

.accordionTitle,
.accordion__Heading {
  background-color: #00008B;
  text-align: center;
  font-weight: 700;
  padding: 2em;
  display: block;
  text-decoration: none;
  color:white!important;
  -webkit-transition: background-color 0.5s ease-in-out;
  transition: background-color 0.5s ease-in-out;
  border-bottom: 1px solid #8000000;
}

You may read more about Specifity


问:
Flink: Cluster Execution error of loss of Taskmanager
I am running the real time streaming program on the Flink with 1 master and 2 workers. One worker is running on the separate machine while another one is running on the master machine itself. I am using the JAR of my program in which the Parallelism is set to 2. Also I am read the data from Kafka with 2 brokers and 2 partitions.

With this scenario when I submit the job to the Flink cluster, it will run for a while and get failed with error java.lang.Exception: The slot in which the task was executed has been released. Probably loss of TaskManager 82f8941ff339603995e37c453f8ff401. What is the probable reason of the loss of taskmanager? (Only one Task-manager which is on the master machine is lost, another one is still there and being shown at Flink Web Interface.)

答:
As ulysses said in his anwer, you can increment the time used for the heartbeat or use an incremental Garbage Collector like G1GC (Flink's docker images already use this garbage collector if it's available).

To enable G1GC you have to add the following argument to the java command that launchs your flink's task manager:

-XX:+UseG1GC

You can find more info about this incremental Garbage collector in the following links:

Getting Started with the G1 Garbage Collector

Garbage First Garbage Collector Tuning


问:
Can't draw the epipolar lines in camera calibration and 3D- reconstruction using opencv & python
After I have generated the Fundamental and Essential Matrix from Camera calibration, I am trying to get the Epipolar lines, and draw them in my images to test the Matrix I have generated, following this python-opencv tutorial

Here is the code for impelementing the drawing epipolar lines function:

```<code>    def drawlines(img1,img2,lines,pts1,pts2):
        ''' img1 - image on which we draw the epilines for the points in img2
            lines - corresponding epilines
        '''
        r,c = img1.shape
        img1 = cv2.cvtColor(img1,cv2.COLOR_GRAY2BGR)
        img2 = cv2.cvtColor(img2,cv2.COLOR_GRAY2BGR)
        for r,pt1,pt2 in zip(lines,pts1,pts2):
            color = tuple(np.random.randint(0,255,3).tolist())
            x0,y0 = map(int, [0, -r[2]/r[1] ])
            x1,y1 = map(int, [c, -(r[2]+r[0]*c)/r[1] ])
            img1 = cv2.line(img1, (x0,y0), (x1,y1), color,1)
            img1 = cv2.circle(img1,tuple(pt1),5,color,-1)
            img2 = cv2.circle(img2,tuple(pt2),5,color,-1)
        return img1,img2
</code>```

but when I run the following code to generate the epipolar lines, I got this error:

Traceback (most recent call last):   File "FundMat.py", line 124,

  in          img5,img6 = drawlines(img1,img2,lines1,pts1,pts2)    File
  "FundMat.py",   line 21, in drawlines
        img1 = cv2.circle(img1,tuple(pt1),5,color,-1)

     TypeError: function takes exactly 2 arguments (1 given)

So, why I got this error and how to solve it?

答:
Your points are in a different format than OpenCV wants. Your pt1 and pt2 probably look something like np.array([[x, y]]), but look what the tuple looks like when you cast it:

```<code>>>> pt1 = np.array([[50, 50]])
>>> tuple(pt1)
(array([50, 50]),)
</code>```

This is a tuple with a single element, instead of two items like you expect. Obviously for drawing, it wants a tuple with length 2 (namely, the x and y coordinates). Hence the error; the inner function expects two arguments but only one value was inside your tuple. To demonstrate:

```<code>>>> pt1 = np.array([[50, 50]])
>>> cv2.circle(img, tuple(pt1), 5, 255, -1)
</code>```

```<code>Traceback (most recent call last):
  File "...", line 10, in <module>
    cv2.circle(img, tuple(pt1), 5, 255, -1) TypeError: function takes exactly 2 arguments (1 given)
</code>```

Instead, this is what you want the tuple to look like:

```<code>>>> tuple(pt1[0])
(50, 50)
</code>```

Supposing you want to be able to handle points passed in either format, just reshape the point first. Either way you only have two values in the pt1 or pt2 arrays, so reshaping won't affect it. For e.g. you could use flatten() from numpy:

```<code>>>> tuple(pt1.flatten())
(50, 50)
</code>```

And this should fix your issue.

```<code>>>> pt1 = np.array([[50, 50]])
>>> cv2.circle(img, tuple(pt1.flatten()), 5, 255, -1)
>>>
</code>```

Body:
After I have generated the Fundamental and Essential Matrix from Camera calibration, I am trying to get the Epipolar lines, and draw them in my images to test the Matrix I have generated, following this python-opencv tutorial

Here is the code for impelementing the drawing epipolar lines function:

    def drawlines(img1,img2,lines,pts1,pts2):
        ''' img1 - image on which we draw the epilines for the points in img2
            lines - corresponding epilines
        '''
        r,c = img1.shape
        img1 = cv2.cvtColor(img1,cv2.COLOR_GRAY2BGR)
        img2 = cv2.cvtColor(img2,cv2.COLOR_GRAY2BGR)
        for r,pt1,pt2 in zip(lines,pts1,pts2):
            color = tuple(np.random.randint(0,255,3).tolist())
            x0,y0 = map(int, [0, -r[2]/r[1] ])
            x1,y1 = map(int, [c, -(r[2]+r[0]*c)/r[1] ])
            img1 = cv2.line(img1, (x0,y0), (x1,y1), color,1)
            img1 = cv2.circle(img1,tuple(pt1),5,color,-1)
            img2 = cv2.circle(img2,tuple(pt2),5,color,-1)
        return img1,img2

but when I run the following code to generate the epipolar lines, I got this error:

Traceback (most recent call last):   File "FundMat.py", line 124,

  in          img5,img6 = drawlines(img1,img2,lines1,pts1,pts2)    File
  "FundMat.py",   line 21, in drawlines
        img1 = cv2.circle(img1,tuple(pt1),5,color,-1)

     TypeError: function takes exactly 2 arguments (1 given)

So, why I got this error and how to solve it?

Body:
Your points are in a different format than OpenCV wants. Your pt1 and pt2 probably look something like np.array([[x, y]]), but look what the tuple looks like when you cast it:

>>> pt1 = np.array([[50, 50]])
>>> tuple(pt1)
(array([50, 50]),)

This is a tuple with a single element, instead of two items like you expect. Obviously for drawing, it wants a tuple with length 2 (namely, the x and y coordinates). Hence the error; the inner function expects two arguments but only one value was inside your tuple. To demonstrate:

>>> pt1 = np.array([[50, 50]])
>>> cv2.circle(img, tuple(pt1), 5, 255, -1)

Traceback (most recent call last):
  File "...", line 10, in <module>
    cv2.circle(img, tuple(pt1), 5, 255, -1) TypeError: function takes exactly 2 arguments (1 given)

Instead, this is what you want the tuple to look like:

>>> tuple(pt1[0])
(50, 50)

Supposing you want to be able to handle points passed in either format, just reshape the point first. Either way you only have two values in the pt1 or pt2 arrays, so reshaping won't affect it. For e.g. you could use flatten() from numpy:

>>> tuple(pt1.flatten())
(50, 50)

And this should fix your issue.

>>> pt1 = np.array([[50, 50]])
>>> cv2.circle(img, tuple(pt1.flatten()), 5, 255, -1)
>>>