问:
User profile in isomorphic applications
I'm currently in the process of adding login, plus a set of advanced features related to login, to a website using React, Redux, Express and Node. For the actual login, I'm using Passport, with Facebook, Google and Twitter strategies. After getting the required token, it's sent to AWS Cognito Federated Identities to get synchronized data for the user. Data from the website is also synchronized back to Cognito whenever needed.

After the user has logged in, I can construct a complete user profile on the Node server, but now what?

```<code>// server.jsx
// imports
.............

// variables
.............

var userProfile;
// logging the user with Passport and adding it to the profile
.............

app.use((req, res) => {
    // I can do whatever I want with the profile here
    .............

    // handling the request and creating an initial state ..
    .............
}
</code>```

Back in the days, this would be fairly easy to solve using either session variables (Java/C#) or cookies (JS), but in isomorphic applications it's not quite that simple. Let's say that the user gets access to profile.jsx via routes after logging in: A cookie (set via client-sessions for example) is only available when the jsx file is run on the client; it's not accessible whenever it's server rendered.

Custom code appears to be required even when using things like isomorphic-cookie or universal-cookie, which pretty much defeats the purpose of an isomorphic application. I also thought of using Redux, but Redux appears to only have an initial state on Node, which doesn't help much.

```<code>// Profile.jsx
import React , { Component } from 'react';
import Cookies from 'universal-cookie';

class Profile extends Component {
    // Stuff
    .............

    render() {
        // Would love to be able to access to the profile without custom code like this
        if (typeof window != 'undefined' && window.document) {
            const cookies = new Cookies();
            console.log(cookies.get('user'));
        }
    }
</code>```

So is there a smooth way of handling user profiles or other variables that you want access to at all times, without writing a huge amount of custom code for each scenario? It seems most tutorials and examples handle this sort of thing exclusively either on the server or the client, which would require a re-write of the website in this particular case.

Isomorphic applications are fairly straight forward in most cases, but the complexity really shoots through the roof when authentication, profiles and so on is introduced, so I would greatly appreciate any feedback on the matter.

答:
I think a common scenario here would be to add an authentication step, then to store a successful authentication token either as a cookie or in your app state that you supply back to the profile API on subsequent queries.

Any data that is returned form your API can also be added to your Redux store so you always have access to it and subsequently updated whenever you need to persist changes or want to force update the current state data.

Title: User profile in isomorphic applications

Body:
I'm currently in the process of adding login, plus a set of advanced features related to login, to a website using React, Redux, Express and Node. For the actual login, I'm using Passport, with Facebook, Google and Twitter strategies. After getting the required token, it's sent to AWS Cognito Federated Identities to get synchronized data for the user. Data from the website is also synchronized back to Cognito whenever needed.

After the user has logged in, I can construct a complete user profile on the Node server, but now what?

// server.jsx
// imports
.............

// variables
.............

var userProfile;
// logging the user with Passport and adding it to the profile
.............

app.use((req, res) => {
    // I can do whatever I want with the profile here
    .............

    // handling the request and creating an initial state ..
    .............
}

Back in the days, this would be fairly easy to solve using either session variables (Java/C#) or cookies (JS), but in isomorphic applications it's not quite that simple. Let's say that the user gets access to profile.jsx via routes after logging in: A cookie (set via client-sessions for example) is only available when the jsx file is run on the client; it's not accessible whenever it's server rendered.

Custom code appears to be required even when using things like isomorphic-cookie or universal-cookie, which pretty much defeats the purpose of an isomorphic application. I also thought of using Redux, but Redux appears to only have an initial state on Node, which doesn't help much.

// Profile.jsx
import React , { Component } from 'react';
import Cookies from 'universal-cookie';

class Profile extends Component {
    // Stuff
    .............

    render() {
        // Would love to be able to access to the profile without custom code like this
        if (typeof window != 'undefined' && window.document) {
            const cookies = new Cookies();
            console.log(cookies.get('user'));
        }
    }

So is there a smooth way of handling user profiles or other variables that you want access to at all times, without writing a huge amount of custom code for each scenario? It seems most tutorials and examples handle this sort of thing exclusively either on the server or the client, which would require a re-write of the website in this particular case.

Isomorphic applications are fairly straight forward in most cases, but the complexity really shoots through the roof when authentication, profiles and so on is introduced, so I would greatly appreciate any feedback on the matter.


来源: stackexchange

问:
Remove the 0b in binary
I am trying to convert a binary number I have to take out the 0b string out.

I understand how to get a bin number

```<code>x = 17

print(bin(17))

'0b10001'
</code>```

but I want to take the 0b in the string out and I am having some issues with doing this. This is going to be within a function returning a binary number without the 0b.

答:
It's easy just make this function:</p>

```<code>def f(n):print('{:0b}'.format(n))
f(17)
>>> 10001
</code>```

ContentLicense: CC BY-SA 4.0

Title: Remove the 0b in binary

Body:
I am trying to convert a binary number I have to take out the 0b string out.

I understand how to get a bin number

x = 17

print(bin(17))

'0b10001'

but I want to take the 0b in the string out and I am having some issues with doing this. This is going to be within a function returning a binary number without the 0b.

Body:
It's easy just make this function:

def f(n):print('{:0b}'.format(n))
f(17)
>>> 10001

ContentLicense: CC BY-SA 3.0


问:
Vertical slides in ionic 2
I am using ionic 2, i would like to have vertical slides, had tried to implement using swiper and also tried passing the {direction : vertical} in options(directive) of ion-slides( which worked in ionic 1.x) but nothing worked is there any alternative solution ?

HTML :

```<code><ion-slides pager options="options" style="background-color:white;">

   <ion-slide>
     <h2>Slide 1</h2>
   </ion-slide>

   <ion-slide>
     <h2>Slide 2</h2>
   </ion-slide>

   <ion-slide>
     <h2>Slide 3</h2>
   </ion-slide>

</ion-slides>
</code>```

JS :

```<code>export class HomePage {
   constructor() {
      this.options = {
         direction: 'vertical'
      };
   }
}
</code>```

答:
Simply use direction="vertical" properties:

```<code><ion-slides pager direction="vertical">

  <ion-slide>
      //Your html
  </ion-slide>

 </ion-slides>
</code>```

Title: Vertical slides in ionic 2

Body:
I am using ionic 2, i would like to have vertical slides, had tried to implement using swiper and also tried passing the {direction : vertical} in options(directive) of ion-slides( which worked in ionic 1.x) but nothing worked is there any alternative solution ?

HTML :

<ion-slides pager options="options" style="background-color:white;">

   <ion-slide>

Slide 1

   </ion-slide>

   <ion-slide>

Slide 2

   </ion-slide>

   <ion-slide>

Slide 3

   </ion-slide>

</ion-slides>

JS :

export class HomePage {
   constructor() {
      this.options = {
         direction: 'vertical'
      };
   }
}

Body:
Simply use direction="vertical" properties:

<ion-slides pager direction="vertical">

  <ion-slide>
      //Your html
  </ion-slide>

 </ion-slides>


问:
weka wrapper attribute selection random forest java
```<code>protected static void attSelection_w(Instances data) throws Exception {
    AttributeSelection fs = new AttributeSelection();
    WrapperSubsetEval wrapper = new WrapperSubsetEval();

    wrapper.buildEvaluator(data);
    wrapper.setClassifier(new RandomForest());
    wrapper.setFolds(10);
    wrapper.setThreshold(0.001);

    fs.SelectAttributes(data);
    fs.setEvaluator(wrapper);
    fs.setSearch(new BestFirst());
    System.out.println(fs.toResultsString());
}
</code>```

Above is my code for wrapper based attribute selection using random forest + bestfirst search. However, this somehow spits out a result using cfs, like below.

```<code>Search Method:
    Greedy Stepwise (forwards).
    Start set: no attributes
    Merit of best subset found:    0.287

Attribute Subset Evaluator (supervised, Class (nominal): 9 class):
    CFS Subset Evaluator
    Including locally predictive attributes
</code>```

There is no other code using CFS in the whole class, and I'm pretty much stuck.. I would appreciate any help. Thanks!

答:
Just set class Index and add this line after creating instance data

```<code>data.setClassIndex(data.numAttributes() - 1);
</code>```

I checked and it worked fine.

Body:
protected static void attSelection_w(Instances data) throws Exception {
    AttributeSelection fs = new AttributeSelection();
    WrapperSubsetEval wrapper = new WrapperSubsetEval();

    wrapper.buildEvaluator(data);
    wrapper.setClassifier(new RandomForest());
    wrapper.setFolds(10);
    wrapper.setThreshold(0.001);

    fs.SelectAttributes(data);
    fs.setEvaluator(wrapper);
    fs.setSearch(new BestFirst());
    System.out.println(fs.toResultsString());
}

Above is my code for wrapper based attribute selection using random forest + bestfirst search. However, this somehow spits out a result using cfs, like below.

Search Method:
    Greedy Stepwise (forwards).
    Start set: no attributes
    Merit of best subset found:    0.287

Attribute Subset Evaluator (supervised, Class (nominal): 9 class):
    CFS Subset Evaluator
    Including locally predictive attributes

There is no other code using CFS in the whole class, and I'm pretty much stuck.. I would appreciate any help. Thanks!

Body:
Just set class Index and add this line after creating instance data

data.setClassIndex(data.numAttributes() - 1);

I checked and it worked fine.


问:
Can I post an inline image using file field in a form
I have an IMG loaded inside the HTML document, and I would like to upload it using the "file" field from a form. The form is in the same document, so I shouldn't have any security issues.

Is it possible to upload the image to a server?

I managed to upload images choosing a file from my hard drive, but I have no clue about doing it using the IMG inside the HTML document.

答:
I have no hands-on experience with this, but it seems to be possible using canvas.toDataURL. I don't know about IE compatibility with exCanvas.

See this SO answer for a successful solution.

ContentLicense: CC BY-SA 2.5


问:
Flex CSS not working in IE 11
I have a responsive menu that I am working on that is using flex css to make the divs stack.  I have them contained within two containers due to some javascript needed on the main div.  My issue is that the main div is 95% width with absolute position, inside I have a container div with relative position that is 95% and set to display: flex, and divs within this div.  (Diagram below)  The problem is that in IE 11, the flex display is not working and the width is expanding beyond the container div width and not wrapping.  I have included the code.  Please advise as this works in all other browers, ipad, on this site, etc.  The code snippet works here but not on the site....  Thank you and sorry for any confusion.

.col_full {
 width:100%;
}

.maindiv {
    margin:4px 10px;
    position:absolute;
    display:show; /* shows on hover */
    text-align:left;
    padding:20px;
    border:1px solid #777777;
    border-top:none;
   left:0;
   right:0;
   z-index:100;
    width:95%;
}

.containerdiv {
 position: relative;
 width:100%;
 margin:auto;
 text-align:center;
 display: flex;
  flex-wrap: wrap;
 flex: 1;
 justify-content: center;
  align-items: top;
  flex-direction: row;
 overflow: auto;
}

.divs {
 max-width:260px;
 position:relative;
 flex-grow: 1;
 padding: 15px 15px 50px 15px;
 margin:15px;
 text-align:left;
 overflow:hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="maindiv"><div class="containerdiv">

  <div class="col_full">
   <h2>Header Goes Here</h2>
  </div>

  <div class="cb"></div>

  <div class="divs">
   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque venenatis imperdiet mauris, a faucibus nibh sollicitudin et. Maecenas ac tincidunt ligula. Praesent ornare mi consequat est fringilla, ac semper ante lacinia. Integer ultricies massa sit amet dui accumsan tincidunt. Duis eget metus vitae odio lacinia fermentum sit amet sed nibh. Phasellus volutpat nulla in ex ullamcorper congue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris justo lectus, ullamcorper eget lacinia at, convallis et lorem.
  </div>

  <div class="divs">
   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque venenatis imperdiet mauris, a faucibus nibh sollicitudin et. Maecenas ac tincidunt ligula. Praesent ornare mi consequat est fringilla, ac semper ante lacinia. Integer ultricies massa sit amet dui accumsan tincidunt. Duis eget metus vitae odio lacinia fermentum sit amet sed nibh. Phasellus volutpat nulla in ex ullamcorper congue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris justo lectus, ullamcorper eget lacinia at, convallis et lorem.
  </div>

  <div class="divs">
   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque venenatis imperdiet mauris, a faucibus nibh sollicitudin et. Maecenas ac tincidunt ligula. Praesent ornare mi consequat est fringilla, ac semper ante lacinia. Integer ultricies massa sit amet dui accumsan tincidunt. Duis eget metus vitae odio lacinia fermentum sit amet sed nibh. Phasellus volutpat nulla in ex ullamcorper congue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris justo lectus, ullamcorper eget lacinia at, convallis et lorem.
  </div>

  <div class="divs">
   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque venenatis imperdiet mauris, a faucibus nibh sollicitudin et. Maecenas ac tincidunt ligula. Praesent ornare mi consequat est fringilla, ac semper ante lacinia. Integer ultricies massa sit amet dui accumsan tincidunt. Duis eget metus vitae odio lacinia fermentum sit amet sed nibh. Phasellus volutpat nulla in ex ullamcorper congue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris justo lectus, ullamcorper eget lacinia at, convallis et lorem.
  </div>

 </div></code>```

答: The sample code was working but not on the actual site.  I had to change the display to flex on hover on the maindiv and this resolved the issue.  The actual page uses a lot of CSS and js to get the page to display the way I wanted it to and I couldn't provide all of the code here.  I appreciate all of the help.</p>

Title: Flex CSS not working in IE 11

Body:
I have a responsive menu that I am working on that is using flex css to make the divs stack.  I have them contained within two containers due to some javascript needed on the main div.  My issue is that the main div is 95% width with absolute position, inside I have a container div with relative position that is 95% and set to display: flex, and divs within this div.  (Diagram below)  The problem is that in IE 11, the flex display is not working and the width is expanding beyond the container div width and not wrapping.  I have included the code.  Please advise as this works in all other browers, ipad, on this site, etc.  The code snippet works here but not on the site....  Thank you and sorry for any confusion.

.col_full {
 width:100%;
}

.maindiv {
    margin:4px 10px;
    position:absolute;
    display:show; /* shows on hover */
    text-align:left;
    padding:20px;
    border:1px solid #777777;
    border-top:none;
   left:0;
   right:0;
   z-index:100;
    width:95%;
}

.containerdiv {
 position: relative;
 width:100%;
 margin:auto;
 text-align:center;
 display: flex;
  flex-wrap: wrap;
 flex: 1;
 justify-content: center;
  align-items: top;
  flex-direction: row;
 overflow: auto;
}

.divs {
 max-width:260px;
 position:relative;
 flex-grow: 1;
 padding: 15px 15px 50px 15px;
 margin:15px;
 text-align:left;
 overflow:hidden;
}

Header Goes Here

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque venenatis imperdiet mauris, a faucibus nibh sollicitudin et. Maecenas ac tincidunt ligula. Praesent ornare mi consequat est fringilla, ac semper ante lacinia. Integer ultricies massa sit amet dui accumsan tincidunt. Duis eget metus vitae odio lacinia fermentum sit amet sed nibh. Phasellus volutpat nulla in ex ullamcorper congue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris justo lectus, ullamcorper eget lacinia at, convallis et lorem.

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque venenatis imperdiet mauris, a faucibus nibh sollicitudin et. Maecenas ac tincidunt ligula. Praesent ornare mi consequat est fringilla, ac semper ante lacinia. Integer ultricies massa sit amet dui accumsan tincidunt. Duis eget metus vitae odio lacinia fermentum sit amet sed nibh. Phasellus volutpat nulla in ex ullamcorper congue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris justo lectus, ullamcorper eget lacinia at, convallis et lorem.

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque venenatis imperdiet mauris, a faucibus nibh sollicitudin et. Maecenas ac tincidunt ligula. Praesent ornare mi consequat est fringilla, ac semper ante lacinia. Integer ultricies massa sit amet dui accumsan tincidunt. Duis eget metus vitae odio lacinia fermentum sit amet sed nibh. Phasellus volutpat nulla in ex ullamcorper congue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris justo lectus, ullamcorper eget lacinia at, convallis et lorem.

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque venenatis imperdiet mauris, a faucibus nibh sollicitudin et. Maecenas ac tincidunt ligula. Praesent ornare mi consequat est fringilla, ac semper ante lacinia. Integer ultricies massa sit amet dui accumsan tincidunt. Duis eget metus vitae odio lacinia fermentum sit amet sed nibh. Phasellus volutpat nulla in ex ullamcorper congue. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris justo lectus, ullamcorper eget lacinia at, convallis et lorem.


问:
Fibonacci sequence works in python, but not in c?
I have the following python code:

```<code>a, b = 1, 1
for i in range(0, 100):
    print a
    a, b = b, a + b
</code>```

It generates this:
1
1
2
3
5
8
etc

I wrote the same in c:

```<code>#include <stdio.h>
long long unsigned int a = 1, b = 1;
void main(){
    for(int i = 0; i < 100; i++){
        printf("%llu \n", a);
        a = b, b = a + b;
    }
}
</code>```

It generates this:
1
1
2
4
8
16
32
etc

Why does the c program generate powers of 2 when it is using the exact same operations?

答:
You misunderstand comma operator.</p>

```<code>#include <stdio.h>
#include <inttypes.h>
#include <stdint.h>

int main(void) {
    uintmax_t a = 1, b = 1;
    for (int i = 0; i < 100; i++) {
        printf("%" PRIuMAX "\n", a);
        b = a + b;
        a = b - a;
    }
}
</code>```

Body:
I have the following python code:

a, b = 1, 1
for i in range(0, 100):
    print a
    a, b = b, a + b

It generates this:
1
1
2
3
5
8
etc

I wrote the same in c:

#include <stdio.h>
long long unsigned int a = 1, b = 1;
void main(){
    for(int i = 0; i < 100; i++){
        printf("%llu \n", a);
        a = b, b = a + b;
    }
}

It generates this:
1
1
2
4
8
16
32
etc

Why does the c program generate powers of 2 when it is using the exact same operations?

Body:
You misunderstand comma operator.

#include <stdio.h>
#include <inttypes.h>
#include <stdint.h>

int main(void) {
    uintmax_t a = 1, b = 1;
    for (int i = 0; i < 100; i++) {
        printf("%" PRIuMAX "\n", a);
        b = a + b;
        a = b - a;
    }
}


问:
Dynamic formatting user input in Angular 2
Task: to make dynamic formatting user input for credit cards in Angular 2.

The problem is that when I was deleting a space between the figures, it is removed and does not appear in the input back, although values in deriving the console correct

My component

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
values: any = "";
input_text: string = "10";
tmp: string[] = [];
val: string;

creditCard(event: any) {

if ((/^3[47]\d{0,13}/).test(event.target.value)) {
  this.values = "";
  this.input_text = this.creditCardType.amex.text_length;
  this.val = event.target.value;
  this.val = this.val.replace(/[\W\s\._\-]+/g, '');
  let chunk = [];
  let split = 4;
  for (var i = 0, len = this.val.length; i < len; i += split) {
    split = ( i >= 4 && i <= 10 ) ? 6 : 4;
    chunk.push( this.val.substr( i, split ) );
  }
  this.values = chunk.join(" ");
  console.log(this.values); //after deleting in console: 3456 598756 58745
                            //on input: 3456 59875658745

 }
 }
 }
</code>```

app.component.html

```<code><md-input-container>
 <input mdInput placeholder="creditCard" (keyup)="creditCard($event)"[value]=values [attr.maxlength]=input_text numbers>
  </md-input-container>

<p>{{values}}</p>
</code>```

I need that space can not be removed or after removing it displays back on the input.

答:
Instead of [value]=values  try [(ngModel)]='values'

```<code><md-input-container> <input mdInput placeholder="creditCard"     (keyup)="creditCard($event)" [(ngModel)]='values' [attr.maxlength]=input_text numbers>
  </md-input-container>
</code>```

[]    -> is one-way data binding
[()]  -> is two-way data binding

Body:
Task: to make dynamic formatting user input for credit cards in Angular 2.

The problem is that when I was deleting a space between the figures, it is removed and does not appear in the input back, although values in deriving the console correct

My component

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
values: any = "";
input_text: string = "10";
tmp: string[] = [];
val: string;

creditCard(event: any) {

if ((/^3[47]\d{0,13}/).test(event.target.value)) {
  this.values = "";
  this.input_text = this.creditCardType.amex.text_length;
  this.val = event.target.value;
  this.val = this.val.replace(/[\W\s\._\-]+/g, '');
  let chunk = [];
  let split = 4;
  for (var i = 0, len = this.val.length; i < len; i += split) {
    split = ( i >= 4 && i <= 10 ) ? 6 : 4;
    chunk.push( this.val.substr( i, split ) );
  }
  this.values = chunk.join(" ");
  console.log(this.values); //after deleting in console: 3456 598756 58745
                            //on input: 3456 59875658745

 }
 }
 }

app.component.html

<md-input-container>
 <input mdInput placeholder="creditCard" (keyup)="creditCard($event)"[value]=values [attr.maxlength]=input_text numbers>
  </md-input-container>

{{values}}

I need that space can not be removed or after removing it displays back on the input.

Body:
Instead of [value]=values  try [(ngModel)]='values'

<md-input-container> <input mdInput placeholder="creditCard"     (keyup)="creditCard($event)" [(ngModel)]='values' [attr.maxlength]=input_text numbers>
  </md-input-container>

[]    -> is one-way data binding
[()]  -> is two-way data binding


问:
How to remove one of the duplicate values that are next to each other in a list?
```<code>x1 = [5, 5]
x2 = [1, 5, 5, 2]
x3 = [5, 5, 1, 2, 5, 5]
x4 = [5, 5, 1, 5, 5, 2, 5, 5]
x5 = [5, -5]
x6 = [1, 2, 3, 4]
x7 = [5, 5, 5, 5, 5, 5]
</code>```

How do I remove one of the duplicate values that are next to each other on every list?

After all one of the duplicate values that are next to each other are removed, they should look like this:

```<code>x1 = [5]
x2 = [1, 5, 2]
x3 = [5, 1, 2, 5]
x4 = [5, 1, 5, 2, 5]
x5 = [5, -5]
x6 = [1, 2, 3, 4]
x7 = [5]
</code>```

答:
You can just loop over your list while keeping track of the previous value, and only keep the next value if they differ:</p>

```<code>def uniquefy_conseq_vals(my_list):
    prev = None
    new_list = []
    for ele in my_list:
        if ele != prev:
            new_list.append(ele)
        prev = ele
    return new_list

if __name__ == "__main__":

    x1 = [5, 5]
    x2 = [1, 5, 5, 2]
    x3 = [5, 5, 1, 2, 5, 5]
    x4 = [5, 5, 1, 5, 5, 2, 5, 5]
    x5 = [5, -5]
    x6 = [1, 2, 3, 4]
    x7 = [5, 5, 5, 5, 5, 5]

    print uniquefy_conseq_vals(x1)
    print uniquefy_conseq_vals(x2)
    print uniquefy_conseq_vals(x3)
    print uniquefy_conseq_vals(x4)
    print uniquefy_conseq_vals(x5)
    print uniquefy_conseq_vals(x6)
    print uniquefy_conseq_vals(x7)
</code>```

Body:
x1 = [5, 5]
x2 = [1, 5, 5, 2]
x3 = [5, 5, 1, 2, 5, 5]
x4 = [5, 5, 1, 5, 5, 2, 5, 5]
x5 = [5, -5]
x6 = [1, 2, 3, 4]
x7 = [5, 5, 5, 5, 5, 5]

How do I remove one of the duplicate values that are next to each other on every list?

After all one of the duplicate values that are next to each other are removed, they should look like this:

x1 = [5]
x2 = [1, 5, 2]
x3 = [5, 1, 2, 5]
x4 = [5, 1, 5, 2, 5]
x5 = [5, -5]
x6 = [1, 2, 3, 4]
x7 = [5]

Body:
You can just loop over your list while keeping track of the previous value, and only keep the next value if they differ:

def uniquefy_conseq_vals(my_list):
    prev = None
    new_list = []
    for ele in my_list:
        if ele != prev:
            new_list.append(ele)
        prev = ele
    return new_list

if __name__ == "__main__":

    x1 = [5, 5]
    x2 = [1, 5, 5, 2]
    x3 = [5, 5, 1, 2, 5, 5]
    x4 = [5, 5, 1, 5, 5, 2, 5, 5]
    x5 = [5, -5]
    x6 = [1, 2, 3, 4]
    x7 = [5, 5, 5, 5, 5, 5]

    print uniquefy_conseq_vals(x1)
    print uniquefy_conseq_vals(x2)
    print uniquefy_conseq_vals(x3)
    print uniquefy_conseq_vals(x4)
    print uniquefy_conseq_vals(x5)
    print uniquefy_conseq_vals(x6)
    print uniquefy_conseq_vals(x7)


问:
Struts 2 - Exception starting filter struts2
I just started with this Struts 2 HelloWorld Tutorial [1] and exactly followed the steps explained in this tutorial but there is a problem with starting the filters. Here is the console output:

[1] https://www.tutorialspoint.com/struts_2/struts_examples.htm

```<code>Jun 06, 2017 4:53:35 PM org.apache.catalina.core.AprLifecycleListener init
INFORMATION: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.8.0_112\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_131/bin/server;C:/Program Files/Java/jre1.8.0_131/bin;C:/Program Files/Java/jre1.8.0_131/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Enterprise Vault\EVClient\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files\eclipse;;.
Jun 06, 2017 4:53:35 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNUNG: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:HelloWorldStruts2' did not find a matching property.
Jun 06, 2017 4:53:36 PM org.apache.coyote.AbstractProtocol init
INFORMATION: Initializing ProtocolHandler ["http-bio-18080"]
Jun 06, 2017 4:53:36 PM org.apache.catalina.startup.Catalina load
INFORMATION: Initialization processed in 428 ms
Jun 06, 2017 4:53:36 PM org.apache.catalina.core.StandardService startInternal
INFORMATION: Starting service Catalina
Jun 06, 2017 4:53:36 PM org.apache.catalina.core.StandardEngine startInternal
INFORMATION: Starting Servlet Engine: Apache Tomcat/7.0.52
Jun 06, 2017 4:53:39 PM org.apache.catalina.startup.TaglibUriRule body
INFORMATION: TLD skipped. URI: /struts-tags is already defined
Jun 06, 2017 4:53:39 PM org.apache.catalina.core.ApplicationContext log
INFORMATION: No Spring WebApplicationInitializer types detected on classpath
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
Jun 06, 2017 4:53:39 PM org.apache.catalina.core.StandardContext filterStart
SCHWERWIEGEND: Exception starting filter struts2
java.lang.reflect.InvocationTargetException - Class: com.opensymphony.xwork2.inject.ContainerImpl$ConstructorInjector
File: ContainerImpl.java
Method: construct
Line: 427 - com/opensymphony/xwork2/inject/ContainerImpl.java:427:-1
    at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:450)
    at org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:74)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
    at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:260)
    at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:105)
    at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4809)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5485)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.opensymphony.xwork2.inject.ContainerImpl$ConstructorInjector.construct(ContainerImpl.java:427)
    at com.opensymphony.xwork2.inject.ContainerBuilder$5.create(ContainerBuilder.java:218)
    at com.opensymphony.xwork2.inject.Scope$2$1.create(Scope.java:52)
    at com.opensymphony.xwork2.inject.ContainerBuilder$3.create(ContainerBuilder.java:91)
    at com.opensymphony.xwork2.inject.ContainerBuilder$7.call(ContainerBuilder.java:571)
    at com.opensymphony.xwork2.inject.ContainerBuilder$7.call(ContainerBuilder.java:568)
    at com.opensymphony.xwork2.inject.ContainerImpl.callInContext(ContainerImpl.java:560)
    at com.opensymphony.xwork2.inject.ContainerBuilder.create(ContainerBuilder.java:568)
    at com.opensymphony.xwork2.config.impl.DefaultConfiguration.createBootstrapContainer(DefaultConfiguration.java:278)
    at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:160)
    at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:67)
    at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:390)
    at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:437)
    ... 14 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.opensymphony.xwork2.inject.ContainerImpl$ConstructorInjector.construct(ContainerImpl.java:410)
    ... 26 more
Caused by: java.lang.NoSuchMethodError: org.apache.commons.lang3.text.StrSubstitutor.setValueDelimiter(Ljava/lang/String;)Lorg/apache/commons/lang3/text/StrSubstitutor;
    at com.opensymphony.xwork2.config.providers.EnvsValueSubstitutor.<init>(EnvsValueSubstitutor.java:32)
    ... 31 more

Jun 06, 2017 4:53:39 PM org.apache.catalina.core.StandardContext startInternal
SCHWERWIEGEND: Error filterStart
Jun 06, 2017 4:53:39 PM org.apache.catalina.core.StandardContext startInternal
SCHWERWIEGEND: Context [/HelloWorldStruts2] startup failed due to previous errors
Jun 06, 2017 4:53:39 PM org.apache.coyote.AbstractProtocol start
INFORMATION: Starting ProtocolHandler ["http-bio-18080"]
Jun 06, 2017 4:53:39 PM org.apache.catalina.startup.Catalina start
INFORMATION: Server startup in 3183 ms
</code>```

I think there is no need to paste my code here as it is exactly the code as stated in the tutorial link above. Except I replaced

```<code>  <filter-class>
     org.apache.struts2.dispatcher.FilterDispatcher
  </filter-class>
</code>```

with

```<code>  <filter-class>
     org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  </filter-class>
</code>```

as proposed in this answer, which did not resolve the issue: java.lang.ClassNotFoundException: org.apache.struts2.dispatcher.FilterDispatcher
I am using struts 2.3.4, but tried it also with struts 2.2 and 2.5 - neither works.

答: I found the flaw: I have left the struts 2.5 jars in the "Deployment Assembly", since some other post proposed this when it showed some other exception. I removed them and booom.. now it works. Thanks, Aleksandr!

Body:
I just started with this Struts 2 HelloWorld Tutorial [1] and exactly followed the steps explained in this tutorial but there is a problem with starting the filters. Here is the console output:

[1] https://www.tutorialspoint.com/struts_2/struts_examples.htm

Jun 06, 2017 4:53:35 PM org.apache.catalina.core.AprLifecycleListener init
INFORMATION: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.8.0_112\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_131/bin/server;C:/Program Files/Java/jre1.8.0_131/bin;C:/Program Files/Java/jre1.8.0_131/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Enterprise Vault\EVClient\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files\eclipse;;.
Jun 06, 2017 4:53:35 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNUNG: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:HelloWorldStruts2' did not find a matching property.
Jun 06, 2017 4:53:36 PM org.apache.coyote.AbstractProtocol init
INFORMATION: Initializing ProtocolHandler ["http-bio-18080"]
Jun 06, 2017 4:53:36 PM org.apache.catalina.startup.Catalina load
INFORMATION: Initialization processed in 428 ms
Jun 06, 2017 4:53:36 PM org.apache.catalina.core.StandardService startInternal
INFORMATION: Starting service Catalina
Jun 06, 2017 4:53:36 PM org.apache.catalina.core.StandardEngine startInternal
INFORMATION: Starting Servlet Engine: Apache Tomcat/7.0.52
Jun 06, 2017 4:53:39 PM org.apache.catalina.startup.TaglibUriRule body
INFORMATION: TLD skipped. URI: /struts-tags is already defined
Jun 06, 2017 4:53:39 PM org.apache.catalina.core.ApplicationContext log
INFORMATION: No Spring WebApplicationInitializer types detected on classpath
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
Jun 06, 2017 4:53:39 PM org.apache.catalina.core.StandardContext filterStart
SCHWERWIEGEND: Exception starting filter struts2
java.lang.reflect.InvocationTargetException - Class: com.opensymphony.xwork2.inject.ContainerImpl$ConstructorInjector
File: ContainerImpl.java
Method: construct
Line: 427 - com/opensymphony/xwork2/inject/ContainerImpl.java:427:-1
    at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:450)
    at org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:74)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
    at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:260)
    at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:105)
    at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4809)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5485)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.opensymphony.xwork2.inject.ContainerImpl$ConstructorInjector.construct(ContainerImpl.java:427)
    at com.opensymphony.xwork2.inject.ContainerBuilder$5.create(ContainerBuilder.java:218)
    at com.opensymphony.xwork2.inject.Scope$2$1.create(Scope.java:52)
    at com.opensymphony.xwork2.inject.ContainerBuilder$3.create(ContainerBuilder.java:91)
    at com.opensymphony.xwork2.inject.ContainerBuilder$7.call(ContainerBuilder.java:571)
    at com.opensymphony.xwork2.inject.ContainerBuilder$7.call(ContainerBuilder.java:568)
    at com.opensymphony.xwork2.inject.ContainerImpl.callInContext(ContainerImpl.java:560)
    at com.opensymphony.xwork2.inject.ContainerBuilder.create(ContainerBuilder.java:568)
    at com.opensymphony.xwork2.config.impl.DefaultConfiguration.createBootstrapContainer(DefaultConfiguration.java:278)
    at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:160)
    at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:67)
    at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:390)
    at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:437)
    ... 14 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.opensymphony.xwork2.inject.ContainerImpl$ConstructorInjector.construct(ContainerImpl.java:410)
    ... 26 more
