问:
Angular2: Form values not picked up
I've created this form inside ngOnInit() method:

```<code>this.cardForm = this.fb.group({
    card_number: ['', Validators.required],
    holderName: ['', Validators.required],
    expiry: ['', Validators.required],
    cvc: ['', Validators.required],
    address_line1: ['', Validators.required],
    address_line2: ['', Validators.required],
    address_city: ['', Validators.required],
    address_state: ['', Validators.required],
    address_zip: ['', Validators.required],
    address_country: ['', Validators.required]
  });
</code>```

On my template:

```<code><form [formGroup]="cardForm" novalidate="novalidate">
  <div class="form-group">
    <label for="cardnumber">Card number</label>
    <input
      type="text"
      name="cardnumber"
      class="input-transparent form-control"
      formControlName="card_number"
      data-mask="9999-9999-9999-9999"
      placeholder="____-____-____-____"
      required="required">
 </div>
</code>```

When I'm trying to get the values of this form, card_number, cvc and expiry are empty.

As you can see, cardForm have several fields. I've to say they are binded in two <from> tags on tamplate.

So, card_number, holderName, expiry and cvc are binded on first form:

```<code><form [formGroup]="cardForm" novalidate="novalidate">
  <input
    id="card_number"
    type="text"
    name="card_number"
    class="input-transparent form-control"
    formControlName="card_number"...
</code>```

and the other ones are binded on a second <form> tag:

```<code><form [formGroup]="cardForm" novalidate="novalidate">
  <input
    id="address_line1"
    type="text"
    name="address_line1"
    class="input-transparent form-control"
    formControlName="address_line1"...
</code>```

I've also tried to create two formGroup, and bind them to a each form on template:

```<code>this.cardForm = this.fb.group({
    card_number: ['', Validators.required],
    holderName: ['', Validators.required],
    expiry: ['', Validators.required],
    cvc: ['', Validators.required]
});
this.detailsForm = this.fb.group({
    address_line1: ['', Validators.required],
    address_line2: ['', Validators.required],
    address_city: ['', Validators.required],
    address_state: ['', Validators.required],
    address_zip: ['', Validators.required],
    address_country: ['', Validators.required]
  });
</code>```

On template:

```<code><form [formGroup]="cardForm" novalidate="novalidate">
<form [formGroup]="detailsForm" novalidate="novalidate">
</code>```

Nevertheless:

答:
For a similar case I used patchValue or setValue of that particular formgroup object.

For e.g in ngOnInityou can set:

```<code> this.cardForm.patchValue({card_number: 'foobar'});
</code>```

Again, if the value changes you can update in similar way.

```<code>cardDetailsChanged(val){
   this.cardForm.patchValue({card_number: val});
}
</code>```

Title: Angular2: Form values not picked up

Body:
I've created this form inside ngOnInit() method:

this.cardForm = this.fb.group({
    card_number: ['', Validators.required],
    holderName: ['', Validators.required],
    expiry: ['', Validators.required],
    cvc: ['', Validators.required],
    address_line1: ['', Validators.required],
    address_line2: ['', Validators.required],
    address_city: ['', Validators.required],
    address_state: ['', Validators.required],
    address_zip: ['', Validators.required],
    address_country: ['', Validators.required]
  });

On my template:

<form [formGroup]="cardForm" novalidate="novalidate">

    Card number
    <input
      type="text"
      name="cardnumber"
      class="input-transparent form-control"
      formControlName="card_number"
      data-mask="9999-9999-9999-9999"
      placeholder="____-____-____-____"
      required="required">

When I'm trying to get the values of this form, card_number, cvc and expiry are empty.

As you can see, cardForm have several fields. I've to say they are binded in two <from> tags on tamplate.

So, card_number, holderName, expiry and cvc are binded on first form:

<form [formGroup]="cardForm" novalidate="novalidate">
  <input
    id="card_number"
    type="text"
    name="card_number"
    class="input-transparent form-control"
    formControlName="card_number"...

and the other ones are binded on a second <form> tag:

<form [formGroup]="cardForm" novalidate="novalidate">
  <input
    id="address_line1"
    type="text"
    name="address_line1"
    class="input-transparent form-control"
    formControlName="address_line1"...

I've also tried to create two formGroup, and bind them to a each form on template:

this.cardForm = this.fb.group({
    card_number: ['', Validators.required],
    holderName: ['', Validators.required],
    expiry: ['', Validators.required],
    cvc: ['', Validators.required]
});
this.detailsForm = this.fb.group({
    address_line1: ['', Validators.required],
    address_line2: ['', Validators.required],
    address_city: ['', Validators.required],
    address_state: ['', Validators.required],
    address_zip: ['', Validators.required],
    address_country: ['', Validators.required]
  });

On template:

<form [formGroup]="cardForm" novalidate="novalidate">
<form [formGroup]="detailsForm" novalidate="novalidate">

Nevertheless:

Body:
For a similar case I used patchValue or setValue of that particular formgroup object.

For e.g in ngOnInityou can set:

 this.cardForm.patchValue({card_number: 'foobar'});

Again, if the value changes you can update in similar way.

cardDetailsChanged(val){
   this.cardForm.patchValue({card_number: val});
}


来源: stackexchange

问:
How can I make a tree with n number of child nodes?
Usually they have only two, but I need to make an object were there are a random number of pointers.
To represent this image enter image description here

Using what I know I made this:

```<code>struct tree{
    string name;
    list<struct pointer> pointers,

    tree(int x){
        name= x;
        pnext=null;
    }
} root1;

struct pointer{
    struct tree *pnext;
};
</code>```

A tree or object with a list of pointers and the structure for the pointers, but I doesn´t seem right.
How can I make a tree with a random number of pointers?
(I should say what is wrong with but I don´t een know were to start, sorry)

答:
try this:

```<code>#include <vector>

struct person {
    string name;

    vector<person> children;

    person(string iName, vector<person> iChildren) {
        name = iName;
        children = iChildren;
    }
}
</code>```

This way, each person has a name, and a vector with all of it's children in it.

ContentLicense: CC BY-SA 3.0

Body:
Usually they have only two, but I need to make an object were there are a random number of pointers.
To represent this image enter image description here

Using what I know I made this:

struct tree{
    string name;
    list<struct pointer> pointers,

    tree(int x){
        name= x;
        pnext=null;
    }
} root1;

struct pointer{
    struct tree *pnext;
};

A tree or object with a list of pointers and the structure for the pointers, but I doesn´t seem right.
How can I make a tree with a random number of pointers?
(I should say what is wrong with but I don´t een know were to start, sorry)

Body:
try this:

#include <vector>

struct person {
    string name;

    vector<person> children;

    person(string iName, vector<person> iChildren) {
        name = iName;
        children = iChildren;
    }
}

This way, each person has a name, and a vector with all of it's children in it.


问:
jquery array of integers into list in html
I have a simple task in jquery and html, but I'm not really getting anywhere.

I have an array of variable size whose content I'd like to present in a scrollable list.

The html code:

```<code><div id="listcss">
    <li id = "list">
    </li>
</div>
</code>```

and the coffeescript

```<code>$("#listcss").show()
$("#list").html(ids)
</code>```

Where ids is the incoming array.

Now when I run my code, this is the output:

Output

In this case, the array is 6 elements long, but in general this is a variable size x.

It's just displayed as one long chain of numbers. I would like to break it up, so I get a list with x entries under each other.

This must be possible rather easily, but I can't seem to find anything that works.

Thanks!

答:
If ids is an array, you can use Array.prototype.join() with parameter "
"

```<code> $("#list").html(ids.join("<br>"))
</code>```

Body:
I have a simple task in jquery and html, but I'm not really getting anywhere.

I have an array of variable size whose content I'd like to present in a scrollable list.

The html code:

and the coffeescript

$("#listcss").show()
$("#list").html(ids)

Where ids is the incoming array.

Now when I run my code, this is the output:

Output

In this case, the array is 6 elements long, but in general this is a variable size x.

It's just displayed as one long chain of numbers. I would like to break it up, so I get a list with x entries under each other.

This must be possible rather easily, but I can't seem to find anything that works.

Thanks!

Body:
If ids is an array, you can use Array.prototype.join() with parameter "<br>"

 $("#list").html(ids.join("<br>"))


