问:
Angular 5: Saving input value from component into service
I am trying to save an input value from a component into my data service, such as input with user name, and input with password, on click it does a post call form the service, but the actual input lives in a separate component where the data service is imported.

how can I bind the data from the input, to add it to a variable in the data service?

UPDATE: I managed to translate the data between DataService and my component. Below is the code.

UPDATE v2: I am now getting a new error "Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response." trying to resolve this.

UPDATE v3: I managed to get everything working, check for the answer below!

DataService:

```<code>import { HttpClient, HttpRequest } from '@angular/common/http';

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

@Injectable()
export class DataService {
    username:string = '';
    password:string = '';

    convioURL:string;
    loginMethod:string;

    constructor(private http: HttpClient) {}

    getData() {
        this.convioURL = 'https://testurl.com/';
        this.loginMethod = '?testMethod&user_name='+ this.username +'&password='+ this.password +'&response_format=json';
        const req = new HttpRequest('POST', this.convioURL + this.loginMethod, {
            reportProgress: true
        });

        return this.http.request(req);
    }
    usernameKey(value: string) {
        this.username + value;
    }
    passwordKey(value: string) {
        this.password + value;
    }
}
</code>```

Component:

```<code>import { Component, OnInit } from '@angular/core';
import { HttpEvent, HttpEventType } from '@angular/common/http';
import { DataService } from '../data.service';
import * as $ from 'jquery';

@Component({
  selector: 'app-step-01',
  templateUrl: './step-01.component.html',
  styleUrls: ['./step-01.component.scss']
})
export class Step01Component implements OnInit {

    data: any;
    usernameInput: any;
    passwordInput: any;
    constructor(private dataService: DataService) {
    }

    ngOnInit() {
    }

    usernameKey(event: any) {
       this.dataService.username = event.target.value;
    }
    passwordKey(event: any) {
       this.dataService.password = event.target.value;
    }

    private getLoggedIn() {
        this.dataService.getData().subscribe((event: HttpEvent<any>) => {
            switch (event.type) {
                case HttpEventType.Sent:
                    console.log('Request sent!');
                break;
                case HttpEventType.ResponseHeader:
                    console.log('Response header received!');
                break;
                case HttpEventType.DownloadProgress:
                    const kbLoaded = Math.round(event.loaded / 1024);
                    console.log(`Download in progress! ${kbLoaded}Kb loaded`);
                break;
                case HttpEventType.Response:
                    console.log(' Done!', event.body);
                    this.data = event.body;
                    console.log(this.data);
          }
        });
    }

}
</code>```

This is my jQuery code that WORKS perfectly fine, but I am trying to stay away from using jQuery on this app, I want to be able to write this the angular5/typescript way. Hope this helps everyone understand what I am trying to do.

```<code>$("#ssoForm").submit(function(e) {
            e.preventDefault();
            var username = $('#username').val();
            var password = $('#password').val();

            var apiURL = 'http://testurl.com/?';
            var loginMethod = 'testMethod&user_name='+ username +'&password='+ password +'&response_format=json';

            $.post(apiURL + loginMethod,
                function(data) {
                    if (data) {
                        var json = $.parseJSON(data)
                        console.log(json);

                        var consID = json.loginResponse.cons_id;

                        var ssoUser = 'fakeusername';
                        var ssoPassword = 'fakepassword';

                        var ssoMethod = 'fakeSSOMethod&response_format=json&login_name='+ ssoUser +'&login_password='+ ssoPassword + '&cons_id='+ consID;

                        $.post(apiURL + ssoMethod, function(ssoData) {
                            var res = $.parseJSON(ssoData);
                            console.log(res);
                        });
                    } else {
                        console.log('No Data!');
                    }
            });
        });
</code>```

Component Template:

```<code><form id="ssoForm">
    <table>
        <tr>
            <td>User Name:</td>
            <td><input id="username" name=user_name type=text size=15 maxlength="100" #box (keyup)="usernameKey($event)"></td>
        </tr>
            <tr>
            <td>Password:</td>
            <td><input id="password" name=password type=password size=15 maxlength="100" #box2 (keyup)="passwordKey($event)"></td>
        </tr>
        <tr>
            <td>Remember Me:</td>
            <td><input name=remember_me type=checkbox></td>
        </tr>
    </table>
    <input (click)="getLoggedIn()" type="submit"/>
</form>
</code>```

答:
I fixed my latest problem by setting up a new function in the data service which is then called in the component I am using.

In the DataService added the following:

```<code>logMeIn() {
    this.convioURL = 'https://www.testurl.com/';
    this.loginMethod = '?testMethod&user_name='+ this.username +'&password='+ this.password +'&response_format=json';
    this.http.post(this.convioURL + this.loginMethod, null)
      .subscribe(res => {
            this.loginRes = res;
            console.log(this.loginRes);
        }, (err) => {
          console.log(err);
        }
      );
 }
</code>```

Then called on it on click in my component template.

Hope this helps others in my situation!

Body:
I am trying to save an input value from a component into my data service, such as input with user name, and input with password, on click it does a post call form the service, but the actual input lives in a separate component where the data service is imported.

how can I bind the data from the input, to add it to a variable in the data service?

UPDATE: I managed to translate the data between DataService and my component. Below is the code.

UPDATE v2: I am now getting a new error "Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response." trying to resolve this.

UPDATE v3: I managed to get everything working, check for the answer below!

DataService:

import { HttpClient, HttpRequest } from '@angular/common/http';

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

@Injectable()
export class DataService {
    username:string = '';
    password:string = '';

    convioURL:string;
    loginMethod:string;

    constructor(private http: HttpClient) {}

    getData() {
        this.convioURL = 'https://testurl.com/';
        this.loginMethod = '?testMethod&user_name='+ this.username +'&password='+ this.password +'&response_format=json';
        const req = new HttpRequest('POST', this.convioURL + this.loginMethod, {
            reportProgress: true
        });

        return this.http.request(req);
    }
    usernameKey(value: string) {
        this.username + value;
    }
    passwordKey(value: string) {
        this.password + value;
    }
}

Component:

import { Component, OnInit } from '@angular/core';
import { HttpEvent, HttpEventType } from '@angular/common/http';
import { DataService } from '../data.service';
import * as $ from 'jquery';

@Component({
  selector: 'app-step-01',
  templateUrl: './step-01.component.html',
  styleUrls: ['./step-01.component.scss']
})
export class Step01Component implements OnInit {

    data: any;
    usernameInput: any;
    passwordInput: any;
    constructor(private dataService: DataService) {
    }

    ngOnInit() {
    }

    usernameKey(event: any) {
       this.dataService.username = event.target.value;
    }
    passwordKey(event: any) {
       this.dataService.password = event.target.value;
    }

    private getLoggedIn() {
        this.dataService.getData().subscribe((event: HttpEvent<any>) => {
            switch (event.type) {
                case HttpEventType.Sent:
                    console.log('Request sent!');
                break;
                case HttpEventType.ResponseHeader:
                    console.log('Response header received!');
                break;
                case HttpEventType.DownloadProgress:
                    const kbLoaded = Math.round(event.loaded / 1024);
                    console.log(`Download in progress! ${kbLoaded}Kb loaded`);
                break;
                case HttpEventType.Response:
                    console.log(' Done!', event.body);
                    this.data = event.body;
                    console.log(this.data);
          }
        });
    }

}

This is my jQuery code that WORKS perfectly fine, but I am trying to stay away from using jQuery on this app, I want to be able to write this the angular5/typescript way. Hope this helps everyone understand what I am trying to do.

$("#ssoForm").submit(function(e) {
            e.preventDefault();
            var username = $('#username').val();
            var password = $('#password').val();

            var apiURL = 'http://testurl.com/?';
            var loginMethod = 'testMethod&user_name='+ username +'&password='+ password +'&response_format=json';

            $.post(apiURL + loginMethod,
                function(data) {
                    if (data) {
                        var json = $.parseJSON(data)
                        console.log(json);

                        var consID = json.loginResponse.cons_id;

                        var ssoUser = 'fakeusername';
                        var ssoPassword = 'fakepassword';

                        var ssoMethod = 'fakeSSOMethod&response_format=json&login_name='+ ssoUser +'&login_password='+ ssoPassword + '&cons_id='+ consID;

                        $.post(apiURL + ssoMethod, function(ssoData) {
                            var res = $.parseJSON(ssoData);
                            console.log(res);
                        });
                    } else {
                        console.log('No Data!');
                    }
            });
        });

Component Template:

<form id="ssoForm">

            User Name:
            <input id="username" name=user_name type=text size=15 maxlength="100" #box (keyup)="usernameKey($event)">

            Password:
            <input id="password" name=password type=password size=15 maxlength="100" #box2 (keyup)="passwordKey($event)">

            Remember Me:
            <input name=remember_me type=checkbox>

    <input (click)="getLoggedIn()" type="submit"/>
</form>

Body:
I fixed my latest problem by setting up a new function in the data service which is then called in the component I am using.

In the DataService added the following:

logMeIn() {
    this.convioURL = 'https://www.testurl.com/';
    this.loginMethod = '?testMethod&user_name='+ this.username +'&password='+ this.password +'&response_format=json';
    this.http.post(this.convioURL + this.loginMethod, null)
      .subscribe(res => {
            this.loginRes = res;
            console.log(this.loginRes);
        }, (err) => {
          console.log(err);
        }
      );
 }

Then called on it on click in my component template.

Hope this helps others in my situation!


来源: stackexchange

问:
PHP get_defined_vars() doesn't print superglobals inside function
I'm working through debugging some legacy code, and want to use a pre-built function that is essentially a wrapper for get_defined_vars().

Running this code directly in the calling file prints an array of variables as expected:

```<code>print_r(get_defined_vars());
</code>```

However, wrapping this in a simplified version of my function prints an empty array:

```<code>function debugAllVars() {
    print_r(get_defined_vars());
}
debugAllVars();
</code>```

Regardless of the scope, I would have expected "superglobal" variables such as $_POST to be present in the output.

Why is the output completely empty?

答:
get_defined_vars() prints all variables in the "symbol table" of the scope where it is called. When you try to wrap it as debugAllVars, you introduce a new scope, which has a new symbol table.

For a standalone function like this, the symbol table consists of:

the function's parameters

any global variables imported into the current scope using the global keyword

any static variables declared in the current scope with the static keyword (even if not assigned a value)

any variables implicitly declared by assigning a value to them

any variables implicitly declared by taking a reference to them (e.g. $foo = &$bar would implicitly declare $bar if not already defined; $foo = $bar would not)

Notably, this list does not include the superglobals, such as $_GET, $_POST, and $GLOBALS. If you run get_defined_vars() in global scope (i.e. outside any function), you will see that these are present in the symbol table there, which is also what the magic variable $GLOBALS points to. So, why are they not present in every scope, and how can we use them if they're not?

For this, we need to dig into the internals of the implementation, where these variables are referred to as "auto-globals" rather than "superglobals".

The answer to why is performance: the naive implementation of an "auto-global" would be one that acted as though every function automatically had a line at the top reading global $_GET, $_POST, ...;. However, this would mean copying all those variables into the symbol table before every function was run, even if they weren't used.