Caused by: java.lang.NoSuchMethodError: org.apache.commons.lang3.text.StrSubstitutor.setValueDelimiter(Ljava/lang/String;)Lorg/apache/commons/lang3/text/StrSubstitutor;
    at com.opensymphony.xwork2.config.providers.EnvsValueSubstitutor.<init>(EnvsValueSubstitutor.java:32)
    ... 31 more

Jun 06, 2017 4:53:39 PM org.apache.catalina.core.StandardContext startInternal
SCHWERWIEGEND: Error filterStart
Jun 06, 2017 4:53:39 PM org.apache.catalina.core.StandardContext startInternal
SCHWERWIEGEND: Context [/HelloWorldStruts2] startup failed due to previous errors
Jun 06, 2017 4:53:39 PM org.apache.coyote.AbstractProtocol start
INFORMATION: Starting ProtocolHandler ["http-bio-18080"]
Jun 06, 2017 4:53:39 PM org.apache.catalina.startup.Catalina start
INFORMATION: Server startup in 3183 ms

I think there is no need to paste my code here as it is exactly the code as stated in the tutorial link above. Except I replaced

  <filter-class>
     org.apache.struts2.dispatcher.FilterDispatcher
  </filter-class>

with

  <filter-class>
     org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  </filter-class>

as proposed in this answer, which did not resolve the issue: java.lang.ClassNotFoundException: org.apache.struts2.dispatcher.FilterDispatcher
I am using struts 2.3.4, but tried it also with struts 2.2 and 2.5 - neither works.