问:
UITableView's deselectRowAtIndexPath prevents cell's subviews from changing background color
I am working on a tableview with custom cells. I need to highlight current selected (active) cell by setting background color for the title label, which is an immediate subview of cell.contentView. My code logic is like this (revised for better understanding):

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    UITableViewCell *previousActiveCell = [tableView cellForRowAtIndexPath:_indexPathActiveCell]; // previous selection
    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath: indexPath]; // current selection

    UILabel *labelpreviousActiveCellTitle = [previousActiveCell.contentView viewWithTag:SUBVIEW_TAG_TITLE_LABEL];
    UILabel *labelSelectedCellTitle = [selectedCell.contentView viewWithTag:SUBVIEW_TAG_TITLE_LABEL];

    labelpreviousActiveCellTitle.backgroundColor = [UIColor clearColor]; // remove highlighting from previous selection
    labelSelectedCellTitle.backgroundColor = [UIColor redColor]; // highlighted

    _indexPathActiveCell = indexPath; // update _indexPathActiveCell with current selection
}
</code>```

The problem is, when a new cell is selected, the highlighting background color appears for a very short moment, about half a second, and then disappears. If I comment out the calling for deselectRowAtIndexPath,

```<code>// [tableView deselectRowAtIndexPath:indexPath animated:YES];
</code>```

the highlighting background color will retain. My guess is that deselectRowAtIndexPath remembers all the subviews' previous background color and when it recovers the cell from the shaded background, it changes all the subviews' background color back.

My workaround is adding a delay like this:

```<code>dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    labelpreviousActiveCellTitle.backgroundColor = [UIColor clearColor];
    labelSelectedCellTitle.backgroundColor = [UIColor redColor];
});
</code>```

and it works. Note that I also tried a shorter delay like 0.01 second which did not work.

Setting the delay time with a magic number is an unpleasant way. My question is, is there any better way to set the background color for cell's subviews in tableview's didSelectRowAtIndexPath delegate method? Thanks in advance.

答:
Have you tried creating a custom cell that inherits from UITableViewCell?

The custom cell would have a label as a public property so you can reference the label from your controller, without tagging.

Body:
I am working on a tableview with custom cells. I need to highlight current selected (active) cell by setting background color for the title label, which is an immediate subview of cell.contentView. My code logic is like this (revised for better understanding):

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    UITableViewCell *previousActiveCell = [tableView cellForRowAtIndexPath:_indexPathActiveCell]; // previous selection
    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath: indexPath]; // current selection

    UILabel *labelpreviousActiveCellTitle = [previousActiveCell.contentView viewWithTag:SUBVIEW_TAG_TITLE_LABEL];
    UILabel *labelSelectedCellTitle = [selectedCell.contentView viewWithTag:SUBVIEW_TAG_TITLE_LABEL];

    labelpreviousActiveCellTitle.backgroundColor = [UIColor clearColor]; // remove highlighting from previous selection
    labelSelectedCellTitle.backgroundColor = [UIColor redColor]; // highlighted

    _indexPathActiveCell = indexPath; // update _indexPathActiveCell with current selection
}

The problem is, when a new cell is selected, the highlighting background color appears for a very short moment, about half a second, and then disappears. If I comment out the calling for deselectRowAtIndexPath,

// [tableView deselectRowAtIndexPath:indexPath animated:YES];

the highlighting background color will retain. My guess is that deselectRowAtIndexPath remembers all the subviews' previous background color and when it recovers the cell from the shaded background, it changes all the subviews' background color back.

My workaround is adding a delay like this:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    labelpreviousActiveCellTitle.backgroundColor = [UIColor clearColor];
    labelSelectedCellTitle.backgroundColor = [UIColor redColor];
});

and it works. Note that I also tried a shorter delay like 0.01 second which did not work.

Setting the delay time with a magic number is an unpleasant way. My question is, is there any better way to set the background color for cell's subviews in tableview's didSelectRowAtIndexPath delegate method? Thanks in advance.


问:
Html 5 required on radio button wil not reset
Why won't an html5 required on radio button group reset with form reset button if it was selected. for example you have a radio button group in a form with the html5 required set if you select one of the radio buttons then click the reset form button it doesn't reset the radio button group required validation so even though the form was reset. So basically you click submit button without selecting anything the radio buttons are given an outline in red then you select one and click reset you are then able to submit the form without selecting a radio button? any help on why it does this would be greatly appreciated. I may misunderstand how its supposed to work.
Simple test</p>

```<code>   <html>
   <form>
   <input type="radio" name="test" required>
   <input type="radio" name="test" required>
   <input type="submit" value="submit">
   <input type="reset" value="cancel">
   </form>
   </html>
</code>```

答:
It is because you are using same name for the radio buttons.If you give the same name only one radio button of the can be checked.And so it passes the Validation

Example : Different name for radio buttons.

<form>
   <input type="radio" name="test" required>
   <input type="radio" name="test2" required>
   <input type="submit" value="submit">
   <input type="reset" value="cancel">
   </form>```
</div>
</div>
</p>

<p>Example : Same name for radio buttons.
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
       <input type="radio" name="test" required>
       <input type="radio" name="test" required>
       <input type="submit" value="submit">
       <input type="reset" value="cancel">
</form></code>```

Body:
Why won't an html5 required on radio button group reset with form reset button if it was selected. for example you have a radio button group in a form with the html5 required set if you select one of the radio buttons then click the reset form button it doesn't reset the radio button group required validation so even though the form was reset. So basically you click submit button without selecting anything the radio buttons are given an outline in red then you select one and click reset you are then able to submit the form without selecting a radio button? any help on why it does this would be greatly appreciated. I may misunderstand how its supposed to work.
Simple test

   <form>
   <input type="radio" name="test" required>
   <input type="radio" name="test" required>
   <input type="submit" value="submit">
   <input type="reset" value="cancel">
   </form>

Body:
It is because you are using same name for the radio buttons.If you give the same name only one radio button of the can be checked.And so it passes the Validation

Example : Different name for radio buttons.

<form>
   <input type="radio" name="test" required>
   <input type="radio" name="test2" required>
   <input type="submit" value="submit">
   <input type="reset" value="cancel">
   </form>

Example : Same name for radio buttons.

<form>
       <input type="radio" name="test" required>
       <input type="radio" name="test" required>
       <input type="submit" value="submit">
       <input type="reset" value="cancel">
</form>


问:
are there any Query Optimization Tools for SQL Server?
Are there any tools that do Query Optimizations for SQL Server 2005 and above?

I've searched & didn't find anything.

What do you recommend?

If this Question was repeated before you can close it but I didn't see anything similar

答: One of the best query optimizers is just running the query in SQL Management Studio, and then inspecting the query plan. This will give you clues as to what indexes it is (or is not) using, and how you can change the query to take advantage of those.</p>

ContentLicense: CC BY-SA 2.5


问:
How to get JS value in UIWebView in Swift?
I've added to my HTML these lines:

```<code>"</script>$(document).ready(func a() {
    $('img').click(function(){
        return $(this).attr('src');
    });
});</script>"
</code>```

and if I set instead of return - alert, then I get what I need.

Later I've tried this on my tap recognizer function:

```<code>var a = self.webView.stringByEvaluatingJavaScriptFromString("a()")
print(a)
</code>```

but it prints me an empty string. What I do wrong? Can anyone help me to fix that?

答: I may be a little late but AFAIK you should call "a();". You might be missing the semicolon</p>

Body:
I've added to my HTML these lines:

"</script>$(document).ready(func a() {
    $('img').click(function(){
        return $(this).attr('src');
    });
});</script>"

and if I set instead of return - alert, then I get what I need.

Later I've tried this on my tap recognizer function:

var a = self.webView.stringByEvaluatingJavaScriptFromString("a()")
print(a)

but it prints me an empty string. What I do wrong? Can anyone help me to fix that?


问:
Make webpack paths relative to current directory

The Question:

I am using Rails 5.0 with Webpacker, and I am trying to setup our initial Webpack config. In Rails+Webpacker Webpack generates a different build file for each item in the app/javascript/packs folder. Is there a way to get these Webpack "packs" to resolve different paths for modules based on a files containing folder?

The Problem:

Redundant sections of paths in my import statements resulting in imports like:

main/pages/home.js:

```<code>import Engine from 'main/engine'
import Routes from 'main/engine/routes.js'
</code>```

dev_panel/pages/home.js:

```<code>import Engine from 'dev_panel/engine'
import Routes from 'dev_panel/engine/routes.js'
</code>```

etc...

And this is compounded for every file and subdirectory of course. This is not only monotonous, but also makes re-organization of files and code a headache.

Desired Pattern:

main/pages/home.js:

```<code>// but still refers to /main/engine/routes.js
import Engine from 'engine'
import Routes from 'engine/routes.js'
</code>```

dev_panel/pages/home.js:

```<code>// but still refers to /dev_panel/engine/routes.js
import Engine from 'engine'
import Routes from 'engine/routes.js'
</code>```

etc...

Example Structure:

```<code>app/javascript
├── packs
│   ├── dev_panel.js
│   ├── admin_panel.js
│   └── main.js
├── main
│   ├── data.js
│   ├── engine
│   │   ├── index.js
│   │   └── routes.js
│   ├── index.js
│   └── pages
│       ├── home.js
│       └── index.js
├── dev_panel
│   ├── data.js
│   ├── engine
│   │   ├── index.js
│   │   └── routes.js
│   ├── index.js
│   └── pages
│       ├── home.js
│       └── index.js
└── admin_panel.js
    ├── data.js
    ├── engine
    │   ├── index.js
    │   └── routes.js
    ├── index.js
    └── pages
        ├── home.js
        └── index.js
</code>```

答:
You can create a file common-exports.js at the top directory which reexports things that you import in many files. That way you can import everything from that file.

common-exports.js:

```<code>export { default as Engine } from 'main/engine';
export { default as Routes } from 'main/engine/routes';
</code>```

main/pages/home.js:

```<code>import { Engine, Routes } from 'common-exports';
</code>```

Body:
The Question:

I am using Rails 5.0 with Webpacker, and I am trying to setup our initial Webpack config. In Rails+Webpacker Webpack generates a different build file for each item in the app/javascript/packs folder. Is there a way to get these Webpack "packs" to resolve different paths for modules based on a files containing folder?

The Problem:

Redundant sections of paths in my import statements resulting in imports like:

main/pages/home.js:

import Engine from 'main/engine'
import Routes from 'main/engine/routes.js'

dev_panel/pages/home.js:

import Engine from 'dev_panel/engine'
import Routes from 'dev_panel/engine/routes.js'

etc...

And this is compounded for every file and subdirectory of course. This is not only monotonous, but also makes re-organization of files and code a headache.

Desired Pattern:

main/pages/home.js:

// but still refers to /main/engine/routes.js
import Engine from 'engine'
import Routes from 'engine/routes.js'

dev_panel/pages/home.js:

// but still refers to /dev_panel/engine/routes.js
import Engine from 'engine'
import Routes from 'engine/routes.js'

etc...

Example Structure:

app/javascript
├── packs
│   ├── dev_panel.js
│   ├── admin_panel.js
│   └── main.js
├── main
│   ├── data.js
│   ├── engine
│   │   ├── index.js
│   │   └── routes.js
│   ├── index.js
│   └── pages
│       ├── home.js
│       └── index.js
├── dev_panel
│   ├── data.js
│   ├── engine
│   │   ├── index.js
│   │   └── routes.js
│   ├── index.js
│   └── pages
│       ├── home.js
│       └── index.js
└── admin_panel.js
    ├── data.js
    ├── engine
    │   ├── index.js
    │   └── routes.js
    ├── index.js
    └── pages
        ├── home.js
        └── index.js

Body:
You can create a file common-exports.js at the top directory which reexports things that you import in many files. That way you can import everything from that file.

common-exports.js:

export { default as Engine } from 'main/engine';
export { default as Routes } from 'main/engine/routes';

main/pages/home.js:

import { Engine, Routes } from 'common-exports';


问:
html2canvas is not working properly while taking snap of a div containing gmap (Google Map)
I'm am converting a div containing google map inside to image but it is not showing as it was.

I'm using angular4.

My original image was as follows:

but after converting with html2canvas shows as follows:

My code for conversion is as follows:

```<code>html2Cnv(){
    let self = this;
    let mycnvHtml: HTMLVideoElement = self.mycnvHtml.nativeElement;
    html2canvas(mycnvHtml, {
      onrendered: function(canvas1) {
        canvas1.toBlob((blob: Blob)=>{
          let file = new File([blob], 'msr-' + (new Date).toISOString().replace(/:|\./g, '-') + '.webm', {
            type: 'image/png'
          });
          self.fileShare.addFile(file);
          self.onDone.emit(file);
        }, "image/png");
      }
    });
  }