So instead, these variables are special-cased in the compiler, while converting your PHP code into the internal "opcodes" used by the VM which executes the code.

Using a source code browser, we can see how this works.

The key function is zend_is_auto_global in zend_compile.c (taken from current master, effectively PHP 7.2):

```<code>zend_bool zend_is_auto_global(zend_string *name) /* {{{ */
{
    zend_auto_global *auto_global;

    if ((auto_global = zend_hash_find_ptr(CG(auto_globals), name)) != NULL) {
        if (auto_global->armed) {
            auto_global->armed = auto_global->auto_global_callback(auto_global->name);
        }
        return 1;
    }
    return 0;
}
</code>```

Here, name is the name of a variable, and CG means "compiler globals", so the main job of this function is to say "if the variable name given is in a compiler-global hash called auto_globals, return 1". The additional call to auto_global_callback allows the variable to be "lazy loaded", and only populated when it is first referenced.

The main usage of that function appears to be this conditional, in zend_compile_simple_var_no_cv:

```<code>if (name_node.op_type == IS_CONST &&
    zend_is_auto_global(Z_STR(name_node.u.constant))) {

    opline->extended_value = ZEND_FETCH_GLOBAL;
} else {
    opline->extended_value = ZEND_FETCH_LOCAL;
}
</code>```

In other words, if the variable name you referenced is in the list of superglobals, the compiler switches the opcode into a different mode, so that when it is executed, it looks up the variable globally rather than locally.

ContentLicense: CC BY-SA 3.0

Body:
I'm working through debugging some legacy code, and want to use a pre-built function that is essentially a wrapper for get_defined_vars().

Running this code directly in the calling file prints an array of variables as expected:

print_r(get_defined_vars());

However, wrapping this in a simplified version of my function prints an empty array:

function debugAllVars() {
    print_r(get_defined_vars());
}
debugAllVars();

Regardless of the scope, I would have expected "superglobal" variables such as $_POST to be present in the output.

Why is the output completely empty?

Body:
get_defined_vars() prints all variables in the "symbol table" of the scope where it is called. When you try to wrap it as debugAllVars, you introduce a new scope, which has a new symbol table.

For a standalone function like this, the symbol table consists of:

the function's parameters

any global variables imported into the current scope using the global keyword

any static variables declared in the current scope with the static keyword (even if not assigned a value)

any variables implicitly declared by assigning a value to them

any variables implicitly declared by taking a reference to them (e.g. $foo = &$bar would implicitly declare $bar if not already defined; $foo = $bar would not)

Notably, this list does not include the superglobals, such as $_GET, $_POST, and $GLOBALS. If you run get_defined_vars() in global scope (i.e. outside any function), you will see that these are present in the symbol table there, which is also what the magic variable $GLOBALS points to. So, why are they not present in every scope, and how can we use them if they're not?

For this, we need to dig into the internals of the implementation, where these variables are referred to as "auto-globals" rather than "superglobals".

The answer to why is performance: the naive implementation of an "auto-global" would be one that acted as though every function automatically had a line at the top reading global $_GET, $_POST, ...;. However, this would mean copying all those variables into the symbol table before every function was run, even if they weren't used.

So instead, these variables are special-cased in the compiler, while converting your PHP code into the internal "opcodes" used by the VM which executes the code.

Using a source code browser, we can see how this works.

The key function is zend_is_auto_global in zend_compile.c (taken from current master, effectively PHP 7.2):

zend_bool zend_is_auto_global(zend_string *name) /* {{{ */
{
    zend_auto_global *auto_global;

    if ((auto_global = zend_hash_find_ptr(CG(auto_globals), name)) != NULL) {
        if (auto_global->armed) {
            auto_global->armed = auto_global->auto_global_callback(auto_global->name);
        }
        return 1;
    }
    return 0;
}

Here, name is the name of a variable, and CG means "compiler globals", so the main job of this function is to say "if the variable name given is in a compiler-global hash called auto_globals, return 1". The additional call to auto_global_callback allows the variable to be "lazy loaded", and only populated when it is first referenced.

The main usage of that function appears to be this conditional, in zend_compile_simple_var_no_cv:

if (name_node.op_type == IS_CONST &&
    zend_is_auto_global(Z_STR(name_node.u.constant))) {

    opline->extended_value = ZEND_FETCH_GLOBAL;
} else {
    opline->extended_value = ZEND_FETCH_LOCAL;
}

In other words, if the variable name you referenced is in the list of superglobals, the compiler switches the opcode into a different mode, so that when it is executed, it looks up the variable globally rather than locally.


问:
Multiple criteria lookup in R
I have data like this:

```<code>ID        1a      2a      3a      1b      2b      3b      Name      Team
cb128c   James   John    Bill    Jeremy   Ed     Simon    Simon     Wolves
cb128c   John    James   Randy   Simon    David  Ben      John      Tigers
ko351u   Adam    Alex    Jacob   Bob      Oscar  David    Oscar     Sparrows
ko351u   Adam    Matt    Sam     Fred     Frank  Harry    Adam      Wildcats
</code>```

And I want to add columns indicating teams A and B by matching the row ID of that row in the ID column, and by matching one of the names in one of the "a" columns of that row in the "Name" column (for Team A), and doing the same for Team B using one of the names in one of the "b" columns of that row:

```<code>ID        1a      2a      3a      1b      2b      3b      Name      Team     Team A    Team B
cb128c   James   John    Bill    Jeremy   Ed     Simon    Simon     Wolves   Tigers    Wolves
cb128c   John    James   Randy   Simon    David  Ben      John      Tigers   Tigers    Wolves
ko351u   Adam    Alex    Jacob   Bob      Oscar  David    Oscar     Sparrows Wildcats  Sparrows
ko351u   Adam    Matt    Sam     Fred     Frank  Harry    Adam      Wildcats Wildcats  Sparrows
</code>```

In row 1, we know Team A is Tigers because we match the ID of row 1, cb128c, in the ID column, and one of the "a" names of row 1 (either James, John or Bill) in the Name column. In this case, Row 2 has that ID, cb128c, and has "John" in the Name column. The Team in row 2 is "Tigers." Therefore, Row 1's Team A is Tigers. Team B is the Wolves because we match row 1's ID, still cb128c, and one of the "b" names in row 1 (either Jeremy, Ed or Simon) in the Name column. In this case, row 1 itself has the data we're looking for since one of the "b" names appears in the "Name" column of that row (Simon). The "Team" listed in each row will always either be the Team A or the Team B for that row.

Further down, we know Team A for row 3 is Wildcats because we match row 3's ID, ko351u and one of row 3's "a" names (either Adam, Alex or Jacob) in the "Name" column. Row 4 has that ID and "Adam" in the Name column. So the Team in Row 4 is Team A for Row 3.

Also notice that David switched teams in Row 3. In Row 2, David was on Simon's team, which we know is the Wolves (as explained above), but when we match Row 3's ID and one of Row 3's "b" names (Bob, Oscar or David), we get the Sparrows (like Row 1, one of the "b" names appears in the name column of that same row, so the Team B is the Team listed in that row).

How can I get this done in R?

答:
```<code>df = read.table(text = "ID        1a      2a      3a      1b      2b      3b      Name      Team
cb128c   James   John    Bill    Jeremy   Ed     Simon    Simon     Wolves
cb128c   John    James   Randy   Simon    David  Ben      John      Tigers
ko351u   Adam    Alex    Jacob   Bob      Oscar  David    Oscar     Sparrows
ko351u   Adam    Matt    Sam     Fred     Frank  Harry    Adam      Wildcats", header = T)

# convert to character
df[] = lapply(df, as.character)
library(tidyr)
library(dplyr)
</code>```

The following code 1. gathers to long format, 2. creates "Team_A" and "Team_B" out of the a or b suffix, 3. matches names to fill in the A/B Team Name, 4. removes missing values (no match), 5. gets rid of unnecessary columns, 6. converts back to wide format, 7. joins the A and B teams to the original data.

I'd encourage you to step through the code line by line to understand what's going on. I'll leave reordering the columns to you.

```<code>result = gather(df, key = "key", value = "value", starts_with("X")) %>%
    mutate(ab = paste0("Team_", toupper(substr(key, start = nchar(key), stop = nchar(key)))),
           team = ifelse(Name == value, Team, NA)) %>%
    filter(!is.na(team)) %>%
    select(ID, ab, team) %>%
    spread(key = ab, value = team) %>%
    right_join(df)

result
#       ID   Team_A   Team_B   X1a   X2a   X3a    X1b   X2b   X3b  Name     Team
# 1 cb128c   Tigers   Wolves James  John  Bill Jeremy    Ed Simon Simon   Wolves
# 2 cb128c   Tigers   Wolves  John James Randy  Simon David   Ben  John   Tigers
# 3 ko351u Wildcats Sparrows  Adam  Alex Jacob    Bob Oscar David Oscar Sparrows
# 4 ko351u Wildcats Sparrows  Adam  Matt   Sam   Fred Frank Harry  Adam Wildcats
</code>```

Title: Multiple criteria lookup in R

Body:
I have data like this:

ID        1a      2a      3a      1b      2b      3b      Name      Team
cb128c   James   John    Bill    Jeremy   Ed     Simon    Simon     Wolves
cb128c   John    James   Randy   Simon    David  Ben      John      Tigers
ko351u   Adam    Alex    Jacob   Bob      Oscar  David    Oscar     Sparrows
ko351u   Adam    Matt    Sam     Fred     Frank  Harry    Adam      Wildcats

And I want to add columns indicating teams A and B by matching the row ID of that row in the ID column, and by matching one of the names in one of the "a" columns of that row in the "Name" column (for Team A), and doing the same for Team B using one of the names in one of the "b" columns of that row:

ID        1a      2a      3a      1b      2b      3b      Name      Team     Team A    Team B
cb128c   James   John    Bill    Jeremy   Ed     Simon    Simon     Wolves   Tigers    Wolves
cb128c   John    James   Randy   Simon    David  Ben      John      Tigers   Tigers    Wolves
ko351u   Adam    Alex    Jacob   Bob      Oscar  David    Oscar     Sparrows Wildcats  Sparrows
ko351u   Adam    Matt    Sam     Fred     Frank  Harry    Adam      Wildcats Wildcats  Sparrows

In row 1, we know Team A is Tigers because we match the ID of row 1, cb128c, in the ID column, and one of the "a" names of row 1 (either James, John or Bill) in the Name column. In this case, Row 2 has that ID, cb128c, and has "John" in the Name column. The Team in row 2 is "Tigers." Therefore, Row 1's Team A is Tigers. Team B is the Wolves because we match row 1's ID, still cb128c, and one of the "b" names in row 1 (either Jeremy, Ed or Simon) in the Name column. In this case, row 1 itself has the data we're looking for since one of the "b" names appears in the "Name" column of that row (Simon). The "Team" listed in each row will always either be the Team A or the Team B for that row.

Further down, we know Team A for row 3 is Wildcats because we match row 3's ID, ko351u and one of row 3's "a" names (either Adam, Alex or Jacob) in the "Name" column. Row 4 has that ID and "Adam" in the Name column. So the Team in Row 4 is Team A for Row 3.