问:
skstoreproductviewcontroller: how to open "rating and review" at launch
I see some tutorial about SKStoreProductViewController, such as:
Open a list of my apps in the App Store within my App

However, it always opens SKStoreProductViewController with "Details" at launch, how can I open "rating and review" programmatically

答:
Below code snippet will open the reviews & ratings section on native AppStore app

```<code>struct AppStoreURLs {
    static let templateReviewURLiOS8 = "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=%@&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software"
}

func showAppReivewScreen(_ appId: String?)  {

        guard let applicaitonIdentifier = appId, (applicaitonIdentifier.isEmpty == false) else { return }

                let reivewURL = String(format: AppStoreURLs.templateReviewURLiOS8, applicaitonIdentifier)

        if let url = URL(string: reivewURL), UIApplication.shared.canOpenURL(url) {

            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url, options: [UIApplicationOpenURLOptionUniversalLinksOnly : false], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(url)
            }
        }

    }
</code>```

call this function using application identifier

```<code>self.showAppReivewScreen("951627022")
</code>```

Body:
Below code snippet will open the reviews & ratings section on native AppStore app

struct AppStoreURLs {
    static let templateReviewURLiOS8 = "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=%@&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software"
}

func showAppReivewScreen(_ appId: String?)  {

        guard let applicaitonIdentifier = appId, (applicaitonIdentifier.isEmpty == false) else { return }

                let reivewURL = String(format: AppStoreURLs.templateReviewURLiOS8, applicaitonIdentifier)

        if let url = URL(string: reivewURL), UIApplication.shared.canOpenURL(url) {

            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url, options: [UIApplicationOpenURLOptionUniversalLinksOnly : false], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(url)
            }
        }

    }