</code>```

答:
In place of converting div containing google map to canvas I followed following steps and I reached closed to my requirement except it didn't gave route

Original div
  After Conversion

Get URL of Map

getCordDistance() {
    let radlat1 = Math.PI * this.locStart.lat/180;
    let radlat2 = Math.PI * this.locEnd.lat/180;
    let theta = this.locStart.lng-this.locEnd.lng;
    let radtheta = Math.PI * theta/180;
    let dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
    dist = Math.acos(dist);
    dist = dist * 180/Math.PI;
    dist = dist * 60 * 1.1515;
    /*if (unit=="K") { dist = dist * 1.609344 }
    if (unit=="N") { dist = dist * 0.8684 }*/
    return dist
  }

getImgUrl(cll){
    let dist=this.getCordDistance();
    let comn={
      lat:((this.locStart.lat+this.locEnd.lat)/2),
      lng:((this.locStart.lng+this.locEnd.lng)/2)
    };
    try {
      let ppp=document.getElementById('map456');
      this.dynamicImg='https://maps.googleapis.com/maps/api/staticmap?' +
        'center=' +comn.lat+','+comn.lng +
        '&zoom='+(dist<1?15:dist>1800?3:dist>900?4:this.mapRef.getZoom())+
        '&size='+ppp.offsetWidth+'x'+ppp.offsetHeight +
        '&maptype=roadmap'+
        '&markers=color:blue%7Clabel:S%7C'+this.locStart.lat+','+this.locStart.lng +
        '&markers=color:red%7Clabel:C%7C'+this.locEnd.lat+','+this.locEnd.lng +
        '&key=myKey';
    }catch(er){console.log(er)}
    if(cll){
      cll()
    }
  }

Do an ajax request to get image blob if you just need image of map

html2Cnv(){
    let self = this;
    this.getImgUrl(()=>{
      let oReq = new XMLHttpRequest();
      oReq.open("GET", this.dynamicImg, true);
      oReq.responseType = "arraybuffer";
      oReq.onload =(oEvent)=>{
        let blob = new Blob([oReq.response], {type: "image/png"});
        let file = new File([blob], 'msr-' + (new Date).toISOString().replace(/:|\./g, '-') + '.webm', {
          type: 'image/png'
        });
        self.fileShare.addFile(file);
        self.onDone.emit(file);
      };
      oReq.send();
    });
  }

Else create a duplicate content same as the div we want to take screenshot but in place of google map create an img tag with src as found in first step

html2Cnv(){
    let self = this;
    this.getImgUrl(()=>{
      html2canvas(this.canvas1, {
        onrendered: function(canvas1) {
          canvas1.toBlob((blob: Blob)=>{
            let file = new File([blob], 'msr-' + (new Date).toISOString().replace(/:|\./g, '-') + '.webm', {
              type: 'image/png'
            });
            self.fileShare.addFile(file);
            self.onDone.emit(file);
          }, "image/png");
        }
      });
    })
  }

Body:
I'm am converting a div containing google map inside to image but it is not showing as it was.

I'm using angular4.

My original image was as follows:

but after converting with html2canvas shows as follows:

My code for conversion is as follows:

html2Cnv(){
    let self = this;
    let mycnvHtml: HTMLVideoElement = self.mycnvHtml.nativeElement;
    html2canvas(mycnvHtml, {
      onrendered: function(canvas1) {
        canvas1.toBlob((blob: Blob)=>{
          let file = new File([blob], 'msr-' + (new Date).toISOString().replace(/:|\./g, '-') + '.webm', {
            type: 'image/png'
          });
          self.fileShare.addFile(file);
          self.onDone.emit(file);
        }, "image/png");
      }
    });
  }


问:
Framework not found (RoboVM Google adMob)
I am trying to add google admob to my Libgdx project that uses RoboVM. I followed the guide here: https://github.com/robovm/robovm-robopods/tree/master/google-mobile-ads/ios but I am getting this error:

```<code>ERROR] ld: framework not found GoogleMobileAds
[ERROR] clang: error: linker command failed with exit code 1 (use -v to
see invocation)
[ERROR] Couldn't compile app
</code>```

However I followed the instructions to put the following code in the robovm.xml file:

```<code><config>
  <executableName>${app.executable}</executableName>
  <mainClass>${app.mainclass}</mainClass>
  <os>ios</os>
  <arch>thumbv7</arch>
  <target>ios</target>
  <iosInfoPList>Info.plist.xml</iosInfoPList>
  <resources>
    <resource>
      <directory>../android/assets</directory>
      <includes>
        <include>**</include>
      </includes>
      <skipPngCrush>true</skipPngCrush>
    </resource>
    <resource>
      <directory>data</directory>
    </resource>
  </resources>
  <forceLinkClasses>
    <pattern>com.badlogic.gdx.scenes.scene2d.ui.*</pattern>
    <pattern>com.badlogic.gdx.graphics.g3d.particles.**</pattern>
    <pattern>com.android.okhttp.HttpHandler</pattern>
    <pattern>com.android.okhttp.HttpsHandler</pattern>
    <pattern>com.android.org.conscrypt.**</pattern>
    <pattern>com.android.org.bouncycastle.jce.provider.BouncyCastleProvider</pattern>
    <pattern>com.android.org.bouncycastle.jcajce.provider.keystore.BC$Mappings</pattern>
    <pattern>com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi</pattern>
    <pattern>com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi$Std</pattern>
    <pattern>com.android.org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi</pattern>
    <pattern>com.android.org.bouncycastle.crypto.digests.AndroidDigestFactoryOpenSSL</pattern>
    <pattern>org.apache.harmony.security.provider.cert.DRLCertFactory</pattern>
    <pattern>org.apache.harmony.security.provider.crypto.CryptoProvider</pattern>
  </forceLinkClasses>
  <libs>
      <lib>z</lib>
  </libs>
  <frameworkPaths>
    <path>libs</path>
  </frameworkPaths>
  <frameworks>
    <framework>UIKit</framework>
    <framework>OpenGLES</framework>
    <framework>QuartzCore</framework>
    <framework>CoreGraphics</framework>
    <framework>OpenAL</framework>
    <framework>AudioToolbox</framework>
    <framework>AVFoundation</framework>
    <framework>GoogleMobileAds</framework>
  </frameworks>
</config>
</code>```

EDIT:
Here's the build.gradle for iOS module:

```<code>sourceSets.main.java.srcDirs = [ "src/" ]

sourceCompatibility = '1.7'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

ext {
    mainClassName = "com.samuel.doubledodge.IOSLauncher"
}

launchIPhoneSimulator.dependsOn build
launchIPadSimulator.dependsOn build
launchIOSDevice.dependsOn build
createIPA.dependsOn build

robovm {
    archs = "thumbv7:arm64"
}