Also notice that David switched teams in Row 3. In Row 2, David was on Simon's team, which we know is the Wolves (as explained above), but when we match Row 3's ID and one of Row 3's "b" names (Bob, Oscar or David), we get the Sparrows (like Row 1, one of the "b" names appears in the name column of that same row, so the Team B is the Team listed in that row).

How can I get this done in R?

Body:
df = read.table(text = "ID        1a      2a      3a      1b      2b      3b      Name      Team
cb128c   James   John    Bill    Jeremy   Ed     Simon    Simon     Wolves
cb128c   John    James   Randy   Simon    David  Ben      John      Tigers
ko351u   Adam    Alex    Jacob   Bob      Oscar  David    Oscar     Sparrows
ko351u   Adam    Matt    Sam     Fred     Frank  Harry    Adam      Wildcats", header = T)

# convert to character
df[] = lapply(df, as.character)
library(tidyr)
library(dplyr)

The following code 1. gathers to long format, 2. creates "Team_A" and "Team_B" out of the a or b suffix, 3. matches names to fill in the A/B Team Name, 4. removes missing values (no match), 5. gets rid of unnecessary columns, 6. converts back to wide format, 7. joins the A and B teams to the original data.

I'd encourage you to step through the code line by line to understand what's going on. I'll leave reordering the columns to you.

result = gather(df, key = "key", value = "value", starts_with("X")) %>%
    mutate(ab = paste0("Team_", toupper(substr(key, start = nchar(key), stop = nchar(key)))),
           team = ifelse(Name == value, Team, NA)) %>%
    filter(!is.na(team)) %>%
    select(ID, ab, team) %>%
    spread(key = ab, value = team) %>%
    right_join(df)

result
#       ID   Team_A   Team_B   X1a   X2a   X3a    X1b   X2b   X3b  Name     Team
# 1 cb128c   Tigers   Wolves James  John  Bill Jeremy    Ed Simon Simon   Wolves
# 2 cb128c   Tigers   Wolves  John James Randy  Simon David   Ben  John   Tigers
# 3 ko351u Wildcats Sparrows  Adam  Alex Jacob    Bob Oscar David Oscar Sparrows
# 4 ko351u Wildcats Sparrows  Adam  Matt   Sam   Fred Frank Harry  Adam Wildcats


问:
How to use Matches() and Pattern correctley
I'm doing a assignment for school and need to build a Student class. The constructor will receive a String,"Student name". I need to verify that the given String from the user includes only letters from a-z, A-Z, and numbers 0-9.

From looking online this is what I found

```<code>boolean ans = true;
String str = ("Maor Rocky");
Pattern pattern = Pattern.compile("[A-Za-z0-9]\\w+");
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.group());

if (!str.matches("[a-zA-Z0-9//s+]"))
    ans = false;

System.out.println(ans);
</code>```

I know it's missing something but I didn't grasp the idea of pattern and matcher yet.

答:
You need something like that:</p>

```<code>public class Student {

    private String name;

    public Student(String name) throws IllegalArgumentException {
        if (!name.matches("[\\w]*")) {
            throw new IllegalArgumentException("name should contain only alphanumeric chars.");
        }
        this.name = name;
    }

    public String getName() {
       return name;
    }
}
</code>```

Body:
I'm doing a assignment for school and need to build a Student class. The constructor will receive a String,"Student name". I need to verify that the given String from the user includes only letters from a-z, A-Z, and numbers 0-9.

From looking online this is what I found

boolean ans = true;
String str = ("Maor Rocky");
Pattern pattern = Pattern.compile("[A-Za-z0-9]\\w+");
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.group());

if (!str.matches("[a-zA-Z0-9//s+]"))
    ans = false;

System.out.println(ans);

I know it's missing something but I didn't grasp the idea of pattern and matcher yet.

Body:
You need something like that:

public class Student {

    private String name;

    public Student(String name) throws IllegalArgumentException {
        if (!name.matches("[\\w]*")) {
            throw new IllegalArgumentException("name should contain only alphanumeric chars.");
        }
        this.name = name;
    }

    public String getName() {
       return name;
    }
}


问:
javascript style all words between special characters
I am looking to style some words in a string that contain special characters.
For instance If I have

"I want to style words in single quotes 'blue' and brackets [red]. There are multiple 'blue' and [red] words in a string"

I would like it to look like this without the special characters

"I want to style words in single quotes blue and brackets red..."

How can I replace the end of the single quote with  in the method below?

This is what I have so far.

```<code>highlightMessage(message) {
    var text = message.replace(/[\[']+/g, "<span class='red'>")
    var text = message.replace(/]\]']+/g, "</span")
    var text = message.replace(/'/g, "<span class='blue'>")
    //how can I replace the end of the single quote with </span>
    //the method above replaces it with <span class='blue'>

    return message;
}
</code>```

The other idea I have was to iterate through the string with .split() and check if the word ends with a single quote then replace that but I don't like that solution.

答:
You may perform a single replace operation to achieve what you need:

var s = "I want to style words in single quotes 'blue' and brackets [red]. There are multiple 'blue' and [red] words in a string";
var res = s.replace(/'([^']+)'|\[([^\][]+)]/g, "$1$2")
console.log(res);```

The pattern - '([^']+)'|\[([^\][]+)] - matches '...' and [...] substrings and captures their contents, and replaced with the span tags using those contents as the attribute and node value.

Pattern details

'([^']+)' - a single quote, then Group 1 (later referred to with $1) capturing 1+ chars other than ', and then a '

|  - or

\[([^\][]+)] - a [ char, then Group 2 (later referred to with $2) capturing 1+ chars other than [ and ], and then a ].

Since $n backreferences are always initialized with an empty string, there is no problem using $1$2 in the replacement: only one of them contains text during each replacement, the other is empty.

Body:
I am looking to style some words in a string that contain special characters.
For instance If I have

"I want to style words in single quotes 'blue' and brackets [red]. There are multiple 'blue' and [red] words in a string"

I would like it to look like this without the special characters

"I want to style words in single quotes blue and brackets red..."

How can I replace the end of the single quote with  in the method below?

This is what I have so far.

highlightMessage(message) {
    var text = message.replace(/[\[']+/g, "")
    var text = message.replace(/]\]']+/g, "</span")
    var text = message.replace(/'/g, "")
    //how can I replace the end of the single quote with
    //the method above replaces it with

    return message;
}

The other idea I have was to iterate through the string with .split() and check if the word ends with a single quote then replace that but I don't like that solution.

Body:
You may perform a single replace operation to achieve what you need:

var s = "I want to style words in single quotes 'blue' and brackets [red]. There are multiple 'blue' and [red] words in a string";
var res = s.replace(/'([^']+)'|\[([^\][]+)]/g, "<span class='$1$2'>$1$2</span>")
console.log(res);

The pattern - '([^']+)'|\[([^\][]+)] - matches '...' and [...] substrings and captures their contents, and replaced with the span tags using those contents as the attribute and node value.

Pattern details

'([^']+)' - a single quote, then Group 1 (later referred to with $1) capturing 1+ chars other than ', and then a '

|  - or

\[([^\][]+)] - a [ char, then Group 2 (later referred to with $2) capturing 1+ chars other than [ and ], and then a ].

Since $n backreferences are always initialized with an empty string, there is no problem using $1$2 in the replacement: only one of them contains text during each replacement, the other is empty.


问:
how to display uipickerview with Button programmatically in iphone
I'm doing application in that I added pickerview with button without using IB (Interface Builder).

Here I added pickerview and button programmatically in iphone.

But when I run this application in pickerview I added some names that was not showing.

It was showing only empty pickerview and when I click button the pickerview displayed in top of the view not in down.

How to add pickerview with button programmatically in iphone?

How to code this button with pickerview without using IB?

答:
Did you implement the datasource and delegate methods for UIPickerView.

Of course you can programmatically add pickerView and button, you just need to make a frame using CGRectMake and giving coordinates where you want to show your picker and button.

post some code of what you used to display data in picker

ContentLicense: CC BY-SA 2.5


问:
Handling external keyboard presses without showing keyboard on screen on iOS app
I have a private iOS app that I want to control using an external keyboard connected via Bluetooth. I don't want any UITextField or UITextView in my app, or at least I don't want the keyboard to show all the time. Is there a way for me listen to these keyboard events from the physical keyboard? thanks.

答:
UIKeyCommands

To listen keys from keyboard, you can override the keyCommands variable on your ViewController (It's an array so you can put many shortcuts):

```<code>override var keyCommands: [UIKeyCommand]? {
    return [
        UIKeyCommand(input: "Q",
                     modifierFlags: [],
                     action: #selector(self.close),
                     discoverabilityTitle: "Close app")
    ]
}

func close() {
    exit(0)
}
</code>```

Input is the key to use, for example CMD+Q (only put Q). Action is the selector to call and discoverabilityTitle is the title of the shortcut, for example "Close app". It will be displayed in iPad when the user holds the CMD key.

It only works with CMD keys and other specials keys:

```<code>UIKeyInputUpArrow
UIKeyInputDownArrow
UIKeyInputLeftArrow
UIKeyInputRightArrow
UIKeyInputEscape
</code>```

Body:
UIKeyCommands

To listen keys from keyboard, you can override the keyCommands variable on your ViewController (It's an array so you can put many shortcuts):

override var keyCommands: [UIKeyCommand]? {
    return [
        UIKeyCommand(input: "Q",
                     modifierFlags: [],
                     action: #selector(self.close),
                     discoverabilityTitle: "Close app")
    ]
}

func close() {
    exit(0)
}

Input is the key to use, for example CMD+Q (only put Q). Action is the selector to call and discoverabilityTitle is the title of the shortcut, for example "Close app". It will be displayed in iPad when the user holds the CMD key.

It only works with CMD keys and other specials keys:

UIKeyInputUpArrow
UIKeyInputDownArrow
UIKeyInputLeftArrow
UIKeyInputRightArrow
UIKeyInputEscape


问:
How to replace commas with semicolons except for commas in Quotes?
I have a csv file with commas used to separate values. I want to replace commas with semicolons via batch, but leave the commas that are inside quotations.
So for example:

```<code>012,ABC,"DE,FG",345
</code>```

must become:

```<code>012;ABC;"DE,FG";345
</code>```

How can I do that via Batch?

答:
This possible alternative appears to work with the single line example you've provided:

@Echo Off
If Not Exist "file.csv" Exit/B
(For /F "Delims=" %%A In ('FindStr "^" "file.csv"') Do (Set "$="
    For %%B In (%%A) Do Call Set "$=%%$%%;%%B"
    Call Echo %%$:~1%%))>"filenew.csv"
```

Body:
I have a csv file with commas used to separate values. I want to replace commas with semicolons via batch, but leave the commas that are inside quotations.
So for example:

012,ABC,"DE,FG",345

must become:

012;ABC;"DE,FG";345

How can I do that via Batch?


问:
How to get the difference between two DataFrames
How to get the difference between two DataFrames. For example, I have 2 DataFrames