call this function using application identifier

self.showAppReivewScreen("951627022")


问:
How to Preserve aspect ratio of a button image .net
I'm trying to re-size an image of the Button control while preserving the aspect ratio from the original image so the new image doesn't look squashed/stretched.

And when i again get it back to the original position (Normal Window Maximized state) it should retain its original resolution.

Basically i want the images in all of monitor resolutions to look the same.

For ex: In my application,
An image of a Globe looks fine with the monitor resolution 1280 * 1024 (5:4)
but looks stretched like an ellipse with the monitor resolution 1920×1080 (16:9)

I know i have to do some form of transformation programatically, but am not getting how to do it. I tried calling the below method on OnResize event, though it works for the first iteration, the images gets smaller on subsequent resizing and finally i lose my image finally.

public Rectangle MaintainAspectRatio(Image imgPhoto, Rectangle thumbRect)
    {
        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;
        int sourceX = 0;
        int sourceY = 0;
        int destX = 0;
        int destY = 0;

```<code>    float nPercent = 0;
    float nPercentW = 0;
    float nPercentH = 0;

    nPercentW = ((float)thumbRect.Width / (float)sourceWidth);
    nPercentH = ((float)thumbRect.Height / (float)sourceHeight);

    //if we have to pad the height pad both the top and the bottom
    //with the difference between the scaled height and the desired height
    if (nPercentH < nPercentW)
    {
        nPercent = nPercentH;
        destX = (int)((thumbRect.Width - (sourceWidth * nPercent)) / 2);
    }
    else
    {
        nPercent = nPercentW;
        destY = (int)((thumbRect.Height - (sourceHeight * nPercent)) / 2);
    }

    int destWidth = (int)(sourceWidth * nPercent);
    int destHeight = (int)(sourceHeight * nPercent);

    Rectangle retRect = new Rectangle(thumbRect.X, thumbRect.Y, destWidth, destHeight);
    return retRect;
}
</code>```

I use this code in my overriden OnPaint eventhandler method as :

protected override void  OnPaint(PaintEventArgs e)
    {
         base.OnPaint(e);
         Graphics g = e.Graphics;

```<code>     int iHeight;
     int iWidth;

     if (Image != null)
     {
         Rectangle ResizedRectangle = MaintainAspectRatio(Image,ClientRectangle);
         iHeight = ResizedRectangle.Height;
         iWidth = ResizedRectangle.Width;

     }
     else
     {
         iWidth = ClientRectangle.Width;
         iHeight = ClientRectangle.Height;
     }

     // Draw border
     Color oLeftTopColor = SystemColors.ControlLightLight;
     Color oRightBottomColor = SystemColors.ActiveCaption;
     Pen oLeftTopPen = new Pen(oLeftTopColor);
     Pen oRightBottomPen = new Pen(oRightBottomColor);
     // top line
     g.DrawLine(oLeftTopPen, 0, 0, iWidth - 1, 0);
     //g.DrawLine(new Pen(SystemColors.ControlLight), 1, 1, iWidth-2, 1);
     // bottom line
     g.DrawLine(oRightBottomPen, 0, iHeight, iWidth - 1, iHeight);
     //g.DrawLine(new Pen(SystemColors.ControlDark), 1, iHeight-2, iWidth-2, iHeight-2);
     // right line
     g.DrawLine(oRightBottomPen, iWidth, 0, iWidth, iHeight - 1);
     //g.DrawLine(new Pen(SystemColors.ControlDark), iWidth-2, 1, iWidth-2, iHeight-2);
     // left line
     g.DrawLine(oLeftTopPen, 0, 0, 0, iHeight - 1);
     //g.DrawLine(new Pen(SystemColors.ControlLightLight), 1, 1, 1, iHeight-2);

     // Draw image
     if (Image != null)
     {

         Rectangle oDrawRectagle = new Rectangle(
            0, 0, iWidth, iHeight);
         if (Enabled == false)
         {
             e.Graphics.DrawImage(Image, oDrawRectagle,
                0, 0, Image.Width, Image.Height,
                GraphicsUnit.Pixel);
         }
         else
         {
             e.Graphics.DrawImage(Image, oDrawRectagle);

         }
     }

     // Draw text
     if (Text != null)
     {
         int iTextTop = 5;
         int iTextLeft = 5;
         int iMaxTextWidth = iWidth - 10;
         int iMaxTextHeight = iHeight - 10;
     }
}
</code>```

Can anyone guide me how should i proceed with this ?

答:
It's not very clear how you are using the image - maybe you should post the code where you actually display the image.

An image might appear deformed on different resolutions if the pixel aspect ratio (PAR) differs in the two resolutions - is this your case? Do you want to display an image independent of the PAR?

In this case you need to keep the image internally at a known DPI value (96, usually) and then stretch it with your method by the values of the current resolution's DPI, which can be obtain with something like this:

```<code>Single xDpi, yDpi;

IntPtr dc = GetDC(IntPtr.Zero);

using(Graphics g = Graphics.FromHdc(dc))
{
    xDpi = g.DpiX;
    yDpi = g.DpiY;
}

if (ReleaseDC(IntPtr.Zero) != 0)
{
    // GetLastError and handle...
}

[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll")]
private static extern Int32 ReleaseDC(IntPtr hwnd);
</code>```

Then you need to scale your image so that final width = original width * 96 / xDpi, and similar for height.

Body:
I'm trying to re-size an image of the Button control while preserving the aspect ratio from the original image so the new image doesn't look squashed/stretched.

And when i again get it back to the original position (Normal Window Maximized state) it should retain its original resolution.

Basically i want the images in all of monitor resolutions to look the same.

For ex: In my application,
An image of a Globe looks fine with the monitor resolution 1280 * 1024 (5:4)
but looks stretched like an ellipse with the monitor resolution 1920×1080 (16:9)

I know i have to do some form of transformation programatically, but am not getting how to do it. I tried calling the below method on OnResize event, though it works for the first iteration, the images gets smaller on subsequent resizing and finally i lose my image finally.

public Rectangle MaintainAspectRatio(Image imgPhoto, Rectangle thumbRect)
    {
        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;
        int sourceX = 0;
        int sourceY = 0;
        int destX = 0;
        int destY = 0;

    float nPercent = 0;
    float nPercentW = 0;
    float nPercentH = 0;

    nPercentW = ((float)thumbRect.Width / (float)sourceWidth);
    nPercentH = ((float)thumbRect.Height / (float)sourceHeight);

    //if we have to pad the height pad both the top and the bottom
    //with the difference between the scaled height and the desired height
    if (nPercentH < nPercentW)
    {
        nPercent = nPercentH;
        destX = (int)((thumbRect.Width - (sourceWidth * nPercent)) / 2);
    }
    else
    {
        nPercent = nPercentW;
        destY = (int)((thumbRect.Height - (sourceHeight * nPercent)) / 2);
    }

    int destWidth = (int)(sourceWidth * nPercent);
    int destHeight = (int)(sourceHeight * nPercent);

    Rectangle retRect = new Rectangle(thumbRect.X, thumbRect.Y, destWidth, destHeight);
    return retRect;
}

I use this code in my overriden OnPaint eventhandler method as :

protected override void  OnPaint(PaintEventArgs e)
    {
         base.OnPaint(e);
         Graphics g = e.Graphics;

     int iHeight;
     int iWidth;

     if (Image != null)
     {
         Rectangle ResizedRectangle = MaintainAspectRatio(Image,ClientRectangle);
         iHeight = ResizedRectangle.Height;
         iWidth = ResizedRectangle.Width;

     }
     else
     {
         iWidth = ClientRectangle.Width;
         iHeight = ClientRectangle.Height;
     }

     // Draw border
     Color oLeftTopColor = SystemColors.ControlLightLight;
     Color oRightBottomColor = SystemColors.ActiveCaption;
     Pen oLeftTopPen = new Pen(oLeftTopColor);
     Pen oRightBottomPen = new Pen(oRightBottomColor);
     // top line
     g.DrawLine(oLeftTopPen, 0, 0, iWidth - 1, 0);
     //g.DrawLine(new Pen(SystemColors.ControlLight), 1, 1, iWidth-2, 1);
     // bottom line
     g.DrawLine(oRightBottomPen, 0, iHeight, iWidth - 1, iHeight);
     //g.DrawLine(new Pen(SystemColors.ControlDark), 1, iHeight-2, iWidth-2, iHeight-2);
     // right line
     g.DrawLine(oRightBottomPen, iWidth, 0, iWidth, iHeight - 1);
     //g.DrawLine(new Pen(SystemColors.ControlDark), iWidth-2, 1, iWidth-2, iHeight-2);
     // left line
     g.DrawLine(oLeftTopPen, 0, 0, 0, iHeight - 1);
     //g.DrawLine(new Pen(SystemColors.ControlLightLight), 1, 1, 1, iHeight-2);

     // Draw image
     if (Image != null)
     {

         Rectangle oDrawRectagle = new Rectangle(
            0, 0, iWidth, iHeight);
         if (Enabled == false)
         {
             e.Graphics.DrawImage(Image, oDrawRectagle,
                0, 0, Image.Width, Image.Height,
                GraphicsUnit.Pixel);
         }
         else
         {
             e.Graphics.DrawImage(Image, oDrawRectagle);

         }
     }

     // Draw text
     if (Text != null)
     {
         int iTextTop = 5;
         int iTextLeft = 5;
         int iMaxTextWidth = iWidth - 10;
         int iMaxTextHeight = iHeight - 10;
     }
}

Can anyone guide me how should i proceed with this ?

Body:
It's not very clear how you are using the image - maybe you should post the code where you actually display the image.

An image might appear deformed on different resolutions if the pixel aspect ratio (PAR) differs in the two resolutions - is this your case? Do you want to display an image independent of the PAR?

In this case you need to keep the image internally at a known DPI value (96, usually) and then stretch it with your method by the values of the current resolution's DPI, which can be obtain with something like this:

Single xDpi, yDpi;

IntPtr dc = GetDC(IntPtr.Zero);

using(Graphics g = Graphics.FromHdc(dc))
{
    xDpi = g.DpiX;
    yDpi = g.DpiY;
}

if (ReleaseDC(IntPtr.Zero) != 0)
{
    // GetLastError and handle...
}

[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll")]
private static extern Int32 ReleaseDC(IntPtr hwnd);

Then you need to scale your image so that final width = original width * 96 / xDpi, and similar for height.


问:
Displaying Text and Images In CSS
I have a database set up for Weapons for Sale and I have my PHP code here:

```<code><?php

echo '<link rel="stylesheet" href="display.css" type="text/css">';

function FindPhoto($name)
{
    $dir_path = "http://www.chemicalzero.com/FireArms_Bis/Guns/";
    $extensions_array = array('jpg','png','jpeg');
    echo "<img src='$dir_path$name' style='width:100px;height:150px'>";
    echo "TESTING";
    echo "</div>";
}

$connection = mysql_connect('localhost', 'USER', 'PASSWORD');
mysql_select_db('DATABASE');

if(mysqli_connect_errno()){
    die("connection failed: "
    . mysqli_connect_error()
    . " (" . mysqli_connect_errno()
    . ")");
}

$query = "SELECT * FROM Guns"; //You don't need a ; like you do in SQL
$result = mysql_query($query);

echo "<table>"; // start a table tag in the HTML

while($row = mysql_fetch_array($result))
{

   print

   "<div id= 'item'>" .
   "<p>Make : ".$row["Make"]."</p>".
   "<p>Model: ".$row["Model"]."</p>".
   "<p>$".$row["Price"]."</p>".
   FindPhoto($row['Photo']);

}
echo "</table>"; //Close the table in HTML

mysql_close(); //Make sure to close out the database connection
</code>```

My PHP displays all information from my database correctly and in the way I want it. The task comes when I incorporate the CSS code:

#item {
  width:100px;
  text-align:center;
  border: 5px solid #D9D9D9;
  padding: 0px;
  list-style: none;
  width: 150px;
  float: left;
  margin-right: 15px;
  margin-bottom: 15px;
  border-radius: 10px;
  -moz-border-radius: 10px; /* firefox rounded corners */
  -webkit-border-radius: 10px; /* Safari rounded corners */
  min-height: 220px;
}

#item li h1 {
  text-align:center;
}

#item li#white {
   min-height: 220px;
}
```

The CSS code works fine except when I combine the two, I get one product that looks great and the other does not get included in the CSS. See picture:

How do I display the images correctly?

答:
Your are not closing the "
" after find image function.
Add ."
" after FindPhoto($row['Photo']);

Title: Displaying Text and Images In CSS

Body:
I have a database set up for Weapons for Sale and I have my PHP code here:

<?php

echo '<link rel="stylesheet" href="display.css" type="text/css">';

function FindPhoto($name)
{
    $dir_path = "http://www.chemicalzero.com/FireArms_Bis/Guns/";
    $extensions_array = array('jpg','png','jpeg');
    echo "";
    echo "TESTING";
    echo "
";
}

$connection = mysql_connect('localhost', 'USER', 'PASSWORD');
mysql_select_db('DATABASE');

if(mysqli_connect_errno()){
    die("connection failed: "
    . mysqli_connect_error()
    . " (" . mysqli_connect_errno()
    . ")");
}

$query = "SELECT * FROM Guns"; //You don't need a ; like you do in SQL
$result = mysql_query($query);

echo "
"; // start a table tag in the HTML

while($row = mysql_fetch_array($result))
{

   print

   "
" .
   "
Make : ".$row["Make"]."
".
   "
Model: ".$row["Model"]."
".
   "
$".$row["Price"]."
".
   FindPhoto($row['Photo']);

}
echo "
"; //Close the table in HTML

mysql_close(); //Make sure to close out the database connection

My PHP displays all information from my database correctly and in the way I want it. The task comes when I incorporate the CSS code:

#item {
  width:100px;
  text-align:center;
  border: 5px solid #D9D9D9;
  padding: 0px;
  list-style: none;
  width: 150px;
  float: left;
  margin-right: 15px;
  margin-bottom: 15px;
  border-radius: 10px;
  -moz-border-radius: 10px; /* firefox rounded corners */
  -webkit-border-radius: 10px; /* Safari rounded corners */
  min-height: 220px;
}

#item li h1 {
  text-align:center;
}

#item li#white {
   min-height: 220px;
}

The CSS code works fine except when I combine the two, I get one product that looks great and the other does not get included in the CSS. See picture:

How do I display the images correctly?

Body:
Your are not closing the "<div class="item">" after find image function.
Add ."</div>" after FindPhoto($row['Photo']);


问:
create a new folder in SVN tags copy file to SVN from Jenkins workspace
I am checking the code from SVN branch from a change number folder to Jenkins. Once the build is success, the artifacts(.WAR) are saving in the Jenkins workspace. I need to create a new folder under SVN /tags/DEV with same change number and copy .WAR file to same folder. Any suggestions please.

答: Yes, you need to be in a SVN working directory. So, what I did is checking out one file from svn. This will turn your directory into a working directory. After that, you can use svn copy command.</p>


问:
How to switch to a specific directory before grepping in emacs?
I am grepping across all my projects:

```<code>(defun grep-all-projects(start end)
  (interactive "r")
  (if (and transient-mark-mode mark-active)
      (setq my-word (buffer-substring-no-properties start end))
    (setq my-word (thing-at-point 'word))
    )
  (let ((default-directory (getenv "REPOS_DIR")))
    (message "===> Grepping '%s' in %s" my-word (getenv "REPOS_DIR"))
    (grep (format "grep --exclude-dir target -r -ne '%s' ." my-word)))
  )
</code>```

But somehow the grepping is performed on the root directory (/), even though the grep buffer correctly says:

```<code>-*- mode: grep; default-directory: "/repos/" -*-
Grep started at Tue Jun  6 10:38:08
</code>```

What is going on? Is emacs grep not respecting the default-directory?

EDIT

This workaround, without making use of default-directory, works:

```<code>(defun grep-all-projects(start end)
  (interactive "r")
  (if (and transient-mark-mode mark-active)
      (setq my-word (buffer-substring-no-properties start end))
    (setq my-word (thing-at-point 'word))
    )
  (message "===> Grepping '%s' in %s" my-word (getenv "REPOS_DIR"))
  (grep (format "grep --exclude-dir target -r -ne '%s' %s" my-word (getenv "REPOS_DIR")))
  )
</code>```

I am still interested in knowing why the first implementation does not work as expected

答:
M-x cd changes to a directory you input. It changes the value of buffer-local variable default-directory.  C-h f cd tells you:

cd is an interactive compiled Lisp function in files.el.

(cd DIR)

Make DIR become the current buffer's default directory.

If your environment includes a CDPATH variable, try each one of
  that list of directories (separated by occurrences of
  path-separator) when resolving a relative directory name.
  The path separator is colon in GNU and GNU-like systems.

Body:
I am grepping across all my projects:

(defun grep-all-projects(start end)
  (interactive "r")
  (if (and transient-mark-mode mark-active)
      (setq my-word (buffer-substring-no-properties start end))
    (setq my-word (thing-at-point 'word))
    )
  (let ((default-directory (getenv "REPOS_DIR")))
    (message "===> Grepping '%s' in %s" my-word (getenv "REPOS_DIR"))
    (grep (format "grep --exclude-dir target -r -ne '%s' ." my-word)))
  )

But somehow the grepping is performed on the root directory (/), even though the grep buffer correctly says:

-*- mode: grep; default-directory: "/repos/" -*-
Grep started at Tue Jun  6 10:38:08

What is going on? Is emacs grep not respecting the default-directory?

EDIT

This workaround, without making use of default-directory, works:

(defun grep-all-projects(start end)
  (interactive "r")
  (if (and transient-mark-mode mark-active)
      (setq my-word (buffer-substring-no-properties start end))
    (setq my-word (thing-at-point 'word))
    )
  (message "===> Grepping '%s' in %s" my-word (getenv "REPOS_DIR"))
  (grep (format "grep --exclude-dir target -r -ne '%s' %s" my-word (getenv "REPOS_DIR")))
  )

I am still interested in knowing why the first implementation does not work as expected


问:
defining the type of a function- int and float on haskell
I have a problem with defining the type of a function. In the cases of 1, 10, 11 and 12, I insert an Int and return a float, but in the case in which I insert an Int and return an Int the types doesn't match.
I tried with
pointsForSeventy:: Int->Float and also with pointsForSeventy:: Real a-> Int->a (I thought this one would work because Integrals and Fractionals are inside the Real numbers)

```<code>pointsForSeventy 1 = 5.5
pointsForSeventy 10 = 0.5
pointsForSeventy 11 = 0.5
pointsForSeventy 12 = 0.5
pointsForSeventy a = a
</code>```

Thanks in advance

答:
Haskell is a statically typed language. So that means that the return type can not depend on the value of the input.

An idea might be to convert the Int into a Float by using fromIntegral :: (Integral a, Num b) => a -> b:

```<code>pointsForSeventy :: Int -> Float
pointsForSeventy 1 = 5.5
pointsForSeventy 10 = 0.5
pointsForSeventy 11 = 0.5
pointsForSeventy 12 = 0.5
pointsForSeventy a = <b>fromIntegral</b> a</code>```

In case you want to treat the Int case different from the Float case, you can also use Either:

```<code>pointsForSeventy :: Int -> <b>Either</b> Float <b>Int</b>
pointsForSeventy 1 = <b>Left</b> 5.5
pointsForSeventy 10 = <b>Left</b> 0.5
pointsForSeventy 11 = <b>Left</b> 0.5
pointsForSeventy 12 = <b>Left</b> 0.5
pointsForSeventy a = <b>Right</b> a</code>```

Body:
I have a problem with defining the type of a function. In the cases of 1, 10, 11 and 12, I insert an Int and return a float, but in the case in which I insert an Int and return an Int the types doesn't match.
I tried with
pointsForSeventy:: Int->Float and also with pointsForSeventy:: Real a-> Int->a (I thought this one would work because Integrals and Fractionals are inside the Real numbers)

pointsForSeventy 1 = 5.5
pointsForSeventy 10 = 0.5
pointsForSeventy 11 = 0.5
pointsForSeventy 12 = 0.5
pointsForSeventy a = a

Thanks in advance

Body:
Haskell is a statically typed language. So that means that the return type can not depend on the value of the input.

An idea might be to convert the Int into a Float by using fromIntegral :: (Integral a, Num b) => a -> b:

pointsForSeventy :: Int -> Float
pointsForSeventy 1 = 5.5
pointsForSeventy 10 = 0.5
pointsForSeventy 11 = 0.5
pointsForSeventy 12 = 0.5
pointsForSeventy a = fromIntegral a

In case you want to treat the Int case different from the Float case, you can also use Either:

pointsForSeventy :: Int -> Either Float Int
pointsForSeventy 1 = Left 5.5
pointsForSeventy 10 = Left 0.5
pointsForSeventy 11 = Left 0.5
pointsForSeventy 12 = Left 0.5
pointsForSeventy a = Right a


问:
Return value from 2 promises undefined
I'm having troubles with a function (uci) expecting a return of a promise but i'm returning two at the same time and when i logged it i get

```<code>uci promise Promise {
2|wscontro |   _bitField: 0,
2|wscontro |   _fulfillmentHandler0: undefined,
2|wscontro |   _rejectionHandler0: undefined,
2|wscontro |   _promise0: undefined,
2|wscontro |   _receiver0: undefined }
</code>```

I need this value to pass into a function and deal with uciData to go on...

```<code> ServicesController.prototype.updateWifi = function (req, res, next) { //this is what i call when i click on the button in the screen
    createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'updateWifi', 'inicio');
    var data = req.body;
    var state;
    if(data.state=="1"){
        state=1;
    } else if(data.state=="0"){
        state=0;
    }
    if (isEmptyObject(data)) {
        res.status(400).send({error: errorMessage.emptyBody});
        return;
    }

    if (data.sn === undefined || data.sn === "") {
        createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'updateWifi', 'Invalid serial number');
        res.status(400).send({error: "Invalid serial number"});
        return;
    }

     Database.Devices.getDeviceBySn(data.sn).then(function (device) {
        createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'updateWifi', 'device', device);
        createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'updateWifi', 'device.id', device[0].id);

        var ifname=data.ifname;
        return ServicesController.prototype.uci(device[0], "teste_wireless", "wifi", ifname, "disabled", data.state, true, true).then(function(wifiData){
            console.log('updateWifi ---> data',wifiData);
            if (wifiData != undefined) {
                res.status(404).end();
            } else {
                console.log('updateDeviceInterface ', device[0].id, ' for ', ifname, ' to ', state);
                Database.Services.updateWifiDeviceInterface(device[0].id, ifname, state);
                res.status(200).send(wifiData);
            }
        }).catch(function (e) {
            createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'updateWifi', e);
            res.status(500).send(e);
        });
    });
}