eclipse.project {
    name = appName + "-ios"
    natures 'org.robovm.eclipse.RoboVMNature'
}
</code>```

答: To anyone who was having this issue, TomGrillGames' solution in the comments above was what solved my problem.I was putting it in the ios/builds/libs instead of ios/libs.

Body:
I am trying to add google admob to my Libgdx project that uses RoboVM. I followed the guide here: https://github.com/robovm/robovm-robopods/tree/master/google-mobile-ads/ios but I am getting this error:

ERROR] ld: framework not found GoogleMobileAds
[ERROR] clang: error: linker command failed with exit code 1 (use -v to
see invocation)
[ERROR] Couldn't compile app

However I followed the instructions to put the following code in the robovm.xml file:

<config>
  <executableName>${app.executable}</executableName>
  <mainClass>${app.mainclass}</mainClass>
  <os>ios</os>
  <arch>thumbv7</arch>
  <target>ios</target>
  <iosInfoPList>Info.plist.xml</iosInfoPList>
  <resources>
    <resource>
      <directory>../android/assets</directory>
      <includes>
        <include>**</include>
      </includes>
      <skipPngCrush>true</skipPngCrush>
    </resource>
    <resource>
      <directory>data</directory>
    </resource>
  </resources>
  <forceLinkClasses>
    <pattern>com.badlogic.gdx.scenes.scene2d.ui.*</pattern>
    <pattern>com.badlogic.gdx.graphics.g3d.particles.**</pattern>
    <pattern>com.android.okhttp.HttpHandler</pattern>
    <pattern>com.android.okhttp.HttpsHandler</pattern>
    <pattern>com.android.org.conscrypt.**</pattern>
    <pattern>com.android.org.bouncycastle.jce.provider.BouncyCastleProvider</pattern>
    <pattern>com.android.org.bouncycastle.jcajce.provider.keystore.BC$Mappings</pattern>
    <pattern>com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi</pattern>
    <pattern>com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi$Std</pattern>
    <pattern>com.android.org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi</pattern>
    <pattern>com.android.org.bouncycastle.crypto.digests.AndroidDigestFactoryOpenSSL</pattern>
    <pattern>org.apache.harmony.security.provider.cert.DRLCertFactory</pattern>
    <pattern>org.apache.harmony.security.provider.crypto.CryptoProvider</pattern>
  </forceLinkClasses>
  <libs>
      <lib>z</lib>
  </libs>
  <frameworkPaths>
    <path>libs</path>
  </frameworkPaths>
  <frameworks>
    <framework>UIKit</framework>
    <framework>OpenGLES</framework>
    <framework>QuartzCore</framework>
    <framework>CoreGraphics</framework>
    <framework>OpenAL</framework>
    <framework>AudioToolbox</framework>
    <framework>AVFoundation</framework>
    <framework>GoogleMobileAds</framework>
  </frameworks>
</config>

EDIT:
Here's the build.gradle for iOS module:

sourceSets.main.java.srcDirs = [ "src/" ]

sourceCompatibility = '1.7'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

ext {
    mainClassName = "com.samuel.doubledodge.IOSLauncher"
}

launchIPhoneSimulator.dependsOn build
launchIPadSimulator.dependsOn build
launchIOSDevice.dependsOn build
createIPA.dependsOn build

robovm {
    archs = "thumbv7:arm64"
}

eclipse.project {
    name = appName + "-ios"
    natures 'org.robovm.eclipse.RoboVMNature'
}


问:
Display problem with Update Panel in ASP.NET
I'll try to explain my problem the best I can, here goes:  I have an update panel on an ASP.NET page and a Panel server control inside it.  I have an rounded corners extender attached to the Panel server control and the extender has a solid background with a solid border.

ok....I haven't found an easy easy to position the update panel itself, so, what I end up doing is trying to position the Panel server control with CSS.  Once I do and I run the project to see the finished product, there is a big gap from where the update panel control starts and where the Panel is positioned.

What I'm wanting to know is:  What's the best way to position an UpdatePanel or regular panel so that gap that I'm talking about doesn't show up??

If anyone needs me to clarify, let me know in the comments and I'll try my best.

答: Try changing the RenderMode of the update panel from Block to Inline.

OwnerDisplayName: Robert Iver

OwnerDisplayName: Robert C. Barth


答:
The best tool I've ever used for optimizing queries in MS SQL Server, by far, is the "Include Actual Execution Plan" option in Microsoft SQL Server Management Studio.  It displays detailed information about the execution path taken by the server when running your query.  (Note that this works best when there's data in the tables.  Of course, without a good bit of test data, any optimization is purely theoretical anyway.)

It basically gives you three very important things:

It tells you which steps take the most processing time and what they're doing at that step.

It tells you which steps carry the most data to the next step, including how many records, which helps identify places where you can be more specific about the data you want and exclude unnecessary records.

It gives you a ton of insight into the inner workings of SQL Server and what it does with your queries.  This knowledge will help you optimize things a lot over time.

Title: are there any Query Optimization Tools for SQL Server?

Body:
Are there any tools that do Query Optimizations for SQL Server 2005 and above?

I've searched & didn't find anything.

What do you recommend?

If this Question was repeated before you can close it but I didn't see anything similar


问:
Can a component realize a service in Archimate 3?
In the Archimate 3 Application Layer Metamodel there is no explicit realization relation between an "Application Component" and an "Application Service". However, in the example of section 12.3 there is such relation. How should I understand this?</p>

答:
New Answer to an old question, but there is a set of rules to follow when deriving relationships, as noted in the ArchiMate 3.0 Specification:

The structural and dependency relationships can be ordered by
  ‘strength’. Structural relationships are ‘stronger’ than dependency
  relationships, and the relationships within these categories can also
  be ordered by strength:

•          Influence (weakest)

•          Access

•          Serving

•          Realization

•          Assignment

•          Aggregation

•          Composition (strongest)

So for example if oyu have an application component and an application service, you have a an Assignement between the application function and the application component and a Realization between the application function and the application function.

So to take out the application function, you have to represent the relationship between the component and the service by the weakest, which is the Realization in this case.


问:
Running local-exec provisioner on all EC2 instances after creation
I currently have a Terraform file to create EC2 instances on AWS that looks like this:

```<code>resource "aws_instance" "influxdata" {
  count      = "${var.ec2-count-influx-data}"

  ami           = "${module.amis.rhel73_id}"
  instance_type = "${var.ec2-type-influx-data}"

  vpc_security_group_ids = ["${var.sg-ids}"]
  subnet_id              = "${element(module.infra.subnet,count.index)}"
  key_name               = "${var.KeyName}"
  iam_instance_profile   = "Custom-role"

  tags {
    Name               = "influx-data-node"
    ASV                = "${module.infra.ASV}"
    CMDBEnvironment    = "${module.infra.CMDBEnvironment}"
    OwnerContact       = "${module.infra.OwnerContact}"
    custodian_downtime = "off"
    OwnerEid           = "${var.OwnerEid}"
  }

  ebs_block_device {
    device_name = "/dev/sdg"
    volume_size = 500
    volume_type = "io1"
    iops = 2000
    encrypted = true
    delete_on_termination = true
  }

  user_data = "${file("terraform/attach_ebs.sh")}"

  connection {
    private_key = "${file("/Users/usr111/Downloads/usr111_CD.pem")}"
    user        = "ec2-user"
  }

  provisioner "remote-exec" {
    inline = ["echo just checking for ssh. ttyl. bye."]
  }

  provisioner "local-exec" {
    command = <<EOF
ansible-playbook base-data.yml --key-file=/Users/usr111/Downloads/usr111_CD.pem --user=ec2-user -b -i "${self.private_ip},"
    EOF
  }
}

resource "aws_route53_record" "influx-data-route" {

  count = "${var.ec2-count-influx-data}"
  zone_id = "${var.r53-zone}"
  name = "influx-data-0${count.index}"
  type = "A"
  ttl = "300"
  // matches up record N to instance N
  records = ["${element(aws_instance.influxdata.*.private_ip, count.index)}"]
}

resource "local_file" "inventory-meta" {
  filename = "inventory"

  content = <<-EOF
[meta]
${join("\n",aws_instance.influxmeta.*.private_ip)}

[data]
${join("\n",aws_instance.influxdata.*.private_ip)}
  EOF
}
</code>```

What I'm struggling to figure out is to get this part to run after I create the inventory file:

```<code>  provisioner "local-exec" {
    command = <<EOF
ansible-playbook base-data.yml --key-file=/Users/usr111/Downloads/usr111_CD.pem --user=ec2-user -b -i "${self.private_ip},"
    EOF
  }
</code>```

Right now I'm passing an IP into Ansible but I want to pass in the inventory file, which is only created after Terraform provisions all of the instances.

答:
since you are using AWS maybe you could try using the Dynamic Inventory script and your provisioner could look like this:

```<code>provisioner "local-exec" {
   command = "ansible-playbook -i ec2.py playbook.yml --limit ${self.public_ip}" }
</code>```

In your playbook you are going to need to wait for SSH to become available since Ansible is making the connection and not Terraform.

```<code>- name: wait for ssh
  hosts: localhost
  gather_facts: no

  tasks:
    - local_action: wait_for port=22 host="{{ ip }}" search_regex=OpenSSH delay=10
</code>```

So the command should look like this:

```<code>provisioner "local-exec" {
   command = "ansible-playbook -i ec2.py playbook.yml --limit ${self.public_ip}" --extra-vars 'ip=${self.public_ip}'}