```<code>previous_asks =  pd.DataFrame({'price':[1,2,3], 'amount':[10,20,30]})
current_asks = pd.DataFrame({'price':[1,2,3,4], 'amount':[11,20,30,40]})
</code>```

I would like to receive

```<code>price':[1, 4], 'amount':[11,40]
</code>```

答:
Using pandas:

```<code>a1 = list(range(10))
a2 = list(range(5, 8))

b1 = list('abcdefghij')
b2 = list('efy')

df1 =  pd.DataFrame({'price':a1, 'amount':b1})
df2 = pd.DataFrame({'price':a2, 'amount':b2})

dict_results = dict()
for col in df1:
    dict_results[col] = df1.loc[~ df1[col].isin(df2[col].values), col].values
    print('--', col, dict_results[col])
</code>```

Gives:

```<code>-- amount ['a' 'b' 'c' 'd' 'g' 'h' 'i' 'j']
-- price [0 1 2 3 4 8 9]
</code>```

Using python3:

```<code>set1 = set(a1)
set2 = set(a2)
print(set1 - set2)
</code>```

Gives:

```<code>{0, 1, 2, 3, 4, 8, 9}
</code>```

I would rather go with python3 here since I think it is much simpler/readable.
If you orignally have pandas dataframes I would convert those to set data
type, manipulate those and revert back to pd.Dataframe if necessary.

Also it is worth checking out the
unique()
method of a pd.Series.

Body:
How to get the difference between two DataFrames. For example, I have 2 DataFrames

previous_asks =  pd.DataFrame({'price':[1,2,3], 'amount':[10,20,30]})
current_asks = pd.DataFrame({'price':[1,2,3,4], 'amount':[11,20,30,40]})

I would like to receive

price':[1, 4], 'amount':[11,40]

Body:
Using pandas:

a1 = list(range(10))
a2 = list(range(5, 8))

b1 = list('abcdefghij')
b2 = list('efy')

df1 =  pd.DataFrame({'price':a1, 'amount':b1})
df2 = pd.DataFrame({'price':a2, 'amount':b2})

dict_results = dict()
for col in df1:
    dict_results[col] = df1.loc[~ df1[col].isin(df2[col].values), col].values
    print('--', col, dict_results[col])

Gives:

-- amount ['a' 'b' 'c' 'd' 'g' 'h' 'i' 'j']
-- price [0 1 2 3 4 8 9]

Using python3:

set1 = set(a1)
set2 = set(a2)
print(set1 - set2)

Gives:

{0, 1, 2, 3, 4, 8, 9}

I would rather go with python3 here since I think it is much simpler/readable.
If you orignally have pandas dataframes I would convert those to set data
type, manipulate those and revert back to pd.Dataframe if necessary.

Also it is worth checking out the
unique()
method of a pd.Series.


问:
@Component @Scope("singleton") public class BootStrapper implements ApplicationListener<ContextStartedEvent> {
I am trying to do a one time initialization of my webapp. I need a singleton for the ApplicationListener class, so I set the scope to Singleton, but it is creating multiple instances. This BootStrapper is not defined in any other xml config files.
I know that the default scope is singleton, but had to add @Scope("singleton") because it was not a singleton. Even with this annotation, it still creates multiple instances.
Here is my ApplicationListener.

```<code>@Component
@Scope("singleton")
public class BootStrapper implements ApplicationListener<ContextRefreshedEvent> {
</code>```

Am I missing anything?

答:
Try like this:</p>

```<code>@Configuration
public class TestService
{
  private Properties properties;

  @Bean
  @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
  public Properties getAppProperties()
  {
    try
    {
        if (properties == null)
        {
          properties = ServiceUtils.loadProperties();
        }
     return properties;
    }
    catch (Exception e)
    {
      LOGGER.logCaughtException("Exception Occured while loading App Properties.", e);
    }
  }
}
</code>```

Body:
I am trying to do a one time initialization of my webapp. I need a singleton for the ApplicationListener class, so I set the scope to Singleton, but it is creating multiple instances. This BootStrapper is not defined in any other xml config files.
I know that the default scope is singleton, but had to add @Scope("singleton") because it was not a singleton. Even with this annotation, it still creates multiple instances.
Here is my ApplicationListener.

@Component
@Scope("singleton")
public class BootStrapper implements ApplicationListener<ContextRefreshedEvent> {

Am I missing anything?

Body:
Try like this:

@Configuration
public class TestService
{
  private Properties properties;