ServicesController.prototype.uci = function(device, config, path, section, opt, value, apply, commit){
    createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'inicio');

    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'config', config);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'path', path);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'section', section);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'option', opt);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'value', value);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'apply', apply);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'commit', commit);

    var values={opt:value};

    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'session', radioAccess[device.id]);

    var result;

    Controllers.Ubus.uciRequest('set', {"config": config, "section": section, values}, device).then(function (uciData) {
        console.log('uci uciData -->', uciData); //this gets undefined

        if (uciData!=null) {
            createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'depois do if do uciData' );
            /*return new Promise(function (resolve, reject) {
                return Controllers.Ubus.uciRequest('changes', config, device).then(function (dataAuth) {
                    if (dataAuth!=null) {
                        createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'Invalid serial number');
                        res.status(400).send({error: "Cant apply changes"});
                        return;
                    }
                }).catch(function (e) {
                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', e);
                    reject(e);
                });
            }).catch(function (e) {
                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', e);
                    reject(e);
                });
        };*/
            if(commit){
                createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'commit');
                return new Promise(function (resolve, reject) {
                    Controllers.Ubus.uciRequest('commit', {"config": config}, device).then(function (dataCommit) {
                        if (dataCommit) {
                            createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'commit data', dataCommit);
                            if (dataCommit.result) {
                                if (dataCommit.result[0] == 0) {
                                    result = dataCommit.result[1];
                                } else {
                                    resolve(null);
                                }
                            } else {
                                resolve(null);
                            }
                        }
                    }).catch(function (e) {
                        createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', e);
                        reject(e);
                    });
                }).catch(function (e) {
                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', e);
                    reject(e);
                });
            }
            if(apply){
                createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'apply');
                return new Promise(function (resolve, reject) {
                    Controllers.Ubus.fileExec(device.id, "exec", path, "restart").then(function (dataApply) {
                        if(dataApply){
                            createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'apply data', dataApply);
                            if (dataApply.result) {
                                if (dataApply.result[0] == 0) {
                                    result+= dataApply.result[1];
                                } else {
                                    resolve(null);
                                }
                            } else {
                                resolve(null);
                            }
                        }
                    }).catch(function (e) {
                        createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', e);
                        reject(e);
                    });
                }).catch(function (e) {
                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', e);
                    reject(e);
                });
            }
        }
        createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'depois do fim do if do uciData' );
    }).catch(function (e) {
        createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', e);
    });
}
</code>```

答:
This code need maaaaaasssive refactoring.

However you can use Promise.all to return after 2 promises are fulfill.

Look like something like this.

```<code>ServicesController.prototype.uci = function(device, config, path, section, opt, value, apply, commit){
    var values={opt:value};

    return Controllers.Ubus.uciRequest('set', {"config": config, "section": section, values}, device)
      .then(function (uciData) {
        var promises = [];

        if (uciData!=null) {
            createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'depois do if do uciData' );

            if (commit){
                createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'commit');
                var p1 = Controllers.Ubus.uciRequest('commit', {"config": config}, device)
                  .then(function (dataCommit) {
                    if (dataCommit && dataCommit.hasOwnProperty('result') && data.result[0] == 0) {
                      createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'commit data', dataCommit);
                      return dataCommit.result[1];
                    }
                  })
              promises.push(p1);
            }

            if(apply){
                createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'apply');
                var p2 = Controllers.Ubus.fileExec(device.id, "exec", path, "restart")
                  .then(function (dataApply) {
                  ...
                })
              promises.push(p2);
            }
        }
        return Promise.all(promises);
        //the function is going to return an array like [dataCommit, applyCommit] or [undefined, undefined] depend of the commit / apply
    })
}
</code>```

Title: Return value from 2 promises undefined

Body:
I'm having troubles with a function (uci) expecting a return of a promise but i'm returning two at the same time and when i logged it i get

uci promise Promise {
2|wscontro |   _bitField: 0,
2|wscontro |   _fulfillmentHandler0: undefined,
2|wscontro |   _rejectionHandler0: undefined,
2|wscontro |   _promise0: undefined,
2|wscontro |   _receiver0: undefined }

I need this value to pass into a function and deal with uciData to go on...

 ServicesController.prototype.updateWifi = function (req, res, next) { //this is what i call when i click on the button in the screen
    createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'updateWifi', 'inicio');
    var data = req.body;
    var state;
    if(data.state=="1"){
        state=1;
    } else if(data.state=="0"){
        state=0;
    }
    if (isEmptyObject(data)) {
        res.status(400).send({error: errorMessage.emptyBody});
        return;
    }

    if (data.sn === undefined || data.sn === "") {
        createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'updateWifi', 'Invalid serial number');
        res.status(400).send({error: "Invalid serial number"});
        return;
    }

     Database.Devices.getDeviceBySn(data.sn).then(function (device) {
        createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'updateWifi', 'device', device);
        createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'updateWifi', 'device.id', device[0].id);

        var ifname=data.ifname;
        return ServicesController.prototype.uci(device[0], "teste_wireless", "wifi", ifname, "disabled", data.state, true, true).then(function(wifiData){
            console.log('updateWifi ---> data',wifiData);
            if (wifiData != undefined) {
                res.status(404).end();
            } else {
                console.log('updateDeviceInterface ', device[0].id, ' for ', ifname, ' to ', state);
                Database.Services.updateWifiDeviceInterface(device[0].id, ifname, state);
                res.status(200).send(wifiData);
            }
        }).catch(function (e) {
            createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'updateWifi', e);
            res.status(500).send(e);
        });
    });
}

ServicesController.prototype.uci = function(device, config, path, section, opt, value, apply, commit){
    createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'inicio');

    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'config', config);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'path', path);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'section', section);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'option', opt);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'value', value);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'apply', apply);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'commit', commit);

    var values={opt:value};

    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'session', radioAccess[device.id]);

    var result;

    Controllers.Ubus.uciRequest('set', {"config": config, "section": section, values}, device).then(function (uciData) {
        console.log('uci uciData -->', uciData); //this gets undefined

        if (uciData!=null) {
            createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'depois do if do uciData' );
            /*return new Promise(function (resolve, reject) {
                return Controllers.Ubus.uciRequest('changes', config, device).then(function (dataAuth) {
                    if (dataAuth!=null) {
                        createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'Invalid serial number');
                        res.status(400).send({error: "Cant apply changes"});
                        return;
                    }
                }).catch(function (e) {
                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', e);
                    reject(e);
                });
            }).catch(function (e) {
                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', e);
                    reject(e);
                });
        };*/
            if(commit){
                createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'commit');
                return new Promise(function (resolve, reject) {
                    Controllers.Ubus.uciRequest('commit', {"config": config}, device).then(function (dataCommit) {
                        if (dataCommit) {
                            createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'commit data', dataCommit);
                            if (dataCommit.result) {
                                if (dataCommit.result[0] == 0) {
                                    result = dataCommit.result[1];
                                } else {
                                    resolve(null);
                                }
                            } else {
                                resolve(null);
                            }
                        }
                    }).catch(function (e) {
                        createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', e);
                        reject(e);
                    });
                }).catch(function (e) {
                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', e);
                    reject(e);
                });
            }
            if(apply){
                createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'apply');
                return new Promise(function (resolve, reject) {
                    Controllers.Ubus.fileExec(device.id, "exec", path, "restart").then(function (dataApply) {
                        if(dataApply){
                            createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'apply data', dataApply);
                            if (dataApply.result) {
                                if (dataApply.result[0] == 0) {
                                    result+= dataApply.result[1];
                                } else {
                                    resolve(null);
                                }
                            } else {
                                resolve(null);
                            }
                        }
                    }).catch(function (e) {
                        createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', e);
                        reject(e);
                    });
                }).catch(function (e) {
                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', e);
                    reject(e);
                });
            }
        }
        createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'depois do fim do if do uciData' );
    }).catch(function (e) {
        createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', e);
    });
}

Body:
This code need maaaaaasssive refactoring.

However you can use Promise.all to return after 2 promises are fulfill.

Look like something like this.

ServicesController.prototype.uci = function(device, config, path, section, opt, value, apply, commit){
    var values={opt:value};

    return Controllers.Ubus.uciRequest('set', {"config": config, "section": section, values}, device)
      .then(function (uciData) {
        var promises = [];

        if (uciData!=null) {
            createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'depois do if do uciData' );

            if (commit){
                createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'commit');
                var p1 = Controllers.Ubus.uciRequest('commit', {"config": config}, device)
                  .then(function (dataCommit) {
                    if (dataCommit && dataCommit.hasOwnProperty('result') && data.result[0] == 0) {
                      createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'commit data', dataCommit);
                      return dataCommit.result[1];
                    }
                  })
              promises.push(p1);
            }

            if(apply){
                createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'apply');
                var p2 = Controllers.Ubus.fileExec(device.id, "exec", path, "restart")
                  .then(function (dataApply) {
                  ...
                })
              promises.push(p2);
            }
        }
        return Promise.all(promises);
        //the function is going to return an array like [dataCommit, applyCommit] or [undefined, undefined] depend of the commit / apply
    })
}


问:
Can you run all JUnit tests in a package from the command line without explicitly listing them?
Provided the test classes and JUnit are both on the classpath, one can run JUnit tests from the command line as follows:

```<code>java org.junit.runner.JUnitCore TestClass1 TestClass2
</code>```

Now, is there a way to run all tests in a package (and sub-packages) as well?

I'm looking for something like

```<code>java org.junit.runner.JUnitCore com.example.tests.testsIWantToRun.*
</code>```

Is there an easy way of doing that (that doesn't involve maven or ant)?

答:
With JUnit 4 this is supported using an extension called cpsuite. All you need to do is add it to your test classpath (maven io.takari.junit:takari-cpsuite), create a dynamic test suite class:

```<code>package com.mycompany;
import org.junit.extensions.cpsuite.ClasspathSuite;
import org.junit.runner.RunWith;