</code>```

You can also copy your playbooks to the host with the "File Provisioner", install ansible and run the playbook locally with "remote-exec", but that's up to you.

ContentLicense: CC BY-SA 4.0

Body:
I currently have a Terraform file to create EC2 instances on AWS that looks like this:

resource "aws_instance" "influxdata" {
  count      = "${var.ec2-count-influx-data}"

  ami           = "${module.amis.rhel73_id}"
  instance_type = "${var.ec2-type-influx-data}"

  vpc_security_group_ids = ["${var.sg-ids}"]
  subnet_id              = "${element(module.infra.subnet,count.index)}"
  key_name               = "${var.KeyName}"
  iam_instance_profile   = "Custom-role"

  tags {
    Name               = "influx-data-node"
    ASV                = "${module.infra.ASV}"
    CMDBEnvironment    = "${module.infra.CMDBEnvironment}"
    OwnerContact       = "${module.infra.OwnerContact}"
    custodian_downtime = "off"
    OwnerEid           = "${var.OwnerEid}"
  }

  ebs_block_device {
    device_name = "/dev/sdg"
    volume_size = 500
    volume_type = "io1"
    iops = 2000
    encrypted = true
    delete_on_termination = true
  }

  user_data = "${file("terraform/attach_ebs.sh")}"

  connection {
    private_key = "${file("/Users/usr111/Downloads/usr111_CD.pem")}"
    user        = "ec2-user"
  }

  provisioner "remote-exec" {
    inline = ["echo just checking for ssh. ttyl. bye."]
  }

  provisioner "local-exec" {
    command = <<EOF
ansible-playbook base-data.yml --key-file=/Users/usr111/Downloads/usr111_CD.pem --user=ec2-user -b -i "${self.private_ip},"
    EOF
  }
}

resource "aws_route53_record" "influx-data-route" {

  count = "${var.ec2-count-influx-data}"
  zone_id = "${var.r53-zone}"
  name = "influx-data-0${count.index}"
  type = "A"
  ttl = "300"
  // matches up record N to instance N
  records = ["${element(aws_instance.influxdata.*.private_ip, count.index)}"]
}

resource "local_file" "inventory-meta" {
  filename = "inventory"

  content = <<-EOF
[meta]
${join("\n",aws_instance.influxmeta.*.private_ip)}

[data]
${join("\n",aws_instance.influxdata.*.private_ip)}
  EOF
}

What I'm struggling to figure out is to get this part to run after I create the inventory file:

  provisioner "local-exec" {
    command = <<EOF
ansible-playbook base-data.yml --key-file=/Users/usr111/Downloads/usr111_CD.pem --user=ec2-user -b -i "${self.private_ip},"
    EOF
  }

Right now I'm passing an IP into Ansible but I want to pass in the inventory file, which is only created after Terraform provisions all of the instances.

Body:
since you are using AWS maybe you could try using the Dynamic Inventory script and your provisioner could look like this:

provisioner "local-exec" {
   command = "ansible-playbook -i ec2.py playbook.yml --limit ${self.public_ip}" }

In your playbook you are going to need to wait for SSH to become available since Ansible is making the connection and not Terraform.

- name: wait for ssh
  hosts: localhost
  gather_facts: no

  tasks:
    - local_action: wait_for port=22 host="{{ ip }}" search_regex=OpenSSH delay=10

So the command should look like this:

provisioner "local-exec" {
   command = "ansible-playbook -i ec2.py playbook.yml --limit ${self.public_ip}" --extra-vars 'ip=${self.public_ip}'}

You can also copy your playbooks to the host with the "File Provisioner", install ansible and run the playbook locally with "remote-exec", but that's up to you.


问:
WCF Test Client sends Null value to service when XML string entered as parameter
Using C#, I've been trying to receive XML as a string, from the client, in a SOAP WCF service (not my choice, it's the way the client is choosing to send it) and I couldn't get it to work correctly in the WCF Test Client. I thought that I had found the problem. I assumed that the backslashes in the closing XML Tags would cause WCF Test Client to parse incorrectly and send a null value to my service without throwing any exceptions or anything in the WCF Test Client. See the link below.

http://programmersranch.blogspot.com/2014/08/c-wcf-backslash-limitation-in-wcf-test.html

However, that does not seem to be the issue, as the slashes in XML are / slashes and the slashes that cause problems are \ slashes. Any suggestions? Here is the string I am copy + pasting into the string parameter for one of my service methods in WCF Test Client. I have escaped the quotation marks and so on to avoid issues with the string parsing, but it doesn't work even after escaping them.

```<code><?xml version=\"1.0\"?><QBXML><QBXMLMsgsRs><ItemNonInventoryQueryRs requestID=\"SXRlbVF1ZXJ5fDEyMA==\" statusCode=\"500\" statusSeverity=\"Warn\" statusMessage=\"The query request has not been fully completed. There was a required element 'your item name' that could not be found in QuickBooks.\"/></QBXMLMsgsRs></QBXML>
</code>```

Also, I want to point out that if I enter a string like "BOB" or "sally2135" or something that's not XML at all, it receives the string just fine. It just doesn't like the XML string.

Thanks!

答: As it turns out, the solution is embarrassingly simple. Just minutes after asking a question I've been working on for a few hours now, I found the answer. Upon removing the \ before all of the quotation marks in the string, I received the XML string without a problem. </p>

Body:
Using C#, I've been trying to receive XML as a string, from the client, in a SOAP WCF service (not my choice, it's the way the client is choosing to send it) and I couldn't get it to work correctly in the WCF Test Client. I thought that I had found the problem. I assumed that the backslashes in the closing XML Tags would cause WCF Test Client to parse incorrectly and send a null value to my service without throwing any exceptions or anything in the WCF Test Client. See the link below.

http://programmersranch.blogspot.com/2014/08/c-wcf-backslash-limitation-in-wcf-test.html

However, that does not seem to be the issue, as the slashes in XML are / slashes and the slashes that cause problems are \ slashes. Any suggestions? Here is the string I am copy + pasting into the string parameter for one of my service methods in WCF Test Client. I have escaped the quotation marks and so on to avoid issues with the string parsing, but it doesn't work even after escaping them.

<?xml version=\"1.0\"?><QBXML><QBXMLMsgsRs><ItemNonInventoryQueryRs requestID=\"SXRlbVF1ZXJ5fDEyMA==\" statusCode=\"500\" statusSeverity=\"Warn\" statusMessage=\"The query request has not been fully completed. There was a required element 'your item name' that could not be found in QuickBooks.\"/></QBXMLMsgsRs></QBXML>

Also, I want to point out that if I enter a string like "BOB" or "sally2135" or something that's not XML at all, it receives the string just fine. It just doesn't like the XML string.

Thanks!


问:
JSartoolkit : camera_para.dat for Android rear cam
I have (again) a trouble using JSartoolkit 5 (https://github.com/artoolkit/jsartoolkit5).

I'm trying to use the rear cam of my device (Android - Nexus 5x, if that matters). I've seen that this framework uses .dat files in order to import cam settings.

So, I used .dat files that are provided in the repo (there : https://github.com/artoolkit/jsartoolkit5/tree/master/examples/Data).

But both of those files uses the user (facing) cam on my Android device.

Does someone have a file I can use to stream the rear cam on Android? Or knows how to set it up?

EDIT:

I used this app https://play.google.com/store/apps/details?id=com.artoolworks.ar.utils.calib_camera as said in artoolkit documentation. However, when I finish the calibration process, it says it upload the data: I don't know where, and how I can use it. Can someone tell me how I can export a .dat file from this app?

答: all you need is use right device of your phone/tablet. It nothing to do with camera_para.dat. You need to use  navigator.mediaDevices.enumerateDevices(), it will return you enum of devices on your phone.


问:
d3.js scopes possibly bleeding over
I have a angular based d3 directive for creating a multi-series line charts. Inside of that directive there are events for mouseover, mouseenter and mousemove events. For some reason they bleed over to a different div, that the same directive sits in. When I hover over one chart, it draws circles over both of them. Is there a way to control that? Can someone explain to me how did it happen that the scope bleeds out like that?

Here's d3 directive:

```<code>angular.module('MissionControlApp').directive('d3MultiSeriesLine', ['d3', function(d3) {
    return {
        restrict: 'E',
        scope: {
            data: '=',
            keys: '=',
            onClick: '&d3OnClick'
        },
        link: function(scope, ele) {
            var svg = d3.select(ele[0])
                .append("svg")
                .attr("width", "100%");

            // on window resize, re-render d3 canvas
            window.onresize = function() {
                return scope.$apply();
            };
            scope.$watch(function(){
                    return angular.element(window)[0].innerWidth;
                }, function(){
                    return scope.render(scope.data);
                }
            );

            // watch for data changes and re-render
            scope.$watch("data", function(newVals) {
                if(!newVals) return;
                return scope.render(newVals);
            }, true);

            scope.render = function (data) {
                if(!data) return;

                svg.selectAll("*").remove();

                // setup variables
                var width, height;
                var margin = {top: 5, right: 10, bottom: 20, left: 30};

                width = d3.select(ele[0])[0][0].offsetWidth - margin.left - margin.right;
                height = 300 - margin.top - margin.bottom;

                // set the height based on the calculations above
                svg.attr('height', height + margin.top + margin.bottom);

                var parseDate = d3.time.format('%Y-%m-%dT%H:%M:%S.%LZ').parse;
                var dateFormat = d3.time.format("%d %b");

                var x = d3.time.scale()
                    .range([0, width]);

                var y = d3.scale.linear()
                    .range([height, 0]);

                var color = d3.scale.category10();

                var xAxis = d3.svg.axis()
                    .scale(x)
                    .orient("bottom")
                    .ticks(6)
                    .tickFormat(dateFormat);

                var yAxis = d3.svg.axis()
                    .scale(y)
                    .orient("left")
                    .ticks(9);

                var line = d3.svg.line()
                    .interpolate("basis")
                    .x(function (d) { return x(d.date); })
                    .y(function (d) { return y(d.value); });

                color.domain(scope.keys);

                data.forEach(function (d) { d.date = parseDate(d.createdOn) });

                x.domain(d3.extent(data, function(d) { return d.date; }));

                var lineData = color.domain().map(function(name){
                    return {
                        name: name,
                        values: data.map(function (d) {
                            return {date: parseDate(d.createdOn), value: +d[name]};
                        })
                    }
                });

                var maxValue = d3.max(lineData, function(c) {
                    return d3.max(c.values, function(v) {
                        return v.value;
                    });
                });

                y.domain([0, maxValue + 20]);

                // Add the X Axis
                svg.append("g")
                    .attr("class", "axisMain")
                    .attr("transform", "translate(" + margin.left + "," + (height + margin.top) + ")")
                    .call(xAxis);

                // Add the Y Axis
                svg.append("g")
                    .attr("class", "axisMain")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                    .call(yAxis);

                var svgLine = svg.selectAll(".city")
                    .data(lineData)
                    .enter().append("g")
                    .attr("class", "city");

                svgLine.append("path")
                    .attr("class", "line")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                    .attr("d", function(d) { return line(d.values); })
                    .style("stroke", function(d) { return color(d.name); })
                    .attr("stroke-width", 1.5)
                    .attr("fill", "none")
                    .style("opacity", 0)
                    .transition()
                    .duration(1500)
                    .style("opacity", 1);

                svgLine.append("text")
                    .datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
                    .attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.value) + ")"; })
                    .attr("x", margin.left)
                    .attr("y", -2)
                    .attr("text-anchor", "end")
                    .attr("dy", ".35em")
                    .text(function(d) { return d.name; });

                var mouseG = svg.append("g")
                    .attr("class", "mouse-over-effects");

                mouseG.append("path") // this is the black vertical line to follow mouse
                    .attr("class", "mouse-line")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                    .style("stroke", "grey")
                    .style("stroke-width", "1px")
                    .style("stroke-dasharray", "3,3")
                    .style("opacity", "0");

                var lines = document.getElementsByClassName('line');

                var mousePerLine = mouseG.selectAll('.mouse-per-line')
                    .data(lineData)
                    .enter()
                    .append("g")
                    .attr("class", "mouse-per-line");

                mousePerLine.append("circle")
                    .attr("r", 6)
                    .style("stroke", function(d) { return color(d.name); })
                    .style("fill", "none")
                    .style("stroke-width", "1px")
                    .style("opacity", "0");

                mousePerLine.append("text")
                    .attr("transform", "translate(10,-6)");

                mouseG.append('svg:rect') // append a rect to catch mouse movements on canvas
                    .attr('width', width) // can't catch mouse events on a g element
                    .attr('height', height)
                    .attr('fill', 'none')
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                    .attr('pointer-events', 'all')
                    .on('mouseout', function() { // on mouse out hide line, circles and text
                        d3.select(".mouse-line")
                            .style("opacity", "0");
                        d3.selectAll(".mouse-per-line circle")
                            .style("opacity", "0");
                        d3.selectAll(".mouse-per-line text")
                            .style("opacity", "0");
                    })
                    .on('mouseover', function() { // on mouse in show line, circles and text
                        d3.select(".mouse-line")
                            .style("opacity", "1");
                        d3.selectAll(".mouse-per-line circle")
                            .style("opacity", "1");
                        d3.selectAll(".mouse-per-line text")
                            .style("opacity", "1");
                    })
                    .on('mousemove', function() { // mouse moving over canvas
                        var mouse = d3.mouse(this);
                        d3.select(".mouse-line")
                            .attr("d", function() {
                                var d = "M" + mouse[0] + "," + height;
                                d += " " + mouse[0] + "," + 0;
                                return d;
                            });

                        d3.selectAll(".mouse-per-line")
                            .attr("transform", function(d, i) {
                                console.log(width/mouse[0]);
                                var xDate = x.invert(mouse[0]),
                                    bisect = d3.bisector(function(d) { return d.date; }).right;
                                bisect(d.values, xDate);

                                var beginning = 0,
                                    end = lines[i].getTotalLength();

                                var pos;
                                var target;
                                while (true) {
                                    target = Math.floor((beginning + end) / 2);
                                    pos = lines[i].getPointAtLength(target);
                                    if ((target === end || target === beginning) && pos.x !== mouse[0]) {
                                        break;
                                    }
                                    if (pos.x > mouse[0]) end = target;
                                    else if (pos.x < mouse[0]) beginning = target;
                                    else break; //position found
                                }

                                d3.select(this).select('text')
                                    .text(y.invert(pos.y).toFixed(2));

                                return "translate(" + (mouse[0]+margin.left) + "," + (pos.y + margin.top) +")";
                            });
                    });
            };
        }
    };
}]);
</code>```

Here's the HTML code:

```<code><div class="row">
    <div class="panel-group" id="p1">
        <div class="panel panel-default">
            <div class="panel-heading" data-toggle="collapse" data-parent="#p1" data-target="#collapseP1">
                <h4 class="panel-title">Views / Views on Sheet</h4>
            </div>
            <div id="collapseP1" class="panel-collapse collapse in">
                <div class="panel-body">
                    <d3-multi-series-line data="vm.d3ViewStatsData" keys="vm.ViewKeys" d3-on-click="vm.d3OnClick(item)"></d3-multi-series-line>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="row">
    <div class="panel-group" id="p2">
        <div class="panel panel-default">
            <div class="panel-heading" data-toggle="collapse" data-parent="#p2" data-target="#collapseP2">
                <h4 class="panel-title">Schedules / Schedules on Sheet</h4>
            </div>
            <div id="collapseP2" class="panel-collapse collapse in">
                <div class="panel-body">
                    <d3-multi-series-line data="vm.d3ViewStatsData" keys="vm.ScheduleKeys" d3-on-click="vm.d3OnClick(item)"></d3-multi-series-line>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