  @Bean
  @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
  public Properties getAppProperties()
  {
    try
    {
        if (properties == null)
        {
          properties = ServiceUtils.loadProperties();
        }
     return properties;
    }
    catch (Exception e)
    {
      LOGGER.logCaughtException("Exception Occured while loading App Properties.", e);
    }
  }
}


问:
Kubernetes network utilization metrics
I'm running a Kubernetes cluster GKE on Google Compute Engine GCE.
Through Heapster I am able to get different network metrics such as sent or received bytes, or error rate.

However, in order to better understand my application (Pods) bottlenecks, it would be essential to understand how utilized is the Node's network. Is it possible to query Network Utilization, otherwise what metrics do indicate my network health?

答:
There is not a direct way on your side to monitor the VPC network but there are some tools that might help you to check that it is behaving as expected.

The only documented limit on VPC networks are the egress throughput caps which will depend  on the number of cores the nodes have.

You can see the graphs for “Networks Bytes” and “Network Packets” in your Google Cloud Console. They can be retrieve by going to:

Cloud Console -> Instance Groups ->  Managed_Intance_Group_Name

or

Cloud Console->  VM Instances -> Node_Name

Network graphs for the pools and the nodes can also be found in the Stackdriver Account

(https://app.google.stackdriver.com) -> Resources -> Container Engine -> Cluster Name

Analyzing those graphs might help you to determine if your traffic is being throttled.

To obtain additional visibility you could also use cAdvisor or other tools mentioned here

Title: Kubernetes network utilization metrics


问:
Can any one please suggest which sql query is better approach for large data set in mysql
I have to find the max id row for same group in a table and show the roe details.Using following two approach we can achieve it. But want know which will be good approach for large data. Or any other new approach that will take less time to execute?

Approach 1:

```<code>select a.* from tab1 a left join (SELECT max(id) as id,name from tab1
GROUP by name) as tab2 on a.id=tab2.id where a.id=tab2.id
</code>```

Approach 2:

```<code>SELECT id,name from tab1 where id in(SELECT MAX(id) FROM tab1 GROUP by name)
</code>```

答:
Taken from the manual (13.2.10.11 Rewriting Subqueries as Joins):

A LEFT JOIN can be faster than a subquery because
the server might be able to optimize it better.

So subqueries can be slower than LEFT [OUTER] JOINS, but in my opinion their strength is slightly higher readability. But since there is one LEFT JOIN and a subquery in the first approach, the second approach might be faster at large scale query.

ContentLicense: CC BY-SA 4.0

Body:
I have to find the max id row for same group in a table and show the roe details.Using following two approach we can achieve it. But want know which will be good approach for large data. Or any other new approach that will take less time to execute?

Approach 1:

select a.* from tab1 a left join (SELECT max(id) as id,name from tab1
GROUP by name) as tab2 on a.id=tab2.id where a.id=tab2.id

Approach 2:

SELECT id,name from tab1 where id in(SELECT MAX(id) FROM tab1 GROUP by name)


问:
Datatables change language dynamically
I'm trying to change with jQuery language of a table with datatables. I'm trying to push a button to change the language of the table.</p>

```<code>$('#prueba').live('click', function () {
var espanol = {
     "sProcessing": "Procesando...",
     "sLengthMenu": "Mostrar _MENU_ registros",
     "sZeroRecords": "No se encontraron resultados",
     "sInfo": "Mostrando desde _START_ hasta _END_ de _TOTAL_ registros",
     "sInfoEmpty": "No existen registros",
     "sInfoFiltered": "(filtrado de un total de _MAX_ líneas)",
     "sInfoPostFix": "",
     "sSearch": "Buscar:",
     "sUrl": "",
"oPaginate": {
"sFirst":    "Primero",
"sPrevious": "Anterior",
"sNext":     "Siguiente",
"sLast":     "Último"
}
};
tablacliente.fnSettings().oLanguage= espanol;
tablacliente.fnDraw();
})
</code>```

答:
```<code><?php
$countries = array (
    "tr-TR"=>"//cdn.datatables.net/plug-ins/1.10.16/i18n/Turkish.json",
    "de-DE" =>"//cdn.datatables.net/plug-ins/1.10.16/i18n/German.json",
    "es-ES"=>"//cdn.datatables.net/plug-ins/1.10.16/i18n/Spanish.json"
);
?>
<script>
    var locale='<?php echo $countries[locale_get_default()];?>';
    $(document).ready(function () {
        $('#page-params').dataTable({
            responsive: true,
            "oLanguage": {
                "sUrl": locale
            }
        });
    });
</script>
</code>```

Title: Datatables change language dynamically

Body:
I'm trying to change with jQuery language of a table with datatables. I'm trying to push a button to change the language of the table.

$('#prueba').live('click', function () {
var espanol = {
     "sProcessing": "Procesando...",
     "sLengthMenu": "Mostrar _MENU_ registros",
     "sZeroRecords": "No se encontraron resultados",
     "sInfo": "Mostrando desde _START_ hasta _END_ de _TOTAL_ registros",
     "sInfoEmpty": "No existen registros",
     "sInfoFiltered": "(filtrado de un total de _MAX_ líneas)",
     "sInfoPostFix": "",
     "sSearch": "Buscar:",
     "sUrl": "",
"oPaginate": {
"sFirst":    "Primero",
"sPrevious": "Anterior",
"sNext":     "Siguiente",
"sLast":     "Último"
}
};
tablacliente.fnSettings().oLanguage= espanol;
tablacliente.fnDraw();
})


问:
ActiveMQ move expired messages to different queue than failed messages
I have a use case where there may be a build up of messages on an ActiveMQ  queue. The goal is to have higher priority, newer messages executed first. High priority messages older than some time should be executed at a lower priority.

From what I have read, the JMS selector does not support a concept of NOW(); (i.e.)

```<code>JMSTimestamp < NOW() - 30 MINUTES
</code>```

I read a suggestion to use expire time. From my understanding of the redelivery policy, expired messages go to the same queue as failed messages. Is there a way to have expired messages move to a different queue (queue.A) then failed messages (DLQ)?

Thanks.

答:
In ActiveMQ 5.x there isn't a way that I can think to do this using the standard set of broker configuration options.  That said you could always write your own BrokerPlugin that does something along these lines by intercepting expired messages and sending them off someplace else.

If you are using ActiveMQ Artemis then you can do this quite easily by configuring it to do what you want, the Failed Delivery and Expiry address configurations allow you do handle this scenario.

Body:
I have a use case where there may be a build up of messages on an ActiveMQ  queue. The goal is to have higher priority, newer messages executed first. High priority messages older than some time should be executed at a lower priority.

From what I have read, the JMS selector does not support a concept of NOW(); (i.e.)

JMSTimestamp < NOW() - 30 MINUTES

I read a suggestion to use expire time. From my understanding of the redelivery policy, expired messages go to the same queue as failed messages. Is there a way to have expired messages move to a different queue (queue.A) then failed messages (DLQ)?

Thanks.


问:
Inserting and querying data from table with foreign key in SQLite
I wanted to create two related tables. My query that is creating tables looks like this:

```<code>static final String SQL_CREATE_TABLE_LISTS =
"CREATE TABLE Lists(Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT);";
static final String SQL_CREATE_TABLE_ITEMS =
"CREATE TABLE Items(IdList INTEGER, ItemName TEXT, FOREIGN KEY(IdList) REFERENCES Lists(Id));";
</code>```

I want now insert and select some data from table Items, but I do not know how the query should looks like. Lets say I have one record in table Lists: id=1 and name=element1. And now I want to add 3 records to table Items, so IdList will be 1, and name will be item1, item2 and item3. How the inserting query will be like? And then, if I want to take for ex. all Names from table Items that its IdList is 1, how the select query will be like? Thanks.

答:
A FOREIGN KEY is a Constraint (Rule that MUST be followed), it does not define a relationshop/link for extracting data. In other words it is saying if the rule is not met then a row cannot be inserted. It is not saying every time you access either of the tables that they are automatically linked.

When inserting you you would insert the Lists first, you would then insert the Items using(checking) the available Lists. You cannot insert into/across multiple tables directly.

You need to use JOIN when querying the data as FOREIGN KEY is just a rule (constraint) that is checked when inserting a row.

So you would do something along the line of:-

SELECT Lists.Id, Lists.Name, Items.ItemName FROM Lists JOIN Items ON Lists.Id = Items.IdList

Body:
I wanted to create two related tables. My query that is creating tables looks like this:

static final String SQL_CREATE_TABLE_LISTS =
"CREATE TABLE Lists(Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT);";
static final String SQL_CREATE_TABLE_ITEMS =
"CREATE TABLE Items(IdList INTEGER, ItemName TEXT, FOREIGN KEY(IdList) REFERENCES Lists(Id));";

I want now insert and select some data from table Items, but I do not know how the query should looks like. Lets say I have one record in table Lists: id=1 and name=element1. And now I want to add 3 records to table Items, so IdList will be 1, and name will be item1, item2 and item3. How the inserting query will be like? And then, if I want to take for ex. all Names from table Items that its IdList is 1, how the select query will be like? Thanks.


问:
How to import big CSV file into Sqlite3 in python?

I'm having a really big CSV file that I need to load into a table in sqlite3. I can't load whole CSV content as a variable into RAM because data is so big, that event with defining types for each column it cannot fit into 64 GB of RAM.

I've tried to use numpy and pandas to load and convert data, but still jumping way above RAM limit.

I would like to somehow read CSV 1 row at a time (or in smaller batches) and progressively save them into the database to keep RAM usage low. Would be perfect if it could be done using more than one CPU core.

答:
I've found a solution digging myself and combining answers from other Stack Overflow questions. Code should be like this:

```<code>import sqlite3
import pandas as pd

def add_to_db(row, con):
    # Function that make insert to your DB, make your own.

def process_chunk(chunk):
    # Handles one chunk of rows from pandas reader.
    con = sqlite3.connect("favorita.db")
    for row in chunk:
        add_to_db(row, con)
    con.commit()

for chunk in pd.read_csv('data.csv', chunksize=100000):
    # Adjust chunksize to your needs and RAM size.
    process_chunk(chunk.values)
</code>```

This could surely be further adjusted to use multi-threading, but I couldn't do it due to deadlocks in database when doing inserts in parallel. But if you have time, this is a solid solution.

Body:
I've found a solution digging myself and combining answers from other Stack Overflow questions. Code should be like this:

import sqlite3
import pandas as pd

def add_to_db(row, con):
    # Function that make insert to your DB, make your own.

def process_chunk(chunk):
    # Handles one chunk of rows from pandas reader.
    con = sqlite3.connect("favorita.db")
    for row in chunk:
        add_to_db(row, con)
    con.commit()

for chunk in pd.read_csv('data.csv', chunksize=100000):
    # Adjust chunksize to your needs and RAM size.
    process_chunk(chunk.values)

This could surely be further adjusted to use multi-threading, but I couldn't do it due to deadlocks in database when doing inserts in parallel. But if you have time, this is a solid solution.


问:
Formula for coordinates in a linearly increasing interval
If I have a list of pairs of separated values, how can I calculate which index a given number falls into (that is, the input is in the interval)? For example:

```<code>f( [[0, 2], [3, 6], [7, 10]], 4 ) == 1
</code>```

Edit - To clarify, I know the naive algorithm is quite obvious. I feel like there's a constant time (or at least better than linear) solution.

答:
Here is an example in Python</p>

```<code>def f(intervals, value):
    for i in intervals:
        if (value >= i[0]) and (value <= i[0]):
            return True
    return False
</code>```

Body:
If I have a list of pairs of separated values, how can I calculate which index a given number falls into (that is, the input is in the interval)? For example:

f( [[0, 2], [3, 6], [7, 10]], 4 ) == 1

Edit - To clarify, I know the naive algorithm is quite obvious. I feel like there's a constant time (or at least better than linear) solution.

Body:
Here is an example in Python

def f(intervals, value):
    for i in intervals:
        if (value >= i[0]) and (value <= i[0]):
            return True
    return False


问:
Select box `appearance` on Mac /safari or chrome
How can I make the select box look the same on all web browsers and devices but I can't find the right way to do that, so far the biggest problem is on IE 10 and Microsoft edge, it seems the appearance is not working!

can anyone help with this issue? thank you.

.form {
  width: 300px;
  padding: 20px;
  background-color: #f5f5f5;
}

.textfield,
.select {
  margin-top: 5px;
  padding: 5px;
  width: 100%;
}

.select {
  background: #fff;
  border-radius: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form">
  <div>
    <label for="text">
      <nobr>Text field</nobr>
    </label>
    <br />
    <input name="text" tabindex="1" class="textfield" />
  </div>
  <br />
  <div>
    <br />
    <select name="select" tabindex="2" class="select">
      <option value="">-- Please Select --</option>
      <option value="option 1">Option 1</option>
      <option value="option 2">Option 2</option>
    </select>
  </div>
</div></code>```

答:
To make the textbox and select box have exactly the same appearance style-wise, pick the style you want (i.e. something like border: 1px solid #666666 to mimic the <input> element) and apply it to both your .textfield and .select classes together.

You can use JavaScript to only apply that style when the user is on a Mac, if you want. (See this answer.)

.form {
  width: 300px;
  padding: 20px;
  background-color: #f5f5f5;
}

.textfield,
.select {
  margin-top: 5px;
  padding: 5px;
  width: 100%;
  border: 1px solid #666666;
}

.select {
  background: #fff;
  border-radius: 0;
}

.asterisk {
  color: #FF0004;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form">
  <div>
    <label for="text">
      <nobr>Text field</nobr>
    </label>
    <br />
    <input name="text" tabindex="1" class="textfield" />
  </div>
  <br />
  <div>
    <label for="select">
      <nobr>Select<span class="asterisk">*</span></nobr>
    </label>
    <br />
    <select name="select" tabindex="2" class="select">
      <option value="">-- Please Select --</option>
      <option value="option 1">Option 1</option>
      <option value="option 2">Option 2</option>
    </select>
  </div>
</div></code>```

Body:
How can I make the select box look the same on all web browsers and devices but I can't find the right way to do that, so far the biggest problem is on IE 10 and Microsoft edge, it seems the appearance is not working!

can anyone help with this issue? thank you.

.form {
  width: 300px;
  padding: 20px;
  background-color: #f5f5f5;
}

.textfield,
.select {
  margin-top: 5px;
  padding: 5px;
  width: 100%;
}

.select {
  background: #fff;
  border-radius: 0;
}

      <nobr>Text field</nobr>

    <input name="text" tabindex="1" class="textfield" />

    <select name="select" tabindex="2" class="select">
      <option value="">-- Please Select --</option>
      <option value="option 1">Option 1</option>
      <option value="option 2">Option 2</option>
    </select>

Body:
To make the textbox and select box have exactly the same appearance style-wise, pick the style you want (i.e. something like border: 1px solid #666666 to mimic the <input> element) and apply it to both your .textfield and .select classes together.

You can use JavaScript to only apply that style when the user is on a Mac, if you want. (See this answer.)

.form {
  width: 300px;
  padding: 20px;
  background-color: #f5f5f5;
}

.textfield,
.select {
  margin-top: 5px;
  padding: 5px;
  width: 100%;
  border: 1px solid #666666;
}

.select {
  background: #fff;
  border-radius: 0;
}

.asterisk {
  color: #FF0004;
}

<div class="form">
  <div>
    <label for="text">
      <nobr>Text field</nobr>
    </label>
    <br />
    <input name="text" tabindex="1" class="textfield" />
  </div>
  <br />
  <div>
    <label for="select">
      <nobr>Select<span class="asterisk">&#42;</span></nobr>
    </label>
    <br />
    <select name="select" tabindex="2" class="select">
      <option value="">&#45;&#45; Please Select &#45;&#45;</option>
      <option value="option 1">Option 1</option>
      <option value="option 2">Option 2</option>
    </select>
  </div>
</div>


问:
What is the backing property for ngModel directive when you use it without the [()] syntax
Looking at an angular forms example that I'm editing I see one example that uses the ngModel keyword without assigning it to a backing property name.

```<code><input ngModel required type="password" class="form-control" name="password" id="password" placeholder="Password" >
</code>```

I normally see it with a binding bracket of [ngModel]="password" or [(ngModel)]="password"

If we use the plain ngModel directive of the first example without an assignment, what backing property is the input data bound to?  Is it not bound to anything and only accesible from form.values?  In what use case would you want to use the plain ngModel directive - when you don't need binding and only want to access it from the form values?

答:
The ngModel registers the input field in the ngForm directive. The name of the input is used as key.

some-component.html

```<code><form novalidate (ngSubmit)="save(form.value)" #form="ngForm" >
  <input type="text" name="title" ngModel />
  <button type="submit" [disabled]="!form.valid">save</button>
</form>
</code>```

some-component.ts

```<code>...
save(value: any) {
   console.log(value.title);
}
</code>```

If you remove the ngModel from the input field, then value.title is gone (undefined).

Body:
Looking at an angular forms example that I'm editing I see one example that uses the ngModel keyword without assigning it to a backing property name.

<input ngModel required type="password" class="form-control" name="password" id="password" placeholder="Password" >

I normally see it with a binding bracket of [ngModel]="password" or [(ngModel)]="password"

If we use the plain ngModel directive of the first example without an assignment, what backing property is the input data bound to?  Is it not bound to anything and only accesible from form.values?  In what use case would you want to use the plain ngModel directive - when you don't need binding and only want to access it from the form values?

Body:
The ngModel registers the input field in the ngForm directive. The name of the input is used as key.

some-component.html

<form novalidate (ngSubmit)="save(form.value)" #form="ngForm" >
  <input type="text" name="title" ngModel />
  <button type="submit" [disabled]="!form.valid">save</button>
</form>

some-component.ts

...
save(value: any) {
   console.log(value.title);
}

If you remove the ngModel from the input field, then value.title is gone (undefined).


问:
unable to fetch dropdown value using ngModel
I have couple of dropdown fields in my application. And I am using ngModel to bind the values. Here is my demo plnkr

Surprisingly From and To dropdowns work fine. But I couldn't able to get value from Group and sortby dropdowns. But I could set values to Group and sort dropdowns when I call clearFilter()

I know that I have gone wrong somewhere but couldn't figure it.

component.html

```<code><div class="modal-body">
              <div >
                <div >Sort by</div>
                <div >
                  <select [(ngModel)]='select_sortby'>
                    <option [ngValue]='relevant' [selected]='select_sortby_default===null'>Most Relevant</option>
                    <option [ngValue]='recent'>Most Recent</option>
                    <option [ngValue]='ascending'>Ascending</option>
                    <option [ngValue]='dscending'>Descending</option>
                  </select>
                </div>
              </div>
              <div >
                <div >Main Group</div>
                <div >
                  <select [(ngModel)]='select_group'>
                      <option [ngValue]='' disabled [selected]='select_group_default===null'>Select Main Group</option>
                      <option [ngValue]='group1'>Group1</option>
                      <option [ngValue]='group2'>Group2</option>
                      <option [ngValue]='group3'>Group3</option>
                    </select>
                </div>
              </div>
              <div >
                <div >Series</div>
                <div >
                  <input [(ngModel)]='series' type="input" placeholder="Enter Series">
                </div>
              </div>
              <div >
                <div >Year Published</div>
                <div >
                  <div >
                    <div class="col-lg-3 ">
                      From
                    </div>
                    <div class="col-lg-7 ">
                      <select [(ngModel)]='select_from_year'>
                        <option [ngValue]='' disabled [selected]='select_from_year_default===null'></option>
                        <option [ngValue]='1992'>1992</option>
                        <option [ngValue]='1993'>1993</option>
                        <option [ngValue]='1994'>1994</option>
                      </select>
                    </div>

                  </div>
                  <div  style="margin-top:10px">
                    <div class="col-lg-3 ">
                      To
                    </div>
                    <div class="col-lg-7 ">
                      <select [(ngModel)]='select_to_year'>
                          <option [ngValue]='' disabled [selected]='select_to_year_default===null'></option>
                          <option [ngValue]='2010'>2010</option>
                          <option [ngValue]='2011'>2011</option>
                          <option [ngValue]='2012'>2012</option>
                        </select>
                    </div>

                  </div>
                </div>
              </div>
            </div>
            <div class="modal-footer" style="border: 0px solid white;">
              <div >
                <div class="col-lg-6">
                  <button type="button" class="bmw-xs-results-btn-clear-filter" (click)='clearFilter()'>Clear Filter</button>
                </div>
                <div class="col-lg-6">
                  <button type="button" class=" bmw-xs-results-btn-apply-filter" (click)='applyFilter()'>Apply Filter</button>
                </div>
              </div>
            </div>
</code>```

component.ts

```<code>    export class App {
      name:string;
      constructor() {

      }
      public select_sortby: string;
      public select_sortby_default = '';
      public select_to_year: string;
      public select_to_year_default = '';
      public select_from_year: string;
      public select_from_year_default = '';
      public select_group: string;
      public select_group_default = '';
      public series: string;
      applyFilter() {
        console.log(this.select_sortby);
        console.log(this.select_group);
        console.log(this.series);
        console.log(this.select_from_year);
        console.log(this.select_to_year);
      }
      clearFilter() {
        this.select_sortby_default = null;
        this.select_from_year_default = null;
        this.select_to_year_default = null;
        this.select_group_default = null;
        this.series = '';
//debug statement
        this.applyFilter();
      }
    }
</code>```

答: The solution for your problem it's quite easy. Just change the "[ngValue]" to "value".</p>

Body:
I have couple of dropdown fields in my application. And I am using ngModel to bind the values. Here is my demo plnkr

Surprisingly From and To dropdowns work fine. But I couldn't able to get value from Group and sortby dropdowns. But I could set values to Group and sort dropdowns when I call clearFilter()

I know that I have gone wrong somewhere but couldn't figure it.

component.html

Sort by

                  <select [(ngModel)]='select_sortby'>
                    <option [ngValue]='relevant' [selected]='select_sortby_default===null'>Most Relevant</option>
                    <option [ngValue]='recent'>Most Recent</option>
                    <option [ngValue]='ascending'>Ascending</option>
                    <option [ngValue]='dscending'>Descending</option>
                  </select>

Main Group

                  <select [(ngModel)]='select_group'>
                      <option [ngValue]='' disabled [selected]='select_group_default===null'>Select Main Group</option>
                      <option [ngValue]='group1'>Group1</option>
                      <option [ngValue]='group2'>Group2</option>
                      <option [ngValue]='group3'>Group3</option>
                    </select>

Series

                  <input [(ngModel)]='series' type="input" placeholder="Enter Series">

Year Published

                      From

                      <select [(ngModel)]='select_from_year'>
                        <option [ngValue]='' disabled [selected]='select_from_year_default===null'></option>
                        <option [ngValue]='1992'>1992</option>
                        <option [ngValue]='1993'>1993</option>
                        <option [ngValue]='1994'>1994</option>
                      </select>

                      To

                      <select [(ngModel)]='select_to_year'>
                          <option [ngValue]='' disabled [selected]='select_to_year_default===null'></option>
                          <option [ngValue]='2010'>2010</option>
                          <option [ngValue]='2011'>2011</option>
                          <option [ngValue]='2012'>2012</option>
                        </select>

                  <button type="button" class="bmw-xs-results-btn-clear-filter" (click)='clearFilter()'>Clear Filter</button>

                  <button type="button" class=" bmw-xs-results-btn-apply-filter" (click)='applyFilter()'>Apply Filter</button>

component.ts

    export class App {
      name:string;
      constructor() {

      }
      public select_sortby: string;
      public select_sortby_default = '';
      public select_to_year: string;
      public select_to_year_default = '';
      public select_from_year: string;
      public select_from_year_default = '';
      public select_group: string;
      public select_group_default = '';
      public series: string;
      applyFilter() {
        console.log(this.select_sortby);
        console.log(this.select_group);
        console.log(this.series);
        console.log(this.select_from_year);
        console.log(this.select_to_year);
      }
      clearFilter() {
        this.select_sortby_default = null;
        this.select_from_year_default = null;
        this.select_to_year_default = null;
        this.select_group_default = null;
        this.series = '';
//debug statement
        this.applyFilter();
      }
    }


问:
Perform search based on seperate table data in PostgreSQL
I have a table which looks like this:

```<code>deals
id     vendorid     name
1      52           '25% Off'
2      34           '10% Off'
</code>```

-

```<code>vendors
id     name
52     'Walmart'
34     'Home Depot'
</code>```

I'm trying to do a search of the database that also searches based on the vendor id.

I was able to do this to get the vendor data in the query:

```<code>SELECT *,
(SELECT json_agg(vendors.*) FROM vendors WHERE deals.vendorid = vendors.id) as vendor
FROM deals
</code>```

Now I want to add a search to it, here is something I tried

```<code>SELECT *,
(SELECT json_agg(vendors.*) FROM vendors WHERE deals.vendorid = vendors.id) as vendor
FROM deals
WHERE vendor.name ILIKE '%wal%'
</code>```

In the above example the user would be starting a search for walmart however it says that the vendor.name column does not exist, what would the correct way to do this be?

The output I'm expecting from the above query is:

```<code>[
 {
   id: 1,
   vendorid: 52,
   name: '25% Off',
   vendor: [
      {
        id: 52,
        name: 'Walmart'
      }
   ]
 }
]
</code>```

答:
The query you need

```<code>drop table if exists deals;
drop table if exists vendors;

create table if not exists deals(
  id serial,
  vendorid int not null,
  name varchar not null
);

create table if not exists vendors(
  id serial,
  name varchar not null
);

insert into deals values
(1,52,'25% off'),
(2,34,'10% off');

insert into vendors values
(52,'Walmart'),
(34,'Home Depot');

select
    d.id,
    d.vendorid,
    v.name,
    json_agg(v.*)
from
    vendors v
left join
    deals d on d.vendorid = v.id
where
    --v.id=52 and
    v.name ILIKE '%wal%'
group by
    d.id,
    d.vendorid,
    v.name;
</code>```

If you are running a 9.3+ version of postgres, you can use a great feature provided by postgres : the full text search

check how it works here

Enjoy postgres power.

Body:
I have a table which looks like this:

deals
id     vendorid     name
1      52           '25% Off'
2      34           '10% Off'

-

vendors
id     name
52     'Walmart'
34     'Home Depot'

I'm trying to do a search of the database that also searches based on the vendor id.

I was able to do this to get the vendor data in the query:

SELECT *,
(SELECT json_agg(vendors.*) FROM vendors WHERE deals.vendorid = vendors.id) as vendor
FROM deals

Now I want to add a search to it, here is something I tried

SELECT *,
(SELECT json_agg(vendors.*) FROM vendors WHERE deals.vendorid = vendors.id) as vendor
FROM deals
WHERE vendor.name ILIKE '%wal%'

In the above example the user would be starting a search for walmart however it says that the vendor.name column does not exist, what would the correct way to do this be?

The output I'm expecting from the above query is:

[
 {
   id: 1,
   vendorid: 52,
   name: '25% Off',
   vendor: [
      {
        id: 52,
        name: 'Walmart'
      }
   ]
 }
]

Body:
The query you need

drop table if exists deals;
drop table if exists vendors;

create table if not exists deals(
  id serial,
  vendorid int not null,
  name varchar not null
);

create table if not exists vendors(
  id serial,
  name varchar not null
);

insert into deals values
(1,52,'25% off'),
(2,34,'10% off');

insert into vendors values
(52,'Walmart'),
(34,'Home Depot');

select
    d.id,
    d.vendorid,
    v.name,
    json_agg(v.*)
from
    vendors v
left join
    deals d on d.vendorid = v.id
where
    --v.id=52 and
    v.name ILIKE '%wal%'
group by
    d.id,
    d.vendorid,
    v.name;

If you are running a 9.3+ version of postgres, you can use a great feature provided by postgres : the full text search

check how it works here

Enjoy postgres power.


问:
When should I use "this" in a class?
I know that this refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x instead of this.x in some of the methods? May be x will refer to a variable which is local for the considered method? I mean variable which is seen only in this method.

What about this.method()? Can I use it? Should I use it. If I just use method(), will it not be, by default, applied to the current object?

答:
With respect to William Brendel's posts and dbconfessions question, regarding case 2. Here is an example:

```<code>public class Window {

  private Window parent;

  public Window (Window parent) {
    this.parent = parent;
  }

  public void addSubWindow() {
    Window child = new Window(this);
    list.add(child);
  }

  public void printInfo() {
    if (parent == null) {
      System.out.println("root");
    } else {
      System.out.println("child");
    }
  }

}
</code>```

I've seen this used, when building parent-child relation's with objects. However, please note that it is simplified for the sake of brevity.

Title: When should I use "this" in a class?

Body:
With respect to William Brendel's posts and dbconfessions question, regarding case 2. Here is an example:

public class Window {

  private Window parent;

  public Window (Window parent) {
    this.parent = parent;
  }

  public void addSubWindow() {
    Window child = new Window(this);
    list.add(child);
  }

  public void printInfo() {
    if (parent == null) {
      System.out.println("root");
    } else {
      System.out.println("child");
    }
  }

}

I've seen this used, when building parent-child relation's with objects. However, please note that it is simplified for the sake of brevity.


问:
Search box not appearing on rails application
I'm attempting to launch an MVC project on ruby on rails. Having a few issues.
Specifically with the search functionality. This is for a rental website. but unable to get the search box to appear and work.

I have 3 models items, profile and users.
Specifically I want to be able to search users by first name and last name.

Within the profile model I have:

```<code>def self.search(search)
  where("lastname LIKE ?", "%#{search}%")
end
</code>```

Within in the profile_controller I have:

```<code>def index
  if params[:search]
    @profiles = Profile.search(params[:search]).order("created_at DESC")
  else
   @profiles = Profile.all.order("created_at DESC")
  end
end
</code>```

The application has the following code layout application.html page:

```<code><p> search </p>
<% form_tag(profiles_path, :method => "get", id: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search Profile by Lastname" %>
<%= submit_tag "Search" %>
</code>```

Would also like to extend this further to see what items the users have rented as well.

答: In ERB <% code here %> tags won't display. You need to change it to <%= code here %>.

Body:
I'm attempting to launch an MVC project on ruby on rails. Having a few issues.
Specifically with the search functionality. This is for a rental website. but unable to get the search box to appear and work.

I have 3 models items, profile and users.
Specifically I want to be able to search users by first name and last name.

Within the profile model I have:

def self.search(search)
  where("lastname LIKE ?", "%#{search}%")
end

Within in the profile_controller I have:

def index
  if params[:search]
    @profiles = Profile.search(params[:search]).order("created_at DESC")
  else
   @profiles = Profile.all.order("created_at DESC")
  end
end

The application has the following code layout application.html page:

 search

<% form_tag(profiles_path, :method => "get", id: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search Profile by Lastname" %>
<%= submit_tag "Search" %>

Would also like to extend this further to see what items the users have rented as well.


问:
recyclerview linear layout responds to click only from half of it, but after scrolling it works fine
I have a recyclerview with each row made of a linear layout, and simple textview.

In the linear layout (which is the parent), I put an interface, with OnItemClickListener. Its working fine but...

The row is only clickable at the area where the text view is. However the rest of the area of the Linear Layout is not clickable. So when I click the blank area of the row, nothing happens. But when I scroll down the list a bit, for the items below it does work fine.

I hope its clear. Why is this.

Here is my adapter:

```<code>    public class SearchAdapter extends RecyclerView.Adapter<SearchItemViewHolder> {

    private ArrayList<String> searchArrayList;
    private Context context;

    private OnItemClickListener mOnItemClickListener;

    public interface OnItemClickListener {
         void onItemClick(String itemName);
    }

    public SearchAdapter(ArrayList<String> searchArrayList, Context context, OnItemClickListener onItemClickListener) {
        this.searchArrayList = searchArrayList;
        this.context = context;
        mOnItemClickListener = onItemClickListener;
    }

    @Override
    public SearchItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.food_list_item_search_view, parent, false);

        return new SearchItemViewHolder(itemView);

    }

    @Override
    public void onBindViewHolder(SearchItemViewHolder holder, final int position) {

        final String currentItem = searchArrayList.get(position);

        holder.itemTextView.setText(currentItem);

        holder.searchItemLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOnItemClickListener.onItemClick(currentItem);
            }
        });

//        holder.setImage(holder.itemTextView.getContext(), holder.countryFlagImageView, currentCountry.getFlag());

    }

//    @Override
//    public void onViewRecycled(SearchItemViewHolder holder) {
//        super.onViewRecycled(holder);
//        holder.imageLoadTask.cancel(true);
//    }

    @Override
    public int getItemCount() {
        return searchArrayList.size();
    }

}
</code>```

Here is my viewholder:

```<code>    public class SearchItemViewHolder extends RecyclerView.ViewHolder {

    TextView itemTextView;
    LinearLayout searchItemLinearLayout;

//    public LoadImage imageLoadTask;

    public SearchItemViewHolder(View itemView) {
        super(itemView);

        itemTextView = (TextView)itemView.findViewById(R.id.search_item_text_view);
        searchItemLinearLayout = (LinearLayout)itemView.findViewById(R.id.search_item_linearlayout);

    }

//    public void setImage(Context context, ImageView imageView, int resource){
//        imageLoadTask = new LoadImage(context, imageView, resource);
//        imageLoadTask.execute();
//    }

}
</code>```

Here is my xml:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:id="@+id/search_item_linearlayout"
    android:layout_height="60dp"
    android:background="?android:attr/selectableItemBackground"

    >

       <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Food item"
        android:textSize="20sp"
        android:gravity="center_vertical"
        android:id="@+id/search_item_text_view"
        android:padding="10dp"
        android:textColor="@color/colorPrimary"
        />

</LinearLayout>
</code>```

答: This was happening because I was using Linear Layout and orietaion horizontal. When I changed it to relative layout, it worked fine.</p>

Body:
I have a recyclerview with each row made of a linear layout, and simple textview.

In the linear layout (which is the parent), I put an interface, with OnItemClickListener. Its working fine but...

The row is only clickable at the area where the text view is. However the rest of the area of the Linear Layout is not clickable. So when I click the blank area of the row, nothing happens. But when I scroll down the list a bit, for the items below it does work fine.

I hope its clear. Why is this.

Here is my adapter:

    public class SearchAdapter extends RecyclerView.Adapter<SearchItemViewHolder> {

    private ArrayList<String> searchArrayList;
    private Context context;

    private OnItemClickListener mOnItemClickListener;

    public interface OnItemClickListener {
         void onItemClick(String itemName);
    }

    public SearchAdapter(ArrayList<String> searchArrayList, Context context, OnItemClickListener onItemClickListener) {
        this.searchArrayList = searchArrayList;
        this.context = context;
        mOnItemClickListener = onItemClickListener;
    }

    @Override
    public SearchItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.food_list_item_search_view, parent, false);

        return new SearchItemViewHolder(itemView);

    }

    @Override
    public void onBindViewHolder(SearchItemViewHolder holder, final int position) {

        final String currentItem = searchArrayList.get(position);

        holder.itemTextView.setText(currentItem);

        holder.searchItemLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOnItemClickListener.onItemClick(currentItem);
            }
        });

//        holder.setImage(holder.itemTextView.getContext(), holder.countryFlagImageView, currentCountry.getFlag());

    }

//    @Override
//    public void onViewRecycled(SearchItemViewHolder holder) {
//        super.onViewRecycled(holder);
//        holder.imageLoadTask.cancel(true);
//    }

    @Override
    public int getItemCount() {
        return searchArrayList.size();
    }

}

Here is my viewholder:

    public class SearchItemViewHolder extends RecyclerView.ViewHolder {

    TextView itemTextView;
    LinearLayout searchItemLinearLayout;

//    public LoadImage imageLoadTask;

    public SearchItemViewHolder(View itemView) {
        super(itemView);

        itemTextView = (TextView)itemView.findViewById(R.id.search_item_text_view);
        searchItemLinearLayout = (LinearLayout)itemView.findViewById(R.id.search_item_linearlayout);

    }

//    public void setImage(Context context, ImageView imageView, int resource){
//        imageLoadTask = new LoadImage(context, imageView, resource);
//        imageLoadTask.execute();
//    }

}

Here is my xml:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:id="@+id/search_item_linearlayout"
    android:layout_height="60dp"
    android:background="?android:attr/selectableItemBackground"

    >

       <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Food item"
        android:textSize="20sp"
        android:gravity="center_vertical"
        android:id="@+id/search_item_text_view"
        android:padding="10dp"
        android:textColor="@color/colorPrimary"
        />

</LinearLayout>


问:
Have file automatically upload to server when .php is launched
I'm trying to write code in php so that when the .php file is opened, it automatically uploads from a specific file address on my windows computer to the localhost server.

This is my attempt but I'm not sure I fully understand how to do this without using an HTML form where the user specifies the file they want to upload.

```<code> <?php
 $target =  'UPLOADED_FILE.csv';
 move_uploaded_file('C:\Users\Ken.Feier\Desktop\temp\REPORT.csv', $target);
 ?>
</code>```

I want the code to take the REPORT.csv file from my personal computer and upload it to our server with the file name UPLOADED_FILE.csv

UPDATE: I see that my problem will not be solved with php. Can anyone recommend any other solution involving Filezilla or any other FTP that can be automated?

答:
That's not how it should be done.

You need a page with a html form, which will send the data to server on submit. Note that the file could be stored on your personal.

Form code e.g.

```<code><form method="post" action="destination.php" enctype="multipart/form-data">
  <input type="file" name="filename" />
  <input type="submit" value="upload" />
</form>
</code>```

Then, on the server, you can use the $_FILES['filename'] which contains your file's infos. Note that when a file is uploaded to the server, it's stored in the tmp folder, which is temporary, so you have to move your file to a persistent directory with move_uploaded_file(); (move_uploaded_file Docs)

E.g:

```<code><?php

    $file = $_FILES['filename'];
    move_uploaded_file($file['tmp_name'], '/new/destination/for/the/filename.php');
</code>```

Body:
I'm trying to write code in php so that when the .php file is opened, it automatically uploads from a specific file address on my windows computer to the localhost server.

This is my attempt but I'm not sure I fully understand how to do this without using an HTML form where the user specifies the file they want to upload.

 <?php
 $target =  'UPLOADED_FILE.csv';
 move_uploaded_file('C:\Users\Ken.Feier\Desktop\temp\REPORT.csv', $target);
 ?>

I want the code to take the REPORT.csv file from my personal computer and upload it to our server with the file name UPLOADED_FILE.csv

UPDATE: I see that my problem will not be solved with php. Can anyone recommend any other solution involving Filezilla or any other FTP that can be automated?

Body:
That's not how it should be done.

You need a page with a html form, which will send the data to server on submit. Note that the file could be stored on your personal.

Form code e.g.

<form method="post" action="destination.php" enctype="multipart/form-data">
  <input type="file" name="filename" />
  <input type="submit" value="upload" />
</form>

Then, on the server, you can use the $_FILES['filename'] which contains your file's infos. Note that when a file is uploaded to the server, it's stored in the tmp folder, which is temporary, so you have to move your file to a persistent directory with move_uploaded_file(); (move_uploaded_file Docs)

E.g:

<?php

    $file = $_FILES['filename'];
    move_uploaded_file($file['tmp_name'], '/new/destination/for/the/filename.php');


问:
How to AJAX load a blog image from RSS/XML when img is in CDATA
How to AJAX load blog image from RSS/XML when img is in CDATA?

I can load the title, url, publication date, etc... from our blog rss feed, but I cannot figure out how to target the image. I started with this script and modified it to get this:

```<code>$.ajax({
type: "GET",
url: "http://www.example.com/blog/feed",
dataType: "xml",

success: function(xml) {

    var contain = $("div#blogSection");
    var limit = 1;

    $(xml).find('item').each(function(index){
    if( index < limit ){

        var title = $(this).find('title').text();
        var url = $(this).find('link').text();
        var pubDate = $(this).find('pubDate').text();
        var img = $(this).find('content:encoded > p > img').attr('src').text();
        var desc = $(this).find('description > p:first').text();

        $('<div class="blogFeed"></div>').html('<div class="feedThumbnail"><img src="'+img+'" class="resizable" title="blog image" alt="blog image"></div><div class="feedExcerpt"><h3 class="title"><a href="'+url+'">'+title+'</a></h3><p>'+desc+'</p><p><a class="allLink" href="'+url+'" title="read more" alt="read more" target="_blank">read more</a></p></div>').appendTo(contain);
        return;
        }
        });//end each
    }
});
</code>```

I think the problem is in CDATA within the xml, as I have read that it interprets everything within it as character data. The xml looks something like this:

```<code><item>
    <title>Title</title>
    <link>Link</link>
    <comments>Comments</comments>
    <pubDate>Date</pubDate>
    <description><![CDATA[Description]]></description>
    <content:encoded><![CDATA[<p><img src="http://www.example.com/img.jpg"...]]></content:encoded>
</item>
</code>```

If I am correct that it is CDATA causing it to not target, what can I do in my ajax code to target the image and the first paragraph? If I am incorrect, should I add/remove?

Thanks!

答:
Working on all browsers:

I replaced this:

```<code>var img = $(this).find('content:encoded > p > img').attr('src').text();
</code>```

With this:

```<code>var img = $(this).find('content\\:encoded, encoded').text();
img = $.parseHTML(img);
img = img[0].firstChild.src;
</code>```

I escaped the special character in 'content:encoded' and added ", encoded". After adding $.parseHTML, console.log(img); revealed the location of the src. Returning .text() removed CDATA and I now suspect that CDATA is irrelevant. Days of testing for a blog image. Hope it helps someone else save time.

Body:
How to AJAX load blog image from RSS/XML when img is in CDATA?

I can load the title, url, publication date, etc... from our blog rss feed, but I cannot figure out how to target the image. I started with this script and modified it to get this:

$.ajax({
type: "GET",
url: "http://www.example.com/blog/feed",
dataType: "xml",

success: function(xml) {

    var contain = $("div#blogSection");
    var limit = 1;

    $(xml).find('item').each(function(index){
    if( index < limit ){

        var title = $(this).find('title').text();
        var url = $(this).find('link').text();
        var pubDate = $(this).find('pubDate').text();
        var img = $(this).find('content:encoded > p > img').attr('src').text();
        var desc = $(this).find('description > p:first').text();

        $('

').html('

'+title+'

'+desc+'

read more

').appendTo(contain);
        return;
        }
        });//end each
    }
});

I think the problem is in CDATA within the xml, as I have read that it interprets everything within it as character data. The xml looks something like this:

<item>
    <title>Title</title>
    <link>Link</link>
    <comments>Comments</comments>
    <pubDate>Date</pubDate>
    <description><![CDATA[Description]]></description>
    <content:encoded><![CDATA[
</content:encoded>
</item>

If I am correct that it is CDATA causing it to not target, what can I do in my ajax code to target the image and the first paragraph? If I am incorrect, should I add/remove?

Thanks!

Body:
Working on all browsers:

I replaced this:

var img = $(this).find('content:encoded > p > img').attr('src').text();

With this:

var img = $(this).find('content\\:encoded, encoded').text();
img = $.parseHTML(img);
img = img[0].firstChild.src;

I escaped the special character in 'content:encoded' and added ", encoded". After adding $.parseHTML, console.log(img); revealed the location of the src. Returning .text() removed CDATA and I now suspect that CDATA is irrelevant. Days of testing for a blog image. Hope it helps someone else save time.


问:
How to sum within a group of values and then take the difference from another group?
Let say I have this simplified dataframe with three variables:

```<code>ID    sample  test_result
P1    Normal           9
P1    Normal           18
P2    Normal           7
P2    Normal           16
P3    Normal           2
P3    Normal           11
P1     Tumor           6
P1     Tumor           15
P2     Tumor           5
P2     Tumor           15
P3     Tumor           3
P3     Tumor           12
</code>```

I want to know how to sum the test_result values for each identical ID in each sample type (i.e. Normal, Tumor).  Then I want to then take the difference between the summed normal and tumor test_result values.

I have tried using groupby on sample column and then use the diff() method on test_result column but that did not work.  I guess I need to know how to do apply the .sum() first, but not sure how.

Here is what I have tried:

```<code>df.groupby('sample')['test_result'].diff()
</code>```

The output I am expecting is like:

```<code>ID   test_result
P1             6 # (the sum of P1 Normal = 27) - (the sum of P1 Tumor = 21)
P2             3
P3            -2
</code>```

Any idea how to tackle this?

答:
Use groupby with sum and reshape by unstack:

```<code>df = df.groupby(['ID','sample'])['test_result'].sum().unstack()
</code>```

Or pivot_table:

```<code>df = df.pivot_table(index='ID',columns='sample', values='test_result', aggfunc='sum')
</code>```

and then subtract columns:

```<code>df['new'] = df['Normal'] - df['Tumor']
print (df)
sample  Normal  Tumor  new
ID
P1          27     21    6
P2          23     20    3
P3          13     15   -2
</code>```

Body:
Let say I have this simplified dataframe with three variables:

ID    sample  test_result
P1    Normal           9
P1    Normal           18
P2    Normal           7
P2    Normal           16
P3    Normal           2
P3    Normal           11
P1     Tumor           6
P1     Tumor           15
P2     Tumor           5
P2     Tumor           15
P3     Tumor           3
P3     Tumor           12

I want to know how to sum the test_result values for each identical ID in each sample type (i.e. Normal, Tumor).  Then I want to then take the difference between the summed normal and tumor test_result values.

I have tried using groupby on sample column and then use the diff() method on test_result column but that did not work.  I guess I need to know how to do apply the .sum() first, but not sure how.

Here is what I have tried:

df.groupby('sample')['test_result'].diff()

The output I am expecting is like:

ID   test_result
P1             6 # (the sum of P1 Normal = 27) - (the sum of P1 Tumor = 21)
P2             3
P3            -2

Any idea how to tackle this?

Body:
Use groupby with sum and reshape by unstack:

df = df.groupby(['ID','sample'])['test_result'].sum().unstack()

Or pivot_table:

df = df.pivot_table(index='ID',columns='sample', values='test_result', aggfunc='sum')

and then subtract columns:

df['new'] = df['Normal'] - df['Tumor']
print (df)
sample  Normal  Tumor  new
ID
P1          27     21    6
P2          23     20    3
P3          13     15   -2


问:
how get company wise highest salaried employee name from this schema
the database schema is like this:

employee(emp_id#,person_name,dob,street,city)

company(company_id#, company_name,city)

works(emp_id,company_id,salary)

manages(emp_id,manager_id)

```<code>insert into employee values('e-1','dipankar pal','15-jul-1997','h.m raod','kolkata');
insert into employee values('e-2','subhadip roy','15-jan-1997','garia','kolkata');
</code>```

the manages table may be little bit confusing, here are some data I've inserted to clear my point

```<code>insert into manages values('e-3','e-1');
insert into manages values('e-4','e-1');
insert into manages values('e-5','e-1');
insert into manages values('e-6','e-2');
insert into manages values('e-7','e-2');
</code>```

答:
Try  </p>

```<code>SELECT Z.COMPANY_NAME, E.PERSON_NAME, Z.HIGHEST_SALARY
FROM
    (SELECT C.COMPANY_ID, C.COMPANY_NAME, MAX(W.SALARY) AS HIGHEST_SALARY
    FROM
    WORKS W INNER JOIN COMPANY C
    ON W.COMPANY_ID = C.COMPANY_ID
    GROUP BY C.COMPANY_ID, C.COMPANY_NAME ) Z
INNER JOIN WORKS W
ON Z.COMPANY_ID = W.COMPANY_ID
AND Z.HIGHEST_SALARY = W.SALARY
INNER JOIN EMPLOYEE E
ON W.EMP_ID = E.EMP_ID
ORDER BY Z.HIGHEST_SALARY DESC;
</code>```

Body:
the database schema is like this:

employee(emp_id#,person_name,dob,street,city)

company(company_id#, company_name,city)

works(emp_id,company_id,salary)

manages(emp_id,manager_id)

insert into employee values('e-1','dipankar pal','15-jul-1997','h.m raod','kolkata');
insert into employee values('e-2','subhadip roy','15-jan-1997','garia','kolkata');

the manages table may be little bit confusing, here are some data I've inserted to clear my point

insert into manages values('e-3','e-1');
insert into manages values('e-4','e-1');
insert into manages values('e-5','e-1');
insert into manages values('e-6','e-2');
insert into manages values('e-7','e-2');

Body:
Try

SELECT Z.COMPANY_NAME, E.PERSON_NAME, Z.HIGHEST_SALARY
FROM
    (SELECT C.COMPANY_ID, C.COMPANY_NAME, MAX(W.SALARY) AS HIGHEST_SALARY
    FROM
    WORKS W INNER JOIN COMPANY C
    ON W.COMPANY_ID = C.COMPANY_ID
    GROUP BY C.COMPANY_ID, C.COMPANY_NAME ) Z
INNER JOIN WORKS W
ON Z.COMPANY_ID = W.COMPANY_ID
AND Z.HIGHEST_SALARY = W.SALARY
INNER JOIN EMPLOYEE E
ON W.EMP_ID = E.EMP_ID
ORDER BY Z.HIGHEST_SALARY DESC;


问:
How I can print an output number for a running file
How I can get an output message which is "1" or "0" of an already running file?

I mean if i have a .jar file and i tun it by this command java -jar [FILENAME].jar, how i can output a status number( 0 if it is not running or 1 if is running)
N.B: I only want the number as an output message. In a bash script as variable.

答:
i think you are expecting something like this,

```<code>[ $(ps -ef | grep "[FILENAME].jar" | grep -v "grep" | wc -l) -gt 0 ] && echo "1" || echo "0"
</code>```

if need bit more detailed version, then below will suit i guess,

```<code>if [ $(ps -ef | grep "[FILENAME].jar" | grep -v "grep" | wc -l) -gt 0 ];then
   echo "1"
else
   echo "0"
fi
</code>```

Body:
i think you are expecting something like this,

[ $(ps -ef | grep "[FILENAME].jar" | grep -v "grep" | wc -l) -gt 0 ] && echo "1" || echo "0"

if need bit more detailed version, then below will suit i guess,

if [ $(ps -ef | grep "[FILENAME].jar" | grep -v "grep" | wc -l) -gt 0 ];then
   echo "1"
else
   echo "0"
fi