@RunWith(ClasspathSuite.class)
@ClasspathSuite.IncludeJars(true)
public class RunAllTests {}
</code>```

and run it:

```<code>java -cp ${CP} org.junit.runner.JUnitCore com.mycompany.RunAllTests
</code>```

Your classpath ${CP} should include your test jar, junit, hamcrest and cpsuite.

Body:
Provided the test classes and JUnit are both on the classpath, one can run JUnit tests from the command line as follows:

java org.junit.runner.JUnitCore TestClass1 TestClass2

Now, is there a way to run all tests in a package (and sub-packages) as well?

I'm looking for something like

java org.junit.runner.JUnitCore com.example.tests.testsIWantToRun.*

Is there an easy way of doing that (that doesn't involve maven or ant)?

Body:
With JUnit 4 this is supported using an extension called cpsuite. All you need to do is add it to your test classpath (maven io.takari.junit:takari-cpsuite), create a dynamic test suite class:

package com.mycompany;
import org.junit.extensions.cpsuite.ClasspathSuite;
import org.junit.runner.RunWith;

@RunWith(ClasspathSuite.class)
@ClasspathSuite.IncludeJars(true)
public class RunAllTests {}

and run it:

java -cp ${CP} org.junit.runner.JUnitCore com.mycompany.RunAllTests

Your classpath ${CP} should include your test jar, junit, hamcrest and cpsuite.


问:
VS2015 build fail "Duplicate identifier" Angular 2
My build is failing with this error after I installed and uninstalled angular-cli:

1>...\node_modules\@types\jasmine\index.d.ts(9,18): error TS2300: Build:Duplicate identifier 'describe'.
1>...\node_modules\@types\jasmine\index.d.ts(11,18): error TS2300: Build:Duplicate identifier 'xdescribe'.
1>...\node_modules\@types\jasmine\index.d.ts(13,18): error TS2300: Build:Duplicate identifier 'it'.
1>...\node_modules\@types\jasmine\index.d.ts(15,18): error TS2300: Build:Duplicate identifier 'xit'.
1>...\node_modules\@types\mocha\index.d.ts(33,13): error TS2300: Build:Duplicate identifier 'describe'.
1>...\node_modules\@types\mocha\index.d.ts(34,13): error TS2300: Build:Duplicate identifier 'xdescribe'.
1>...\node_modules\@types\mocha\index.d.ts(39,13): error TS2300: Build:Duplicate identifier 'it'.
1>...\node_modules\@types\mocha\index.d.ts(40,13): error TS2300: Build:Duplicate identifier 'xit'.

The solution is very messy at the moment and I'm new to Angular 2/TypeScript, so it's being very hard to debug. I tried this solution Typescript, confusing "duplicate identifier" error message but it did not work for me.

tsconfig.json:

```<code>{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "*": [ "./node_modules/@types/*", "*" ]
     },
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "types": [ ],
     "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "/node_modules",
    "../node_modules",
    "*node_modules*",
    "/node_modules*",
    "angular2",
    "rxjs",
    "typings"
  ]
}
</code>```

答: Looks like a .d.ts definition collision. Are you using both Jasmine and Mocha? If not, remove whichever you aren't using, then delete your node_modules folder and run npm install again.

Body:
My build is failing with this error after I installed and uninstalled angular-cli:

1>...\node_modules\@types\jasmine\index.d.ts(9,18): error TS2300: Build:Duplicate identifier 'describe'.
1>...\node_modules\@types\jasmine\index.d.ts(11,18): error TS2300: Build:Duplicate identifier 'xdescribe'.
1>...\node_modules\@types\jasmine\index.d.ts(13,18): error TS2300: Build:Duplicate identifier 'it'.
1>...\node_modules\@types\jasmine\index.d.ts(15,18): error TS2300: Build:Duplicate identifier 'xit'.
1>...\node_modules\@types\mocha\index.d.ts(33,13): error TS2300: Build:Duplicate identifier 'describe'.
1>...\node_modules\@types\mocha\index.d.ts(34,13): error TS2300: Build:Duplicate identifier 'xdescribe'.
1>...\node_modules\@types\mocha\index.d.ts(39,13): error TS2300: Build:Duplicate identifier 'it'.
1>...\node_modules\@types\mocha\index.d.ts(40,13): error TS2300: Build:Duplicate identifier 'xit'.

The solution is very messy at the moment and I'm new to Angular 2/TypeScript, so it's being very hard to debug. I tried this solution Typescript, confusing "duplicate identifier" error message but it did not work for me.

tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "*": [ "./node_modules/@types/*", "*" ]
     },
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "types": [ ],
     "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "/node_modules",
    "../node_modules",
    "*node_modules*",
    "/node_modules*",
    "angular2",
    "rxjs",
    "typings"
  ]
}


问:
How to pass the query result to another method
I am querying

```<code>select empname
from employee
where empsal > 5000
</code>```

I got 3 rows (one column having 3 rows) and now I want to return this as string array.

And then I want the strings in the String array as separate string

答: Loop through your ResultSet with rs.next() and then add each row to an ArrayList<String>. Then you can get your "separate strings" by their index.

Body:
I am querying

select empname
from employee
where empsal > 5000

I got 3 rows (one column having 3 rows) and now I want to return this as string array.

And then I want the strings in the String array as separate string


问:
React native nat find file ~/.profile
I want to create android project but I stuck at the setup step 4

I don't know where ~/.profile is.

Can you guys tell me where is that file ?

答:
Problem solve!

Finally I found .profile file
It's in ~/etc/.profile

and then copy this code and paste it

export ANDROID_HOME=${HOME}/Library/Android/sdk
 export PATH=${PATH}:${ANDROID_HOME}/tools
 export PATH=${PATH}:${ANDROID_HOME}/platform-tools

That's it.

Title: React native nat find file ~/.profile


问:
Properly filtering DataGridView DataSource with buttons
The main goal is to not alter the DataSource. So, when I get my result set, I want to filter based on this result set ALWAYS. I have been using a DataGridView and the pre-existing code is limited to adding the rows directly to the DataGridView rather than using a DataTable.

I have tried this and it works but I feel as though it is not incredibly efficient and was wondering if there is an optimal solution that doesn't require looping through.

This is on a button press:

```<code>for (int i = 0; i < this.dataGridView1.RowCount; i++)
    {
     if (this.dataGridView.Rows[i].Cells[3].Value = "Sleeping Disorder")
     {
       this.dataGridView.Rows[i].Visible = true;
     }
     else
     {
       this.dataGridView.Rows[i].Visible = false;
      }
    }