答:
It's some of my old code :)

When I originally wrote that, I assumed one graph within the document.  There's a few lines in there that are selecting/finding things globally across the document.  Lines like:

```<code>var lines = document.getElementsByClassName('line');
</code>```

And

```<code>d3.selectAll(".mouse-per-line")
</code>```

Are not selections based off your original elem[0] and are therefore not confined to your directive.

Easy fix is to replace all the d3.select... with svg.select... and replace the lines line with something like this:

```<code>var lines = [];
svg.selectAll('line').each(function(){
  lines.append(this);
});
</code>```

Title: d3.js scopes possibly bleeding over

Body:
I have a angular based d3 directive for creating a multi-series line charts. Inside of that directive there are events for mouseover, mouseenter and mousemove events. For some reason they bleed over to a different div, that the same directive sits in. When I hover over one chart, it draws circles over both of them. Is there a way to control that? Can someone explain to me how did it happen that the scope bleeds out like that?

Here's d3 directive:

angular.module('MissionControlApp').directive('d3MultiSeriesLine', ['d3', function(d3) {
    return {
        restrict: 'E',
        scope: {
            data: '=',
            keys: '=',
            onClick: '&d3OnClick'
        },
        link: function(scope, ele) {
            var svg = d3.select(ele[0])
                .append("svg")
                .attr("width", "100%");

            // on window resize, re-render d3 canvas
            window.onresize = function() {
                return scope.$apply();
            };
            scope.$watch(function(){
                    return angular.element(window)[0].innerWidth;
                }, function(){
                    return scope.render(scope.data);
                }
            );

            // watch for data changes and re-render
            scope.$watch("data", function(newVals) {
                if(!newVals) return;
                return scope.render(newVals);
            }, true);

            scope.render = function (data) {
                if(!data) return;

                svg.selectAll("*").remove();

                // setup variables
                var width, height;
                var margin = {top: 5, right: 10, bottom: 20, left: 30};

                width = d3.select(ele[0])[0][0].offsetWidth - margin.left - margin.right;
                height = 300 - margin.top - margin.bottom;

                // set the height based on the calculations above
                svg.attr('height', height + margin.top + margin.bottom);

                var parseDate = d3.time.format('%Y-%m-%dT%H:%M:%S.%LZ').parse;
                var dateFormat = d3.time.format("%d %b");

                var x = d3.time.scale()
                    .range([0, width]);

                var y = d3.scale.linear()
                    .range([height, 0]);

                var color = d3.scale.category10();

                var xAxis = d3.svg.axis()
                    .scale(x)
                    .orient("bottom")
                    .ticks(6)
                    .tickFormat(dateFormat);

                var yAxis = d3.svg.axis()
                    .scale(y)
                    .orient("left")
                    .ticks(9);

                var line = d3.svg.line()
                    .interpolate("basis")
                    .x(function (d) { return x(d.date); })
                    .y(function (d) { return y(d.value); });

                color.domain(scope.keys);

                data.forEach(function (d) { d.date = parseDate(d.createdOn) });

                x.domain(d3.extent(data, function(d) { return d.date; }));

                var lineData = color.domain().map(function(name){
                    return {
                        name: name,
                        values: data.map(function (d) {
                            return {date: parseDate(d.createdOn), value: +d[name]};
                        })
                    }
                });

                var maxValue = d3.max(lineData, function(c) {
                    return d3.max(c.values, function(v) {
                        return v.value;
                    });
                });

                y.domain([0, maxValue + 20]);

                // Add the X Axis
                svg.append("g")
                    .attr("class", "axisMain")
                    .attr("transform", "translate(" + margin.left + "," + (height + margin.top) + ")")
                    .call(xAxis);

                // Add the Y Axis
                svg.append("g")
                    .attr("class", "axisMain")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                    .call(yAxis);

                var svgLine = svg.selectAll(".city")
                    .data(lineData)
                    .enter().append("g")
                    .attr("class", "city");

                svgLine.append("path")
                    .attr("class", "line")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                    .attr("d", function(d) { return line(d.values); })
                    .style("stroke", function(d) { return color(d.name); })
                    .attr("stroke-width", 1.5)
                    .attr("fill", "none")
                    .style("opacity", 0)
                    .transition()
                    .duration(1500)
                    .style("opacity", 1);

                svgLine.append("text")
                    .datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
                    .attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.value) + ")"; })
                    .attr("x", margin.left)
                    .attr("y", -2)
                    .attr("text-anchor", "end")
                    .attr("dy", ".35em")
                    .text(function(d) { return d.name; });

                var mouseG = svg.append("g")
                    .attr("class", "mouse-over-effects");

                mouseG.append("path") // this is the black vertical line to follow mouse
                    .attr("class", "mouse-line")
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                    .style("stroke", "grey")
                    .style("stroke-width", "1px")
                    .style("stroke-dasharray", "3,3")
                    .style("opacity", "0");

                var lines = document.getElementsByClassName('line');

                var mousePerLine = mouseG.selectAll('.mouse-per-line')
                    .data(lineData)
                    .enter()
                    .append("g")
                    .attr("class", "mouse-per-line");

                mousePerLine.append("circle")
                    .attr("r", 6)
                    .style("stroke", function(d) { return color(d.name); })
                    .style("fill", "none")
                    .style("stroke-width", "1px")
                    .style("opacity", "0");

                mousePerLine.append("text")
                    .attr("transform", "translate(10,-6)");

                mouseG.append('svg:rect') // append a rect to catch mouse movements on canvas
                    .attr('width', width) // can't catch mouse events on a g element
                    .attr('height', height)
                    .attr('fill', 'none')
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                    .attr('pointer-events', 'all')
                    .on('mouseout', function() { // on mouse out hide line, circles and text
                        d3.select(".mouse-line")
                            .style("opacity", "0");
                        d3.selectAll(".mouse-per-line circle")
                            .style("opacity", "0");
                        d3.selectAll(".mouse-per-line text")
                            .style("opacity", "0");
                    })
                    .on('mouseover', function() { // on mouse in show line, circles and text
                        d3.select(".mouse-line")
                            .style("opacity", "1");
                        d3.selectAll(".mouse-per-line circle")
                            .style("opacity", "1");
                        d3.selectAll(".mouse-per-line text")
                            .style("opacity", "1");
                    })
                    .on('mousemove', function() { // mouse moving over canvas
                        var mouse = d3.mouse(this);
                        d3.select(".mouse-line")
                            .attr("d", function() {
                                var d = "M" + mouse[0] + "," + height;
                                d += " " + mouse[0] + "," + 0;
                                return d;
                            });

                        d3.selectAll(".mouse-per-line")
                            .attr("transform", function(d, i) {
                                console.log(width/mouse[0]);
                                var xDate = x.invert(mouse[0]),
                                    bisect = d3.bisector(function(d) { return d.date; }).right;
                                bisect(d.values, xDate);

                                var beginning = 0,
                                    end = lines[i].getTotalLength();

                                var pos;
                                var target;
                                while (true) {
                                    target = Math.floor((beginning + end) / 2);
                                    pos = lines[i].getPointAtLength(target);
                                    if ((target === end || target === beginning) && pos.x !== mouse[0]) {
                                        break;
                                    }
                                    if (pos.x > mouse[0]) end = target;
                                    else if (pos.x < mouse[0]) beginning = target;
                                    else break; //position found
                                }

                                d3.select(this).select('text')
                                    .text(y.invert(pos.y).toFixed(2));

                                return "translate(" + (mouse[0]+margin.left) + "," + (pos.y + margin.top) +")";
                            });
                    });
            };
        }
    };
}]);

Here's the HTML code:

Views / Views on Sheet

                    <d3-multi-series-line data="vm.d3ViewStatsData" keys="vm.ViewKeys" d3-on-click="vm.d3OnClick(item)"></d3-multi-series-line>