</code>```

I researched a bit and saw people using DataTables but I am not permitted to re-work the entire code-set, so I am wondering if I can do this without a DataTable or if I have to use a DataTable, could I use a method to populate a Table with my DataGridView and go from there?

Data initially comes from a MySQL query.
Thanks.

答:
a snippet I use to filter a DataGrid </p>

```<code>// DevicesGrid is the DataGrid with the data I want to filter
// this next line gets the textbox contents to filter on, you won't need this
Controls.TextBox textbox = sender as Controls.TextBox;
        ICollectionView cvs = CollectionViewSource.GetDefaultView(DevicesGrid.ItemsSource);

   // doing the filter
// A PortResult is what is in the collection, replace that with whatever is in yours
        cvs.Filter = new Predicate<object>(item =>
        {
            PortResult pr = item as PortResult;
            if (pr.Name.Contains(textbox.Text))
            { return true; }
            else { return false; }
        });
</code>```

Body:
The main goal is to not alter the DataSource. So, when I get my result set, I want to filter based on this result set ALWAYS. I have been using a DataGridView and the pre-existing code is limited to adding the rows directly to the DataGridView rather than using a DataTable.

I have tried this and it works but I feel as though it is not incredibly efficient and was wondering if there is an optimal solution that doesn't require looping through.

This is on a button press:

for (int i = 0; i < this.dataGridView1.RowCount; i++)
    {
     if (this.dataGridView.Rows[i].Cells[3].Value = "Sleeping Disorder")
     {
       this.dataGridView.Rows[i].Visible = true;
     }
     else
     {
       this.dataGridView.Rows[i].Visible = false;
      }
    }

I researched a bit and saw people using DataTables but I am not permitted to re-work the entire code-set, so I am wondering if I can do this without a DataTable or if I have to use a DataTable, could I use a method to populate a Table with my DataGridView and go from there?

Data initially comes from a MySQL query.
Thanks.

Body:
a snippet I use to filter a DataGrid

// DevicesGrid is the DataGrid with the data I want to filter
// this next line gets the textbox contents to filter on, you won't need this
Controls.TextBox textbox = sender as Controls.TextBox;
        ICollectionView cvs = CollectionViewSource.GetDefaultView(DevicesGrid.ItemsSource);

   // doing the filter
// A PortResult is what is in the collection, replace that with whatever is in yours
        cvs.Filter = new Predicate<object>(item =>
        {
            PortResult pr = item as PortResult;
            if (pr.Name.Contains(textbox.Text))
            { return true; }
            else { return false; }
        });


问:
every letter different color in string, HTML PHP
I need to print every character of string with different color (not random colors) using only HTML and PHP. It almost works, but first letter from array is black. Do you know why?</p>

```<code><html>
    <?php
        $myString = ["s","t","r","i","n","g"];
        $myColors = ["blue","green","yellow","brown","gray","pink"];

        for ($i = 0; $i < count($myString); $i++) {
            echo "$myString[$i] <span style='color:$myColors[$i]'</span>";
        }
    ?>
</html>
</code>```

答:
```<code><html>
<?php
$myString = ["s","t","r","i","n","g"];
$myColors = ["blue","green","yellow","brown","gray","pink"];

for ($i = 0; $i < count($myString); $i++) {

   echo "<span style='color:$myColors[$i]'> $myString[$i] </span>";

}
?>
</html>
</code>```

Body:
I need to print every character of string with different color (not random colors) using only HTML and PHP. It almost works, but first letter from array is black. Do you know why?

    <?php
        $myString = ["s","t","r","i","n","g"];
        $myColors = ["blue","green","yellow","brown","gray","pink"];

        for ($i = 0; $i < count($myString); $i++) {
            echo "$myString[$i] <span style='color:$myColors[$i]'";
        }
    ?>


问:
total number of rows of a query
I have a very large query that is supposed to return only the top 10 results:

select top 10 ProductId from .....

The problem is that I also want the total number of results that match the criteria without that 'top 10', but in the same time it's considered unaceptable to return all rows (we are talking of roughly 100 thousand results.

Is there a way to get the total number of rows affected by the previous query, either in it or afterwords without running it again?

PS: please no temp tables of 100 000 rows :))

答:
I suppose you could hack it with a union select

```<code>select top 10 ... from ... where ...
union
select count(*) from ... where ...
</code>```

For you to get away with this type of hack you will need to add fake columns to the count query so it returns the same amount of columns as the main query. For example:

```<code>select top 10 id, first_name from people
union
select count(*), '' as first_name from people
</code>```

I don't recommend using this solution. Using two separate queries is how it should be done

Title: total number of rows of a query

Body:
I suppose you could hack it with a union select

select top 10 ... from ... where ...
union
select count(*) from ... where ...

For you to get away with this type of hack you will need to add fake columns to the count query so it returns the same amount of columns as the main query. For example:

select top 10 id, first_name from people
union
select count(*), '' as first_name from people

I don't recommend using this solution. Using two separate queries is how it should be done