Schedules / Schedules on Sheet

                    <d3-multi-series-line data="vm.d3ViewStatsData" keys="vm.ScheduleKeys" d3-on-click="vm.d3OnClick(item)"></d3-multi-series-line>

Body:
It's some of my old code :)

When I originally wrote that, I assumed one graph within the document.  There's a few lines in there that are selecting/finding things globally across the document.  Lines like:

var lines = document.getElementsByClassName('line');

And

d3.selectAll(".mouse-per-line")

Are not selections based off your original elem[0] and are therefore not confined to your directive.

Easy fix is to replace all the d3.select... with svg.select... and replace the lines line with something like this:

var lines = [];
svg.selectAll('line').each(function(){
  lines.append(this);
});


问:
Conditional IF statement inside this.state of the Constructor Reactjs
Im trying to render a conditional if inside a state variable of my constructor.

My original code is like this and it works

```<code>constructor(props, context){
  super(props, context);
}
this.state={
  ... // the rest of my state
  columns: [{
    render:
      row => (
        row.row.exported === 0 ?

        <span className={styles.centered} >
        {
          row.value === true ? <img src={checkedImage} />
              : <img src={uncheckedImage} />
        }
      </span>: ""
    ),
    maxWidth: 60,
    hideFilter: true,
    style: {textAlign:"center"},
  }]
}
</code>```

And i want to do something like this:

```<code>    constructor(props, context){
      super(props, context);

    this.state={
      ... // the rest of my state
      columns:
        render:
          if(this.state.profile.role == 'dba' || this.state.profile.role == 'both'){
            row => (
            row.row.exported === 0 ?
            <span className={styles.centered} >
              {
                row.value === true ? <img src={checkedImage} />
                    : <img src={uncheckedImage} />
              }
            </span>: ""
          }
        ),
        maxWidth: 60,
        hideFilter: true,
        style: {textAlign:"center"},
      }]
    }
  }
</code>```

In my render method im using react-table so it look like this:

Render Method

```<code>render(){
 return(
  <ReactTable columns={this.state.columns} />
 )
}
</code>```

Is it possible or is there any work around to achieve this?

答:
It's a little hard to understand what you are trying to do, this is a significant signal that your code needs improvement. A good alternative would be to have columns being their own components with a render method a state and all.

You can pass down props from the current component and then do conditional rendering from inside the current component and from inside the column component as well. I am wildly guessing here but your component can be kind of like this:

```<code>...
render() {
  return() {
    ...
    {
      this.state.profile.role === 'dba' || this.state.profile.role === 'both'
        ? (
         <Column
           row={this.props.row}
           checkedImage={checkedImage}
           uncheckedImage={uncheckedImage}
           ... // other props
         />
       )
       : null
     }
     ...
   }
 }
 ...
</code>```

So what I am doing here I am conditionally rendering the column depending on the state of my component (instead of a ternary you can also just use &&). Now inside the Column:

```<code>...
render() {
  return() {
    this.props.row.exported === 0
      ? (
        <span className={styles.centered} >
          {
            this.props.row.value === true
              ? <img src={this.props.checkedImage} />
              : <img src={this.props.uncheckedImage} />
          }
        </span>
      )
      : null
   }
 }
 ...
</code>```

This is much more clear and also allows you to easily modify your Column component and its rendering logic.

EDIT

Given the edit on your question you can also alter the columns you are passing down with a .filter. In this case your render method would be like this:

```<code>render() {
  const columns = this.state.columns.filter(column => {
    return (this.state.profile.role === 'dba' || this.state.profile.role === 'both');
  }

  return() {
    <ReactTable columns={columns} />
  }
}
</code>```

If you are not familiar with js filter check some docs here.

Body:
Im trying to render a conditional if inside a state variable of my constructor.

My original code is like this and it works

constructor(props, context){
  super(props, context);
}
this.state={
  ... // the rest of my state
  columns: [{
    render:
      row => (
        row.row.exported === 0 ?

        {
          row.value === true ?
              :
        }
      : ""
    ),
    maxWidth: 60,
    hideFilter: true,
    style: {textAlign:"center"},
  }]
}

And i want to do something like this:

    constructor(props, context){
      super(props, context);

    this.state={
      ... // the rest of my state
      columns:
        render:
          if(this.state.profile.role == 'dba' || this.state.profile.role == 'both'){
            row => (
            row.row.exported === 0 ?

              {
                row.value === true ?
                    :
              }
            : ""
          }
        ),
        maxWidth: 60,
        hideFilter: true,
        style: {textAlign:"center"},
      }]
    }
  }

In my render method im using react-table so it look like this:

Render Method

render(){
 return(
  <ReactTable columns={this.state.columns} />
 )
}

Is it possible or is there any work around to achieve this?

Body:
It's a little hard to understand what you are trying to do, this is a significant signal that your code needs improvement. A good alternative would be to have columns being their own components with a render method a state and all.

You can pass down props from the current component and then do conditional rendering from inside the current component and from inside the column component as well. I am wildly guessing here but your component can be kind of like this:

...
render() {
  return() {
    ...
    {
      this.state.profile.role === 'dba' || this.state.profile.role === 'both'
        ? (
         <Column
           row={this.props.row}
           checkedImage={checkedImage}
           uncheckedImage={uncheckedImage}
           ... // other props
         />
       )
       : null
     }
     ...
   }
 }
 ...

So what I am doing here I am conditionally rendering the column depending on the state of my component (instead of a ternary you can also just use &&). Now inside the Column:

...
render() {
  return() {
    this.props.row.exported === 0
      ? (
        <span className={styles.centered} >
          {
            this.props.row.value === true
              ? <img src={this.props.checkedImage} />
              : <img src={this.props.uncheckedImage} />
          }
        </span>
      )
      : null
   }
 }
 ...

This is much more clear and also allows you to easily modify your Column component and its rendering logic.

EDIT

Given the edit on your question you can also alter the columns you are passing down with a .filter. In this case your render method would be like this:

render() {
  const columns = this.state.columns.filter(column => {
    return (this.state.profile.role === 'dba' || this.state.profile.role === 'both');
  }

  return() {
    <ReactTable columns={columns} />
  }
}

If you are not familiar with js filter check some docs here.


问:
Select Direct Child of $(this) in Jquery
I know that I can use $('img', this) to select all img elements in $(this).

In my current case I am trying to manipulate only DIRECT child images of $(this).

Is there a selector for that??

答:
```<code>$(this).find('> img')
</code>```

Read this

Body:
$(this).find('> img')

Read this


问:
How to $.trim a contenteditiable div on keypress
I'm trying to trim a contenteditable div upon keypress, however nothing seems to be working.

HTML

```<code><div class="datacollection NoFirstInputSpace" placeholder="____________" contenteditable</div>

$(document).on('keypress', '.NoFirstInputSpace', function(e) {

    var str = $(this).text();
    $.trim(str);
    var code = e.keyCode ? e.keyCode : e.which;
    if (code === 32 && (e.target.selectionStart === 0 || getCaretCharacterOffsetWithin(e.target) === 0)) {
        e.preventDefault();
        return false;
    }

});
</code>```

The keypress works correctly, it prevents the suer from entering a space as the first character of the contenteditable div. However the problem is if the end user types a string then highlights it and then presses the space bar it will replace the string with a space, which i cant have a space as the first character

答:
You should bind the keyup event instead and check when pressed key is Space.

If true, you trim the empty spaces and set .text() = to empty.

Also, keyCode is deprecated. Use key.

See reference.

$(document).on('keyup', '.NoFirstInputSpace', function(e) {
  if (e.key == ' ') {
    var text = $.trim($(this).text());
    if (text == '') {
      $(this).text('');
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.NoFirstInputSpace {
  border: 1px solid red;
}</code>```

```

Body:
I'm trying to trim a contenteditable div upon keypress, however nothing seems to be working.

HTML

<div class="datacollection NoFirstInputSpace" placeholder="____________" contenteditable

$(document).on('keypress', '.NoFirstInputSpace', function(e) {

    var str = $(this).text();
    $.trim(str);
    var code = e.keyCode ? e.keyCode : e.which;
    if (code === 32 && (e.target.selectionStart === 0 || getCaretCharacterOffsetWithin(e.target) === 0)) {
        e.preventDefault();
        return false;
    }

});

The keypress works correctly, it prevents the suer from entering a space as the first character of the contenteditable div. However the problem is if the end user types a string then highlights it and then presses the space bar it will replace the string with a space, which i cant have a space as the first character

Body:
You should bind the keyup event instead and check when pressed key is Space.

If true, you trim the empty spaces and set .text() = to empty.

Also, keyCode is deprecated. Use key.

See reference.

$(document).on('keyup', '.NoFirstInputSpace', function(e) {
  if (e.key == ' ') {
    var text = $.trim($(this).text());
    if (text == '') {
      $(this).text('');
    }
  }
});

.NoFirstInputSpace {
  border: 1px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="datacollection NoFirstInputSpace" placeholder="____________" contenteditable></div>


问:
How to pass generic class objects with a different type to one List?
Hello I need some inspiration,

I have a waypoint class like so:

```<code>public class Waypoint<T> {

}
</code>```

and I would like to add all my waypoints to one list like so:

```<code>var w1 = new Waypoint<Item>();
var w2 = new Waypoint<Player>();
var waypoints = new List<Waypoint<?>>();
</code>```

Problem is, they are not all of the same Type.
Is there a way that I can add different types to one list?

Anybody know an easy workaround?
Language: C#

Kind regards,

Venomous

答:
Assuming you are coding in C#, there is no common base class for Waypoint<Item> and Waypoint<Player> except for object so the type of collection would be List<object> (or even ArrayList).

Even if Item and Player both derived from the same base class, you wouldn't be able to define a List<Waypoint<Base>> and add both Waypoint<Item> and Waypoint<Player> objects to this list.

Waypoint<Item> is not a derived type of Waypoint<Base> just because Item is a derived type of Base.

Body:
Hello I need some inspiration,

I have a waypoint class like so:

public class Waypoint<T> {

}

and I would like to add all my waypoints to one list like so:

var w1 = new Waypoint<Item>();
var w2 = new Waypoint<Player>();
var waypoints = new List<Waypoint<?>>();

Problem is, they are not all of the same Type.
Is there a way that I can add different types to one list?

Anybody know an easy workaround?
Language: C#

Kind regards,

Venomous


问:
Java get logged in user
I'm using the netbeans GUI Builder for this!
I've created an JFrame and put a JPanel inside with a CardLayout to switch between JPanels. The JFrame also has a Menu attached to it with diffrent options. Now i want the options to be grayed out until the user logs in. According to the premissions of the logged in user, options become available (see picture for reference).

The problem is that i have no idea on how to get what user is logged in when switching panels. The login panel knows what got typed in the fields and know if the login is correct. I've tryed using the .getParent() function to change a variable inside the Jframe but that does not seem to work. But how would i go about changing the JMenu items from the JPanel?
(See this picture for child parent relations)

答:
Hi I've developed this quick example. (Please focus on the way of mantain and share the login info).

As @Jan suggested, this is a coarse implementation of the MVC pattern. In which you try to separate:
Model: The data you are using, and the component layer for your services and data transformation.
View: The component which receives the data from the user
Controller: The way of connect the view with your model
Here you are a link to get more information: The MVC pattern and SWING

Class used to get the Login:

```<code>package com.stackoverflow.login;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;

public class LoginDialog extends JDialog {

    private static final long serialVersionUID = 1L;

    // This is the class who will mantain the logged used information
    private User user;
    private JTextField tfUsername;
    private JPasswordField pfPassword;
    private JLabel lbUsername;
    private JLabel lbPassword;
    private JButton btnLogin;
    private JButton btnCancel;
    private boolean succeeded;

    public LoginDialog(Frame parent) {
        super(parent, "Login", true);
        //
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints cs = new GridBagConstraints();

        cs.fill = GridBagConstraints.HORIZONTAL;

        lbUsername = new JLabel("Username: ");
        cs.gridx = 0;
        cs.gridy = 0;
        cs.gridwidth = 1;
        panel.add(lbUsername, cs);

        tfUsername = new JTextField(20);
        cs.gridx = 1;
        cs.gridy = 0;
        cs.gridwidth = 2;
        panel.add(tfUsername, cs);

        lbPassword = new JLabel("Password: ");
        cs.gridx = 0;
        cs.gridy = 1;
        cs.gridwidth = 1;
        panel.add(lbPassword, cs);

        pfPassword = new JPasswordField(20);
        cs.gridx = 1;
        cs.gridy = 1;
        cs.gridwidth = 2;
        panel.add(pfPassword, cs);
        panel.setBorder(new LineBorder(Color.GRAY));

        btnLogin = new JButton("Login");

        btnLogin.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (Login.authenticate(getUsername(), getPassword())) {
                    JOptionPane.showMessageDialog(LoginDialog.this,
                            "Hi " + getUsername() + "! You have successfully logged in.", "Login",
                            JOptionPane.INFORMATION_MESSAGE);
                    succeeded = true;
                    user = new User();
                    user.setPassword(getPassword());
                    user.setUsername(getUsername());
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(LoginDialog.this, "Invalid username or password", "Login",
                            JOptionPane.ERROR_MESSAGE);
                    // reset username and password
                    tfUsername.setText("");
                    pfPassword.setText("");
                    succeeded = false;

                }
            }
        });
        btnCancel = new JButton("Cancel");
        btnCancel.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        JPanel bp = new JPanel();
        bp.add(btnLogin);
        bp.add(btnCancel);

        getContentPane().add(panel, BorderLayout.CENTER);
        getContentPane().add(bp, BorderLayout.PAGE_END);

        pack();
        setResizable(false);
        setLocationRelativeTo(parent);
    }

    public String getUsername() {
        return tfUsername.getText().trim();
    }

    public String getPassword() {
        return new String(pfPassword.getPassword());
    }

    public boolean isSucceeded() {
        return succeeded;
    }

    public User getUser() {
        return user;
    }

}
</code>```

Login service

```<code>package com.stackoverflow.login;
public class Login {

    public static boolean authenticate(String username, String password) {
        // hardcoded username and password
        if (username.equals("bob") && password.equals("secret")) {
            return true;
        }
        return false;
    }
}
</code>```

Class for hold user information:
    package com.stackoverflow.login;

```<code>/**
 * Class used to mantain the login information, it's just for educational
 * purpouses, for prod environment you must implement it in a secure way!!
 */
public class User {

    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}
</code>```

Class for run the program

package com.stackoverflow.login;

```<code>import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 * Run the program
 */
public class Main {
    public static void main(String[] args) {
        final JFrame frame = new JFrame("JDialog Demo");
        final JButton btnLogin = new JButton("Click to login");
        final JButton btnPanel = new JButton();

        LoginDialog loginDlg = new LoginDialog(frame);
        loginDlg.setVisible(true);
        // if logon successfully
        if (loginDlg.isSucceeded()) {
            btnLogin.setVisible(false);
            btnPanel.setText("Hi " + loginDlg.getUsername() + "! click to open new frame");
            frame.getContentPane().add(btnPanel);
        }

        btnPanel.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JLabel label = new JLabel("Logged user is: " + loginDlg.getUser().getUsername());
                JDialog mydialog = new JDialog();
                mydialog.setSize(new Dimension(400, 100));
                mydialog.setTitle("Another frame");
                mydialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
                mydialog.add(label);
                mydialog.setVisible(true);
            }
        });

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 100);
        frame.setLayout(new FlowLayout());
        frame.getContentPane().add(btnLogin);
        frame.setVisible(true);
    }
}
</code>```

Title: Java get logged in user

Body:
Hi I've developed this quick example. (Please focus on the way of mantain and share the login info).

As @Jan suggested, this is a coarse implementation of the MVC pattern. In which you try to separate:
Model: The data you are using, and the component layer for your services and data transformation.
View: The component which receives the data from the user
Controller: The way of connect the view with your model
Here you are a link to get more information: The MVC pattern and SWING

Class used to get the Login:

package com.stackoverflow.login;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;

public class LoginDialog extends JDialog {

    private static final long serialVersionUID = 1L;

    // This is the class who will mantain the logged used information
    private User user;
    private JTextField tfUsername;
    private JPasswordField pfPassword;
    private JLabel lbUsername;
    private JLabel lbPassword;
    private JButton btnLogin;
    private JButton btnCancel;
    private boolean succeeded;

    public LoginDialog(Frame parent) {
        super(parent, "Login", true);
        //
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints cs = new GridBagConstraints();

        cs.fill = GridBagConstraints.HORIZONTAL;

        lbUsername = new JLabel("Username: ");
        cs.gridx = 0;
        cs.gridy = 0;
        cs.gridwidth = 1;
        panel.add(lbUsername, cs);

        tfUsername = new JTextField(20);
        cs.gridx = 1;
        cs.gridy = 0;
        cs.gridwidth = 2;
        panel.add(tfUsername, cs);

        lbPassword = new JLabel("Password: ");
        cs.gridx = 0;
        cs.gridy = 1;
        cs.gridwidth = 1;
        panel.add(lbPassword, cs);

        pfPassword = new JPasswordField(20);
        cs.gridx = 1;
        cs.gridy = 1;
        cs.gridwidth = 2;
        panel.add(pfPassword, cs);
        panel.setBorder(new LineBorder(Color.GRAY));

        btnLogin = new JButton("Login");

        btnLogin.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (Login.authenticate(getUsername(), getPassword())) {
                    JOptionPane.showMessageDialog(LoginDialog.this,
                            "Hi " + getUsername() + "! You have successfully logged in.", "Login",
                            JOptionPane.INFORMATION_MESSAGE);
                    succeeded = true;
                    user = new User();
                    user.setPassword(getPassword());
                    user.setUsername(getUsername());
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(LoginDialog.this, "Invalid username or password", "Login",
                            JOptionPane.ERROR_MESSAGE);
                    // reset username and password
                    tfUsername.setText("");
                    pfPassword.setText("");
                    succeeded = false;

                }
            }
        });
        btnCancel = new JButton("Cancel");
        btnCancel.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        JPanel bp = new JPanel();
        bp.add(btnLogin);
        bp.add(btnCancel);

        getContentPane().add(panel, BorderLayout.CENTER);
        getContentPane().add(bp, BorderLayout.PAGE_END);

        pack();
        setResizable(false);
        setLocationRelativeTo(parent);
    }

    public String getUsername() {
        return tfUsername.getText().trim();
    }

    public String getPassword() {
        return new String(pfPassword.getPassword());
    }

    public boolean isSucceeded() {
        return succeeded;
    }

    public User getUser() {
        return user;
    }

}

Login service

package com.stackoverflow.login;
public class Login {

    public static boolean authenticate(String username, String password) {
        // hardcoded username and password
        if (username.equals("bob") && password.equals("secret")) {
            return true;
        }
        return false;
    }
}

Class for hold user information:
    package com.stackoverflow.login;

/**
 * Class used to mantain the login information, it's just for educational
 * purpouses, for prod environment you must implement it in a secure way!!
 */
public class User {

    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

Class for run the program

package com.stackoverflow.login;

import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 * Run the program
 */
public class Main {
    public static void main(String[] args) {
        final JFrame frame = new JFrame("JDialog Demo");
        final JButton btnLogin = new JButton("Click to login");
        final JButton btnPanel = new JButton();

        LoginDialog loginDlg = new LoginDialog(frame);
        loginDlg.setVisible(true);
        // if logon successfully
        if (loginDlg.isSucceeded()) {
            btnLogin.setVisible(false);
            btnPanel.setText("Hi " + loginDlg.getUsername() + "! click to open new frame");
            frame.getContentPane().add(btnPanel);
        }

        btnPanel.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JLabel label = new JLabel("Logged user is: " + loginDlg.getUser().getUsername());
                JDialog mydialog = new JDialog();
                mydialog.setSize(new Dimension(400, 100));
                mydialog.setTitle("Another frame");
                mydialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
                mydialog.add(label);
                mydialog.setVisible(true);
            }
        });

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 100);
        frame.setLayout(new FlowLayout());
        frame.getContentPane().add(btnLogin);
        frame.setVisible(true);
    }
}