问:
Create a Map out of a List of String(s) with streams
I have a List of String(s), but I want to convert it into a Map<String, Boolean> from the List<String>, making all of the boolean mappings set to true. I have the following code.

```<code>import java.lang.*;
import java.util.*;
class Main {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("ab");
    list.add("bc");
    list.add("cd");
    Map<String, Boolean> alphaToBoolMap = new HashMap<>();
    for (String item: list) {
      alphaToBoolMap.put(item, true);
    }
    //System.out.println(list); [ab, bc, cd]
    //System.out.println(alphaToBoolMap);  {ab=true, bc=true, cd=true}
  }
}
</code>```

Is there a way to reduce this using streams?

答:
The shortest way I can think of is not a one-liner, but it's indeed short:

```<code>Map<String, Boolean> map = new HashMap<>();
list.forEach(k -> map.put(k, true));
</code>```

This is personal taste, but I only use streams when I need to apply transformations to the source, or filter out some elements, etc.

As suggested in the comments by @holi-java, many times, using a Map with Boolean values is pointless, since there are only two possible values to map keys to. Instead, a Set could be used to solve almost all the same problems you'd solve with a Map<T, Boolean>.

Body:
I have a List of String(s), but I want to convert it into a Map<String, Boolean> from the List<String>, making all of the boolean mappings set to true. I have the following code.

import java.lang.*;
import java.util.*;
class Main {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("ab");
    list.add("bc");
    list.add("cd");
    Map<String, Boolean> alphaToBoolMap = new HashMap<>();
    for (String item: list) {
      alphaToBoolMap.put(item, true);
    }
    //System.out.println(list); [ab, bc, cd]
    //System.out.println(alphaToBoolMap);  {ab=true, bc=true, cd=true}
  }
}

Is there a way to reduce this using streams?

Body:
The shortest way I can think of is not a one-liner, but it's indeed short:

Map<String, Boolean> map = new HashMap<>();
list.forEach(k -> map.put(k, true));

This is personal taste, but I only use streams when I need to apply transformations to the source, or filter out some elements, etc.

As suggested in the comments by @holi-java, many times, using a Map with Boolean values is pointless, since there are only two possible values to map keys to. Instead, a Set could be used to solve almost all the same problems you'd solve with a Map<T, Boolean>.


来源: stackexchange

问:
Cannot implicitly convert type 'string' to 'System.DateTime'
I am  trying  to  convert from string to DataTime but an an error occurs.
I am using  VS 2003, .NET Framework 1.1

```<code>DateTime dt = Convert.ToDateTime("11/23/2010");
string s2 = dt.ToString("dd-MM-yyyy");
DateTime dtnew = Convert.ToString(s2);
</code>```

Cannot implicitly convert type 'string' to 'System.DateTime'

Can any one  help me  me  with the  syntax  how  to  solve the error.

答:
You should be using DateTime.Parse, or DateTime.ParseExact.

```<code>DateTime dt= DateTime.Parse("11/23/2010");
string  s2=dt.ToString("dd-MM-yyyy");
DateTime dtnew = DateTime.Parse(s2);
</code>```

Both have TryXXX variants that require passing in an out parameter, but will not throw an exception if the parse fails:

```<code>DateTime dt;
if(td = DateTime.TryParse("11/23/2010", out td))
{
  string  s2=dt.ToString("dd-MM-yyyy");
  DateTime dtnew = DateTime.Parse(s2);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am  trying  to  convert from string to DataTime but an an error occurs.
I am using  VS 2003, .NET Framework 1.1

DateTime dt = Convert.ToDateTime("11/23/2010");
string s2 = dt.ToString("dd-MM-yyyy");
DateTime dtnew = Convert.ToString(s2);

Cannot implicitly convert type 'string' to 'System.DateTime'

Can any one  help me  me  with the  syntax  how  to  solve the error.

Body:
You should be using DateTime.Parse, or DateTime.ParseExact.

DateTime dt= DateTime.Parse("11/23/2010");
string  s2=dt.ToString("dd-MM-yyyy");
DateTime dtnew = DateTime.Parse(s2);

Both have TryXXX variants that require passing in an out parameter, but will not throw an exception if the parse fails:

DateTime dt;
if(td = DateTime.TryParse("11/23/2010", out td))
{
  string  s2=dt.ToString("dd-MM-yyyy");
  DateTime dtnew = DateTime.Parse(s2);
}

ContentLicense: CC BY-SA 2.5


问:
How to get the vaadin-context-menu demo to work?
Here is the vaadin-context-menu documentation page.

On that page, there is a button labeled TRY IT OUT that links to a demo page here.

My problem is that I can't get the demo page to actually do anything. I see no errors in the console.

Is the problem on my end? Or is there something wrong with the demo? If it's the latter, how can I fix the code to get the demo to work?

Please show the solution in a working jsBin or Codepen.

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

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>vaadin-context-menu demo</title>
  <script src="https://cdn.vaadin.com/vaadin-core-elements/master/webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="https://cdn.vaadin.com/vaadin-core-elements/master/vaadin-context-menu/vaadin-context-menu.html">

  <!-- import paper-menu and paper-item -->
  <link rel="import" href="https://cdn.vaadin.com/vaadin-core-elements/master/paper-listbox/paper-listbox.html">
  <link rel="import" href="https://cdn.vaadin.com/vaadin-core-elements/master/paper-item/paper-item.html">
</head>
<body>

<vaadin-context-menu>
  <template>
    <paper-listbox>
      <paper-item>First menu item</paper-item>
      <paper-item>Second menu item</paper-item>
    </paper-listbox>
  </template>

  <p>This paragraph has the context menu provided in the above template.</p>
  <p>Another paragraph with the context menu.</p>
</vaadin-context-menu>
</body>
</html>
</code>```

答:
Edit: @petey points out in a comment that this answer only applies when trying to run vaadin-context-menu from jsBin. So the problem might be between jsBin and Safari and not Vaadin and Safari.

This answer only applies to JSBin.

It works in Chrome. But not on Safari. (Running macOS Sierra v.10.12.5.)

vaadin-context-menu

```<code>Browser  Support
-------  -------
Chrome     ✅
Safari     ❌
</code>```

Safari apparently does not support vaadin-context-menu at this time. Below are screen recordings using Safari then Chrome.

(Note: In the below recordings:
Green circles indicate a right click.
Black circles indicate a left click.)

Safari ❌

v10.1.1 (12603.2.4):

Chrome ✅

v59.0.3071.115 (Official Build) (64-bit):

Body:
Here is the vaadin-context-menu documentation page.

On that page, there is a button labeled TRY IT OUT that links to a demo page here.

My problem is that I can't get the demo page to actually do anything. I see no errors in the console.

Is the problem on my end? Or is there something wrong with the demo? If it's the latter, how can I fix the code to get the demo to work?

Please show the solution in a working jsBin or Codepen.

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

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>vaadin-context-menu demo</title>

  <link rel="import" href="https://cdn.vaadin.com/vaadin-core-elements/master/vaadin-context-menu/vaadin-context-menu.html">

  <link rel="import" href="https://cdn.vaadin.com/vaadin-core-elements/master/paper-listbox/paper-listbox.html">
  <link rel="import" href="https://cdn.vaadin.com/vaadin-core-elements/master/paper-item/paper-item.html">

<vaadin-context-menu>
  <template>
    <paper-listbox>
      <paper-item>First menu item</paper-item>
      <paper-item>Second menu item</paper-item>
    </paper-listbox>
  </template>

This paragraph has the context menu provided in the above template.

Another paragraph with the context menu.

</vaadin-context-menu>

Body:
Edit: @petey points out in a comment that this answer only applies when trying to run vaadin-context-menu from jsBin. So the problem might be between jsBin and Safari and not Vaadin and Safari.

This answer only applies to JSBin.

It works in Chrome. But not on Safari. (Running macOS Sierra v.10.12.5.)

vaadin-context-menu

Browser  Support
-------  -------
Chrome     ✅
Safari     ❌

Safari apparently does not support vaadin-context-menu at this time. Below are screen recordings using Safari then Chrome.

(Note: In the below recordings:
Green circles indicate a right click.
Black circles indicate a left click.)

Safari ❌

v10.1.1 (12603.2.4):

Chrome ✅

v59.0.3071.115 (Official Build) (64-bit):


问:
How to groupby by a column and return the values of other columns as lists in pandas?
I am facing trouble clubbing the values of a column together and retaining the respective values of other columns. I would like to do something similar to this: grouping rows in list in pandas groupby

But instead, I want the list/dictionary (preferably latter) to contain values of multiple columns.
Example for this dataframe:

df:

```<code>Col1   Col2   Col3
A      xyz     1
A      pqr     2
B      xyz     2
B      pqr     3
B      lmn     1
C      pqr     2
</code>```

I want something like-

```<code>A {'xyz':1, 'pqr': 2}
B {'xyz':2, 'pqr': 3, 'lmn': 1}
C {'pqr':2}
</code>```

I tried doing

```<code>df.groupby('Col1')[['Col2', 'Col3']].apply(list)
</code>```

which is a variant of the solution mentioned in the linked post, but isn't giving me the result I need.

From that point on, I would also like to transform it into a dataframe of the form:

```<code>  xyz  pqr  lmn
A  1    2    NaN
B  2    3    1
C  NaN  2    NaN
</code>```

答:
Use pivot or unstack:

```<code>df = df.pivot(index='Col1',columns='Col2',values='Col3')
print (df)
Col2  lmn  pqr  xyz
Col1
A     NaN  2.0  1.0
B     1.0  3.0  2.0
C     NaN  2.0  NaN
</code>```

```<code>df = df.set_index(['Col1','Col2'])['Col3'].unstack()
print (df)

Col2  lmn  pqr  xyz
Col1
A     NaN  2.0  1.0
B     1.0  3.0  2.0
C     NaN  2.0  NaN
</code>```

but if:

ValueError: Index contains duplicate entries, cannot reshape

it means duplicates, need pivot_table or aggregate with groupby by mean (can be changed to sum, median), and last reshape by unstack:

```<code>print (df)
  Col1 Col2  Col3
0    A  xyz     1 <-same A, xyz
1    A  xyz     5 <-same A, xyz
2    A  pqr     2
3    B  xyz     2
4    B  pqr     3
5    B  lmn     1
6    C  pqr     2

df = df.groupby(['Col1','Col2'])['Col3'].mean().unstack()
print (df)
Col2  lmn  pqr  xyz
Col1
A     NaN  2.0  3.0 (1+5)/2 = 3
B     1.0  3.0  2.0
C     NaN  2.0  NaN
</code>```

EDIT:

For check all duplicates by Col1 and Col2:

```<code>print (df[df.duplicated(subset=['Col1','Col2'], keep=False)])
  Col1 Col2  Col3
0    A  xyz     1
1    A  xyz     5
</code>```

EDIT1:

If need only first row if duplicates:

```<code>df = df.groupby(['Col1','Col2'])['Col3'].first().unstack()
print (df)
Col2  lmn  pqr  xyz
Col1
A     NaN  2.0  1.0
B     1.0  3.0  2.0
C     NaN  2.0  NaN
</code>```

Or better first remove duplicates by drop_duplicates and then use first or second solution:

```<code>df = df.drop_duplicates(subset=['Col1','Col2'])
df = df.pivot(index='Col1',columns='Col2',values='Col3')
print (df)
Col2  lmn  pqr  xyz
Col1
A     NaN  2.0  1.0
B     1.0  3.0  2.0
C     NaN  2.0  NaN
</code>```

Body:
I am facing trouble clubbing the values of a column together and retaining the respective values of other columns. I would like to do something similar to this: grouping rows in list in pandas groupby

But instead, I want the list/dictionary (preferably latter) to contain values of multiple columns.
Example for this dataframe:

df:

Col1   Col2   Col3
A      xyz     1
A      pqr     2
B      xyz     2
B      pqr     3
B      lmn     1
C      pqr     2

I want something like-

A {'xyz':1, 'pqr': 2}
B {'xyz':2, 'pqr': 3, 'lmn': 1}
C {'pqr':2}

I tried doing

df.groupby('Col1')[['Col2', 'Col3']].apply(list)

which is a variant of the solution mentioned in the linked post, but isn't giving me the result I need.

From that point on, I would also like to transform it into a dataframe of the form:

  xyz  pqr  lmn
A  1    2    NaN
B  2    3    1
C  NaN  2    NaN

Body:
Use pivot or unstack:

df = df.pivot(index='Col1',columns='Col2',values='Col3')
print (df)
Col2  lmn  pqr  xyz
Col1
A     NaN  2.0  1.0
B     1.0  3.0  2.0
C     NaN  2.0  NaN

df = df.set_index(['Col1','Col2'])['Col3'].unstack()
print (df)

Col2  lmn  pqr  xyz
Col1
A     NaN  2.0  1.0
B     1.0  3.0  2.0
C     NaN  2.0  NaN

but if:

ValueError: Index contains duplicate entries, cannot reshape

it means duplicates, need pivot_table or aggregate with groupby by mean (can be changed to sum, median), and last reshape by unstack:

print (df)
  Col1 Col2  Col3
0    A  xyz     1 <-same A, xyz
1    A  xyz     5 <-same A, xyz
2    A  pqr     2
3    B  xyz     2
4    B  pqr     3
5    B  lmn     1
6    C  pqr     2

df = df.groupby(['Col1','Col2'])['Col3'].mean().unstack()
print (df)
Col2  lmn  pqr  xyz
Col1
A     NaN  2.0  3.0 (1+5)/2 = 3
B     1.0  3.0  2.0
C     NaN  2.0  NaN

EDIT:

For check all duplicates by Col1 and Col2:

print (df[df.duplicated(subset=['Col1','Col2'], keep=False)])
  Col1 Col2  Col3
0    A  xyz     1
1    A  xyz     5

EDIT1:

If need only first row if duplicates:

df = df.groupby(['Col1','Col2'])['Col3'].first().unstack()
print (df)
Col2  lmn  pqr  xyz
Col1
A     NaN  2.0  1.0
B     1.0  3.0  2.0
C     NaN  2.0  NaN

Or better first remove duplicates by drop_duplicates and then use first or second solution:

df = df.drop_duplicates(subset=['Col1','Col2'])
df = df.pivot(index='Col1',columns='Col2',values='Col3')
print (df)
Col2  lmn  pqr  xyz
Col1
A     NaN  2.0  1.0
B     1.0  3.0  2.0
C     NaN  2.0  NaN


问:
Spring Boot bounded autoconfiguration
I am creating a custom Spring Boot starter that registers/activates an IntegrationFlow. This was originally a regular project, but 60% of the customization is done by Spring Boot properties autoconfiguration on a YAML.

My problem is that when moving it to a starter, I am fearing that my importer project overrides certain configurations so the integration won't work.

How can I solve that? Basically I'd like to avoid having to create and set manually all chain of beans and dependencies that Spring Boot does for me (resttemplate, objectmapper, jms broker) in fear of any possible existence in the importer project in the shape of a registered @Bean or a YAML property.

Ideally there would be a way to tell my starter autoconfigurer "ignore anything on the importer and use a private context with my YAML properties and the inferences as if importer did not exist which applies to the X,Y,Z beans that I really want to inject in the importer context given @Conditional clause".

答:
When running the process with your custom starter, there is a way to specify as argument the path to the properties/yml file, from which spring boot will create its context. This would assure you that the context will be created only using the file you explicitly given as input argument.

This would imply also for you to have separate full config file for your integration starter.

For a mix usage of yaml files, as far as my knowledge goes, spring boot can only reference one config file. Let me know if this information helps you, or if you could further develop your question maybe with some sample code of your starter.

Title: Spring Boot bounded autoconfiguration


问:
Create Excel Pivot Charts Or Graphs From Multiple Pivot Table Data Set
I have a data set with multiple dimensions, time range and metrics but not in a standard format to create pivot charts. My objective is to create graphs which will show the time series data of the metrics by the offer types.

I can edit and create appropriate columns and make the completely tabular but that will require some work. Is there any other way? I also have access to microstrategy.

答:
When it comes to pivot charts in Excel, one usually has to abide by the command: "Thou shalt flatten!" Pivot charts are created from memory objects call pivot caches, which contain n-dimensional cube data derived from structured data sources, such as Excel tables. The following Contextures article has a good example.

If you plan on creating pivot charts from your data, it will have to be properly structured. You will also have to transform your data from a wide to a long format, so that each data point has it's own row, with categories and values appearing in their own columns. Your input data should look something like this:

```<code>Offer Type          Metric            Quarter  Period    Value
Activation Offers   Number of offers  Q2 2016  Period 6  6
Activation Offers   Total Circulation Q2 2016  Period 6  2,020,000
...                 ...               ...      ...       ...
</code>```

I am not familiar with microstrategy; however, given the layout of the data in your example, rearranging your data should be relatively straightforward. If your outputs are in the form of pivot tables, you may need to convert them to normal ranges (see the paste special options). Note that my example structure assumes that quarterly data can be computed from the data in each period. You may have to play around with the pivot table metrics it so that it produces the figures you are looking for.

If you decide that base Excel isn't able to produce what you need, I suggest looking into Excel PowerPivot, which would allow you to construct more complex pivot tables. PowerPivot is available as a free add-in for Excel 2010 and 2013, and is included in the Pro and Enterprise versions of Excel 2016.

Body:
When it comes to pivot charts in Excel, one usually has to abide by the command: "Thou shalt flatten!" Pivot charts are created from memory objects call pivot caches, which contain n-dimensional cube data derived from structured data sources, such as Excel tables. The following Contextures article has a good example.

If you plan on creating pivot charts from your data, it will have to be properly structured. You will also have to transform your data from a wide to a long format, so that each data point has it's own row, with categories and values appearing in their own columns. Your input data should look something like this:

Offer Type          Metric            Quarter  Period    Value
Activation Offers   Number of offers  Q2 2016  Period 6  6
Activation Offers   Total Circulation Q2 2016  Period 6  2,020,000
...                 ...               ...      ...       ...

I am not familiar with microstrategy; however, given the layout of the data in your example, rearranging your data should be relatively straightforward. If your outputs are in the form of pivot tables, you may need to convert them to normal ranges (see the paste special options). Note that my example structure assumes that quarterly data can be computed from the data in each period. You may have to play around with the pivot table metrics it so that it produces the figures you are looking for.

If you decide that base Excel isn't able to produce what you need, I suggest looking into Excel PowerPivot, which would allow you to construct more complex pivot tables. PowerPivot is available as a free add-in for Excel 2010 and 2013, and is included in the Pro and Enterprise versions of Excel 2016.


问:
Swing: easiest way to align width of [dynamic][static][dynamic] components?
What is the easiest way in standard Java Swing to align three components in such a way that:

the dynamic widths of Component1 and Component3 are adjusted to be equal,

while Component2 (which is in between) has constant width?

Imagine we have some resizable JPanel (such as inside a JFrame).

Small width should look like this:

```<code>[----------------whole JPanel----------------]
[--Component1--] [Component2] [--Component3--]
</code>```

Big width should look like this:

```<code>[------------------------whole JPanel------------------------]
[------Component1------] [Component2] [------Component3------]
</code>```

Note: I just "trialed-and-errored" with GroupLayout for too long.

答:
How about the MigLayout manager? It is not a part of JRE, but is a great layout manager, which can easily produce the layout you require with less code than GridBag. Check out their demo.

Could not resist to post the totally grid bag cartoon... enjoy (:

Body:
What is the easiest way in standard Java Swing to align three components in such a way that:

the dynamic widths of Component1 and Component3 are adjusted to be equal,

while Component2 (which is in between) has constant width?

Imagine we have some resizable JPanel (such as inside a JFrame).

Small width should look like this:

[----------------whole JPanel----------------]
[--Component1--] [Component2] [--Component3--]

Big width should look like this:

[------------------------whole JPanel------------------------]
[------Component1------] [Component2] [------Component3------]

Note: I just "trialed-and-errored" with GroupLayout for too long.


问:
Syntax error in PHP login page query
I am trying to make a PHP login page that checks weather the user entered details are in the database but it returns the following error:

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access
      violation: 1064 You have an error in your SQL syntax; check the manual that
      corresponds to your MariaDB server version for the right syntax to use near
      'SLEECT * FROM users where username = NULL AND password = NULL' at line 1 in
      C:\xampp\htdocs\sign\login.php:18 Stack trace: #0
      C:\xampp\htdocs\sign\login.php(18): PDOStatement->execute() #1

      C:\xampp\htdocs\sign\login.php(31): SignIn() #2 {main} thrown in
      C:\xampp\htdocs\sign\login.php on line 18

What am I doing wrong and how can I fix it?

```<code><?php
include('connection.php');
$username =$_POST['username'];
$password = $_POST['password'];
if($username == '') {
$errmsg_arr[] = 'You must enter your Username';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'You must enter your Password';
$errflag = true;
}
function SignIn(){
global $connection;
$search = $connection->prepare("SLEECT * FROM users where username =
:username AND password = :password");
$search->bindParam(':username',$username);
$search->bindParam(':password',$password);
$result = $search->execute();
$count = $result->rowcount();
if($count> 0)
{
    $_SESSION['username'] = $_POST['username'];
    echo "welcom to the page ";
}
else{
    echo "wron email or password";
}
}
if(isset($_POST['submit']))
{
SignIn();
}
?>
</code>```

the code written in connection.php is

```<code><?php
try{
$connection = new PDO('mysql:host=localhost;dbname=signup;charset=utf8mb4',
'root', '');
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $err){
echo $err->getMessage();
die();
}
?>
</code>```

the HTML code written is

```<code><html>
<body>
<form method="POST" action="login.php">
<b>Enter your username: </b><br>
<input type="text" name="username"><br>
<b>Enter your password: </b><br>
<input type="password" name ="password"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
</code>```

答:
You get error message like this because you call variables not defined $username and $password inside SignIn() function. That's why, the query will treat them as null.

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access
    violation: 1064 You have an error in your SQL syntax; check the manual that
    corresponds to your MariaDB server version for the right syntax to use near
    'SLEECT * FROM users where username = NULL AND password = NULL' at line 1 in

You can pass it on function defenition

```<code>function SignIn($username, $password)
</code>```

Then please check the $_POST["submit"] first, then validate the username & password and call SignIn($username, $password)

```<code>if(isset($_POST['submit']))
{
    $username = $_POST['username'];
    $password = $_POST['password'];
    $errflag  = false;
    if($username == '') {
       $errmsg_arr[] = 'You must enter your Username';
       $errflag = true;
    }

    if($password == '') {
       $errmsg_arr[] = 'You must enter your Password';
       $errflag = true;
    }

    if ($errflag == false) {
       SignIn($username, $password);
    }
}
</code>```

Title: Syntax error in PHP login page query

Body:
I am trying to make a PHP login page that checks weather the user entered details are in the database but it returns the following error:

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access
      violation: 1064 You have an error in your SQL syntax; check the manual that
      corresponds to your MariaDB server version for the right syntax to use near
      'SLEECT * FROM users where username = NULL AND password = NULL' at line 1 in
      C:\xampp\htdocs\sign\login.php:18 Stack trace: #0
      C:\xampp\htdocs\sign\login.php(18): PDOStatement->execute() #1

      C:\xampp\htdocs\sign\login.php(31): SignIn() #2 {main} thrown in
      C:\xampp\htdocs\sign\login.php on line 18

What am I doing wrong and how can I fix it?

<?php
include('connection.php');
$username =$_POST['username'];
$password = $_POST['password'];
if($username == '') {
$errmsg_arr[] = 'You must enter your Username';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'You must enter your Password';
$errflag = true;
}
function SignIn(){
global $connection;
$search = $connection->prepare("SLEECT * FROM users where username =
:username AND password = :password");
$search->bindParam(':username',$username);
$search->bindParam(':password',$password);
$result = $search->execute();
$count = $result->rowcount();
if($count> 0)
{
    $_SESSION['username'] = $_POST['username'];
    echo "welcom to the page ";
}
else{
    echo "wron email or password";
}
}
if(isset($_POST['submit']))
{
SignIn();
}
?>

the code written in connection.php is

<?php
try{
$connection = new PDO('mysql:host=localhost;dbname=signup;charset=utf8mb4',
'root', '');
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $err){
echo $err->getMessage();
die();
}
?>

the HTML code written is

<form method="POST" action="login.php">
Enter your username:

<input type="text" name="username">

Enter your password:

<input type="password" name ="password">

<input type="submit" name="submit">
</form>

Body:
You get error message like this because you call variables not defined $username and $password inside SignIn() function. That's why, the query will treat them as null.

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access
    violation: 1064 You have an error in your SQL syntax; check the manual that
    corresponds to your MariaDB server version for the right syntax to use near
    'SLEECT * FROM users where username = NULL AND password = NULL' at line 1 in

You can pass it on function defenition

function SignIn($username, $password)

Then please check the $_POST["submit"] first, then validate the username & password and call SignIn($username, $password)

if(isset($_POST['submit']))
{
    $username = $_POST['username'];
    $password = $_POST['password'];
    $errflag  = false;
    if($username == '') {
       $errmsg_arr[] = 'You must enter your Username';
       $errflag = true;
    }

    if($password == '') {
       $errmsg_arr[] = 'You must enter your Password';
       $errflag = true;
    }

    if ($errflag == false) {
       SignIn($username, $password);
    }
}


问:
Javascript return value from asynchronous function

I know it's a very popular and many times answered topics, but I

 couldn't fully understand it's application in my case.

I am learning my way through Javascript, and I am stuck trying to return a value from async function. Essentially, I want my function to take a city name and return its current temperature from APIXU Weather API (https://www.apixu.com).

Then, I wanted to use this function inside my other Google API function. This function takes id of the clicked marker, finds it's city name in the array of places, and displays information in an infowindow, such as title of the place, weather of a city and  Google Streetview. My initial plan was to use getWeather function inside populateInfoWindow to find the weather of a city. Is it possible to achieve it? Because from what I understand using asynchronous function inside synchronous, will make the latest one asynchronous. Another possible route I was going to choose is to get the weather of all places in the array on document load and just take the information from the array in populateInfoWindow function. But I am afraid that this will be repetitive and unnecessary.

To your opinion, what would be the best way to accomplish it and how to avoid similar problems?

Here is the code:

```<code>//Get current forecast from weather API
        function getWeather(city) {
            var weatherAPIXU = "http://api.apixu.com/v1/current.json?key=XXXXXXXXXXXXXXX&q=" + city;
            $.getJSON(weatherAPIXU, function(data) {
                var forecast = data.current.temp_c;
                var curWeather = forecast + '° C';
                 return curWeather
            });
        }

// Return a city name that matches a marker id
function getCityName(locations, marker) {
    for (var i = 0, iLen = locations.length; i < iLen; i++) {
        if (locations[i].id == marker.id) return locations[i].city;
    }
}

// This function populates the infowindow when the marker is clicked. It'll only allow
// one infowindow which will open at the marker that is clicked, and populate based
// on that markers position.
function populateInfoWindow(marker, infowindow) {
    // Check to make sure the infowindow is not already opened on this marker.
    if (infowindow.marker != marker) {
        // Clear the infowindow content to give the streetview time to load.
        infowindow.setContent('');
        infowindow.marker = marker;
        // Make sure the marker property is cleared if the infowindow is closed.
        infowindow.addListener('closeclick', function() {
            infowindow.marker = null;
        });
        var streetViewService = new google.maps.StreetViewService();
        var radius = 50;
        var city = getCityName(locations, marker);
        console.log(city);
        var weatherInCity = getWeather(city);
        console.log(weatherInCity);
        // In case the status is OK, which means the pano was found, compute the
        // position of the streetview image, then calculate the heading, then get a
        // panorama from that and set the options
        var getStreetView = function(data, status) {
            if (status == google.maps.StreetViewStatus.OK) {
                var nearStreetViewLocation = data.location.latLng;
                var heading = google.maps.geometry.spherical.computeHeading(
                    nearStreetViewLocation, marker.position);
                infowindow.setContent('<div>' + marker.title + '' + weatherInCity +
                    '</div><div id="pano"></div>');
                var panoramaOptions = {
                    position: nearStreetViewLocation,
                    pov: {
                        heading: heading,
                        pitch: 30
                    }
                };
                var panorama = new google.maps.StreetViewPanorama(
                    document.getElementById('pano'),
                    panoramaOptions);
            } else {
                infowindow.setContent('<div>' + marker.title +
                    '</div>' +
                    '<div>No Street View Found</div>');
            }
        };
        // Use streetview service to get the closest streetview image within
        // 50 meters of the markers position
        streetViewService.getPanoramaByLocation(marker.position,
            radius, getStreetView);
        // Open the infowindow on the correct marker.
        infowindow.open(map, marker);
    }
}
</code>```

答:
You cannot return object like this as it is callback function. You can write you logic inside the callback function.

```<code>function getWeather() {
var city = $("#txtCity").val();
    var weatherAPIXU = "http://api.apixu.com/v1/current.json?key=XXXXXXX&q=" + city;
    $.getJSON(weatherAPIXU, function(data) {
        var forecast = data.current.temp_c;
        var curWeather = forecast + '° C';
        $("#lblTemp").html(curWeather)

    });
</code>```

The Other option which is not recommended is declare a global variable and assign the return value to the global variable.

```<code>var CurrentWeather = null
function getWeather(city) {

var weatherAPIXU = "http://api.apixu.com/v1/current.json?key=XXXXX&q=" + city;
$.getJSON(weatherAPIXU, function(data) {
    var forecast = data.current.temp_c;
    var curWeather = forecast + '° C';
    $("#lblTemp").html(curWeather)
     CurrentWeather = curWeather;
});
</code>```

Body:
I know it's a very popular and many times answered topics, but I

 couldn't fully understand it's application in my case.

I am learning my way through Javascript, and I am stuck trying to return a value from async function. Essentially, I want my function to take a city name and return its current temperature from APIXU Weather API (https://www.apixu.com).

Then, I wanted to use this function inside my other Google API function. This function takes id of the clicked marker, finds it's city name in the array of places, and displays information in an infowindow, such as title of the place, weather of a city and  Google Streetview. My initial plan was to use getWeather function inside populateInfoWindow to find the weather of a city. Is it possible to achieve it? Because from what I understand using asynchronous function inside synchronous, will make the latest one asynchronous. Another possible route I was going to choose is to get the weather of all places in the array on document load and just take the information from the array in populateInfoWindow function. But I am afraid that this will be repetitive and unnecessary.

To your opinion, what would be the best way to accomplish it and how to avoid similar problems?

Here is the code:

//Get current forecast from weather API
        function getWeather(city) {
            var weatherAPIXU = "http://api.apixu.com/v1/current.json?key=XXXXXXXXXXXXXXX&q=" + city;
            $.getJSON(weatherAPIXU, function(data) {
                var forecast = data.current.temp_c;
                var curWeather = forecast + '° C';
                 return curWeather
            });
        }

// Return a city name that matches a marker id
function getCityName(locations, marker) {
    for (var i = 0, iLen = locations.length; i < iLen; i++) {
        if (locations[i].id == marker.id) return locations[i].city;
    }
}

// This function populates the infowindow when the marker is clicked. It'll only allow
// one infowindow which will open at the marker that is clicked, and populate based
// on that markers position.
function populateInfoWindow(marker, infowindow) {
    // Check to make sure the infowindow is not already opened on this marker.
    if (infowindow.marker != marker) {
        // Clear the infowindow content to give the streetview time to load.
        infowindow.setContent('');
        infowindow.marker = marker;
        // Make sure the marker property is cleared if the infowindow is closed.
        infowindow.addListener('closeclick', function() {
            infowindow.marker = null;
        });
        var streetViewService = new google.maps.StreetViewService();
        var radius = 50;
        var city = getCityName(locations, marker);
        console.log(city);
        var weatherInCity = getWeather(city);
        console.log(weatherInCity);
        // In case the status is OK, which means the pano was found, compute the
        // position of the streetview image, then calculate the heading, then get a
        // panorama from that and set the options
        var getStreetView = function(data, status) {
            if (status == google.maps.StreetViewStatus.OK) {
                var nearStreetViewLocation = data.location.latLng;
                var heading = google.maps.geometry.spherical.computeHeading(
                    nearStreetViewLocation, marker.position);
                infowindow.setContent('
' + marker.title + '' + weatherInCity +
                    '

');
                var panoramaOptions = {
                    position: nearStreetViewLocation,
                    pov: {
                        heading: heading,
                        pitch: 30
                    }
                };
                var panorama = new google.maps.StreetViewPanorama(
                    document.getElementById('pano'),
                    panoramaOptions);
            } else {
                infowindow.setContent('
' + marker.title +
                    '
' +
                    '
No Street View Found
');
            }
        };
        // Use streetview service to get the closest streetview image within
        // 50 meters of the markers position
        streetViewService.getPanoramaByLocation(marker.position,
            radius, getStreetView);
        // Open the infowindow on the correct marker.
        infowindow.open(map, marker);
    }
}

Body:
You cannot return object like this as it is callback function. You can write you logic inside the callback function.

function getWeather() {
var city = $("#txtCity").val();
    var weatherAPIXU = "http://api.apixu.com/v1/current.json?key=XXXXXXX&q=" + city;
    $.getJSON(weatherAPIXU, function(data) {
        var forecast = data.current.temp_c;
        var curWeather = forecast + '° C';
        $("#lblTemp").html(curWeather)

    });

The Other option which is not recommended is declare a global variable and assign the return value to the global variable.

var CurrentWeather = null
function getWeather(city) {

var weatherAPIXU = "http://api.apixu.com/v1/current.json?key=XXXXX&q=" + city;
$.getJSON(weatherAPIXU, function(data) {
    var forecast = data.current.temp_c;
    var curWeather = forecast + '° C';
    $("#lblTemp").html(curWeather)
     CurrentWeather = curWeather;
});


问:
How to use slash ('/') in Kibana Discovery?
I'm testing ELK stack for nginx-access logs. It looks good except I have not found a way to search records in Kibana Discovery (v5.3.2) with a path that start with "/test/a". Search works if I remove slashes, but in this case, I get what I don't need - "/ololo/ololo?test=1"

I tried different requests:

```<code>path:/\/test\/a/
path:/\\/test\\/a/
path:"/test/a"
path:"\/test\/a"
path:"\\/test\\/a"
</code>```

but nothing works as I expect.

Records:

```<code>[
{
    ...
    "path": "/test/a1"
    ...
},
{
    ...
    "path": "/test/a2"
    ...
},
{
    ...
    "path": "/ololo/ololo?test=1"
    ...
},
]
</code>```

Mapping:

```<code>"path": {
  "type": "string",
  "index": "analyzed",
},
</code>```

Is there any way to search using slashes as part of pattern?

Update:

These patterns do not work too:

```<code>path:/.*\/test\/a.*/
path:/[\/]test[\/]a/
</code>```

答:
You need to change the mapping of the path field to not be analyzed, otherwise the slashes will not be indexed.

The mapping should be like this:

```<code>"path": {
  "type": "string",
  "index": "not_analyzed",    <--- change this
},
</code>```

Note that you need to delete your index and re-create it with the proper mapping in order for this to work.

After that you'll be able to search using the following query path:"/test/a"

Body:
I'm testing ELK stack for nginx-access logs. It looks good except I have not found a way to search records in Kibana Discovery (v5.3.2) with a path that start with "/test/a". Search works if I remove slashes, but in this case, I get what I don't need - "/ololo/ololo?test=1"

I tried different requests:

path:/\/test\/a/
path:/\\/test\\/a/
path:"/test/a"
path:"\/test\/a"
path:"\\/test\\/a"

but nothing works as I expect.

Records:

[
{
    ...
    "path": "/test/a1"
    ...
},
{
    ...
    "path": "/test/a2"
    ...
},
{
    ...
    "path": "/ololo/ololo?test=1"
    ...
},
]

Mapping:

"path": {
  "type": "string",
  "index": "analyzed",
},

Is there any way to search using slashes as part of pattern?

Update:

These patterns do not work too:

path:/.*\/test\/a.*/
path:/[\/]test[\/]a/

Body:
You need to change the mapping of the path field to not be analyzed, otherwise the slashes will not be indexed.

The mapping should be like this:

"path": {
  "type": "string",
  "index": "not_analyzed",    <--- change this
},

Note that you need to delete your index and re-create it with the proper mapping in order for this to work.

After that you'll be able to search using the following query path:"/test/a"


问:
Java inheritance - Two classes that use the same methods
I have two classes, ObjectA and ObjectB that both extend the same class MasterObject. I also have an interface which contains a method that I want both ObjectA and ObjectB to implement. This method is not found within MasterObject. I then have a class which has a field of type MasterObject and want to access the methods within ObjectA and ObjectB. Is this possible without casting? Here is some code that I have.

In addition, I am unable to alter the MasterObject class.

```<code>public interface MyInterface{
    void doSomething();
}

class ObjectA extends MasterObject implements MyInterface {

    @Override
    public void doSomething(){
        //...
    }
}

class ObjectB extends MasterObject implements MyInterface {
    @Override
    public void doSomething(){
        //...
    }
}

class Main {
    MasterObject mObj;

    public void method1() {
        mObj = new ObjectA();
        mObj.doSomething();
    }

    public void method2() {
        mObj = new ObjectB();
        mObj.doSomething(); //runs code from ObjectB class
    }
}
</code>```

Right now this is obviously throwing some compiler issues. (Cannot resolve method doSomething()).

Casting like so: ((ObjectA) mObj).doSomething(); seems to work, but is there another way to do this without casting? Anything cleaner?

答:
You have a few options here and some have already been mentioned. You've already mentioned that you can't add the interface to MasterObject and that the interaction is more complicated than just doSomething. Any other constraints will likely determine which is best for you.

The first option is to do like Craig suggested and create the intermediate AbstractMasterObject to extend MasterObject and implement MyInterface. This is a quick and easy way to have a single reference that's both a MasterObject and MyInterface instance. The downside is that Main now has to use AbstractMasterObject instead of MasterObject. So it can't use any other subclasses of MasterObject. That may not be a problem at all or it may be a complete deal-breaker. Realistically, it's somewhere in between.

Another option is to use composition instead of inheritance. So ObjectA and ObjectB each have an instance of MasterObject instead of extending it. Then they use that reference for access to MasterClass behavior (For brevity, I'm just showing ObjectA):

```<code>class ObjectA implements MyInterface {

     private masterObject masterObject;

     public ObjectA(MasterObject masterObject){
       this.masterObject = masterObject;
    }
    @Override
    public void doSomething(){ /* Implementation */ }

 }
</code>```

From here, there are a few different strategies to incorporate this into Main. You could have a reference to a MasterClass in Main and pass that to the ObjectA constructor. Then maintain both a MasterClass and MyInterface reference:

```<code>class Main {
   MyInterface myInterface;
   MasterObject masterObject;

   public void method1(){
      masterObject = new MasterObject();
      myInterface = new ObjectA(masterObject);

      myInterface.doSomething();
      masterObject.someMasterObjectMethod();

   }
}
</code>```

This approach would only work if ObjectA neither overrides MasterObject methods nor accesses any protected members. It could also lead to confusion having a reference to the same MasterObject in both Main and ObjectA. If both classes can change the state of MasterObject then you might end up with some tricky bugs. On the other hand, if none of these are a concern then this may be a good way. It adds MyInterface to Main without disrupting MasterObject and it uses MasterObject indirectly to implement MyInterface.

Or you could hide MasterObject entirely from Main and interact only through MyInterface. To do this, you could simply at getMasterObject to MyInterface. Or you could add methods to MyInterface that specifically pertain to how Main interacts with it. I think an approach like this is cleanest, but it involves changing the most code. If this is mostly new development, then it may be worth the effort to refactor. If it's older code, then I'd favor a less invasive approach.

Another option approaches this from a slightly different direction. You use the classes exactly as you have them defined. The difference is that Main has both a MasterObject and MyInterface reference pointing to the same instance:

```<code>class Main {

   private MasterObject masterObject;
   private MyInterface myInterface;

   public void method1(){

       ObjectA objectA = new ObjectA();
       masterObject = objectA; // Legal because ObjectA extends MasterObject
       myInterface = objectA; // Legal because ObjectA implements MyInterface

       myInterface.doSomething(); // This does ObjectA's implementation
       masterObject.someMasterObjectMethod();

   }
}
</code>```

So to Main, it's completely coincidental that the same instance performs as MyInterface and MasterObject. I think this approach would be best if this is legacy code because it's the least invasive. If this is relatively new code, then I'd consider the other strategies before resorting to something like this. There are still other approaches, but I think this should be a good overview. No matter what, you should step back and think about what the relationships among each of these classes really are. That should help point you in the right direction.

Body:
I have two classes, ObjectA and ObjectB that both extend the same class MasterObject. I also have an interface which contains a method that I want both ObjectA and ObjectB to implement. This method is not found within MasterObject. I then have a class which has a field of type MasterObject and want to access the methods within ObjectA and ObjectB. Is this possible without casting? Here is some code that I have.

In addition, I am unable to alter the MasterObject class.

public interface MyInterface{
    void doSomething();
}

class ObjectA extends MasterObject implements MyInterface {

    @Override
    public void doSomething(){
        //...
    }
}

class ObjectB extends MasterObject implements MyInterface {
    @Override
    public void doSomething(){
        //...
    }
}

class Main {
    MasterObject mObj;

    public void method1() {
        mObj = new ObjectA();
        mObj.doSomething();
    }

    public void method2() {
        mObj = new ObjectB();
        mObj.doSomething(); //runs code from ObjectB class
    }
}

Right now this is obviously throwing some compiler issues. (Cannot resolve method doSomething()).

Casting like so: ((ObjectA) mObj).doSomething(); seems to work, but is there another way to do this without casting? Anything cleaner?

Body:
You have a few options here and some have already been mentioned. You've already mentioned that you can't add the interface to MasterObject and that the interaction is more complicated than just doSomething. Any other constraints will likely determine which is best for you.

The first option is to do like Craig suggested and create the intermediate AbstractMasterObject to extend MasterObject and implement MyInterface. This is a quick and easy way to have a single reference that's both a MasterObject and MyInterface instance. The downside is that Main now has to use AbstractMasterObject instead of MasterObject. So it can't use any other subclasses of MasterObject. That may not be a problem at all or it may be a complete deal-breaker. Realistically, it's somewhere in between.

Another option is to use composition instead of inheritance. So ObjectA and ObjectB each have an instance of MasterObject instead of extending it. Then they use that reference for access to MasterClass behavior (For brevity, I'm just showing ObjectA):

class ObjectA implements MyInterface {

     private masterObject masterObject;

     public ObjectA(MasterObject masterObject){
       this.masterObject = masterObject;
    }
    @Override
    public void doSomething(){ /* Implementation */ }

 }

From here, there are a few different strategies to incorporate this into Main. You could have a reference to a MasterClass in Main and pass that to the ObjectA constructor. Then maintain both a MasterClass and MyInterface reference:

class Main {
   MyInterface myInterface;
   MasterObject masterObject;

   public void method1(){
      masterObject = new MasterObject();
      myInterface = new ObjectA(masterObject);

      myInterface.doSomething();
      masterObject.someMasterObjectMethod();

   }
}

This approach would only work if ObjectA neither overrides MasterObject methods nor accesses any protected members. It could also lead to confusion having a reference to the same MasterObject in both Main and ObjectA. If both classes can change the state of MasterObject then you might end up with some tricky bugs. On the other hand, if none of these are a concern then this may be a good way. It adds MyInterface to Main without disrupting MasterObject and it uses MasterObject indirectly to implement MyInterface.

Or you could hide MasterObject entirely from Main and interact only through MyInterface. To do this, you could simply at getMasterObject to MyInterface. Or you could add methods to MyInterface that specifically pertain to how Main interacts with it. I think an approach like this is cleanest, but it involves changing the most code. If this is mostly new development, then it may be worth the effort to refactor. If it's older code, then I'd favor a less invasive approach.

Another option approaches this from a slightly different direction. You use the classes exactly as you have them defined. The difference is that Main has both a MasterObject and MyInterface reference pointing to the same instance:

class Main {

   private MasterObject masterObject;
   private MyInterface myInterface;

   public void method1(){

       ObjectA objectA = new ObjectA();
       masterObject = objectA; // Legal because ObjectA extends MasterObject
       myInterface = objectA; // Legal because ObjectA implements MyInterface

       myInterface.doSomething(); // This does ObjectA's implementation
       masterObject.someMasterObjectMethod();

   }
}

So to Main, it's completely coincidental that the same instance performs as MyInterface and MasterObject. I think this approach would be best if this is legacy code because it's the least invasive. If this is relatively new code, then I'd consider the other strategies before resorting to something like this. There are still other approaches, but I think this should be a good overview. No matter what, you should step back and think about what the relationships among each of these classes really are. That should help point you in the right direction.


问:
Android: Capturing the return of an activity
I have a question regarding launching new activities. It boils down to this.
I have 3 tabs on a view

```<code>A) contains gMap activity
 B) camera activity
 C) some random text fields.
</code>```

Requirement is that the application runs in Portrait mode.

All 3 tabs work as expected w/ the exception of the Camera Preview Surface (B). It is rotated 90 degrees. They only way to make it correct is to set the app to landscape which throws all my tabs around, and is pretty much unworkable.

My solution is this : replace

my camera activity with a regular activity that is empty w/ the exception of

```<code>Intent i = new Intent(this,CameraActivity.class);
    startActivity(i);
</code>```

This launches my CameraActivity. And that works fine. I had to do a linear layout and include 3 images that look like real tabs, so I can try and mimic the operation of the tabs while rotating the screen to landscape and keep the visuals as portrait.
The user can click one of the images(buttons) to display the next tab. This is my issue. It should exit my 'camera activity' returning to the 'blank activity' in a tab, where it should be interpreted to click the desiered tab from my image.

The main thing is, when it returns, it returns to a blank (black) page under a tab (because it is 'empty'). How can I capture the return event back to the page that called the activity, and then see what action they performed?

I can set an onclicklistener where I can respond to the fake tabs (images) being clicked to exit out of the camera activity. On exit, the tab should update so that is where you return. any Suggestions?

Thanks,

答:
I'll focus on answering how to resolve your workround so that it behaves as you want.

To capture actions performed on one Activity within another requires three steps.

Launch the secondary Activity (your 'camera Activity') as a subactivity by using startActivityForResult instead of startActivity.

```<code>Intent i = new Intent(this,CameraActivity.class);
startActivityForResult(i, STATIC_INTEGER_VALUE);
</code>```

Within the subactivity (camera Activity), rather than just closing the Activity when a user clicks the different tab image, you need to create a new Intent and include the index of the tab to display when you return to the parent app using the extras bundle. To pass it back to the parent call setResult before calling finish to close the camera Activity.

```<code>resultIntent = new Intent(null);
resultIntent.putExtra(PUBLIC_STATIC_STRING_IDENTIFIER, tabIndexValue);
setResult(Activity.RESULT_OK, resultIntent);
finish();
</code>```

The final step is in the calling Activity, override onActivityResult to listen for callbacks from the camera Activity. Get the extra from the returned Intent to determine the index of the tab you should be displaying.

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  switch(requestCode) {
    case (STATIC_INTEGER_VALUE) : {
      if (resultCode == Activity.RESULT_OK) {
      int tabIndex = data.getIntExtra(PUBLIC_STATIC_STRING_IDENTIFIER);
      // TODO Switch tabs using the index.
      }
      break;
    }
  }
}
</code>```

Body:
I have a question regarding launching new activities. It boils down to this.
I have 3 tabs on a view

A) contains gMap activity
 B) camera activity
 C) some random text fields.

Requirement is that the application runs in Portrait mode.

All 3 tabs work as expected w/ the exception of the Camera Preview Surface (B). It is rotated 90 degrees. They only way to make it correct is to set the app to landscape which throws all my tabs around, and is pretty much unworkable.

My solution is this : replace

my camera activity with a regular activity that is empty w/ the exception of

Intent i = new Intent(this,CameraActivity.class);
    startActivity(i);

This launches my CameraActivity. And that works fine. I had to do a linear layout and include 3 images that look like real tabs, so I can try and mimic the operation of the tabs while rotating the screen to landscape and keep the visuals as portrait.
The user can click one of the images(buttons) to display the next tab. This is my issue. It should exit my 'camera activity' returning to the 'blank activity' in a tab, where it should be interpreted to click the desiered tab from my image.

The main thing is, when it returns, it returns to a blank (black) page under a tab (because it is 'empty'). How can I capture the return event back to the page that called the activity, and then see what action they performed?

I can set an onclicklistener where I can respond to the fake tabs (images) being clicked to exit out of the camera activity. On exit, the tab should update so that is where you return. any Suggestions?

Thanks,

Body:
I'll focus on answering how to resolve your workround so that it behaves as you want.

To capture actions performed on one Activity within another requires three steps.

Launch the secondary Activity (your 'camera Activity') as a subactivity by using startActivityForResult instead of startActivity.

Intent i = new Intent(this,CameraActivity.class);
startActivityForResult(i, STATIC_INTEGER_VALUE);

Within the subactivity (camera Activity), rather than just closing the Activity when a user clicks the different tab image, you need to create a new Intent and include the index of the tab to display when you return to the parent app using the extras bundle. To pass it back to the parent call setResult before calling finish to close the camera Activity.

resultIntent = new Intent(null);
resultIntent.putExtra(PUBLIC_STATIC_STRING_IDENTIFIER, tabIndexValue);
setResult(Activity.RESULT_OK, resultIntent);
finish();

The final step is in the calling Activity, override onActivityResult to listen for callbacks from the camera Activity. Get the extra from the returned Intent to determine the index of the tab you should be displaying.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  switch(requestCode) {
    case (STATIC_INTEGER_VALUE) : {
      if (resultCode == Activity.RESULT_OK) {
      int tabIndex = data.getIntExtra(PUBLIC_STATIC_STRING_IDENTIFIER);
      // TODO Switch tabs using the index.
      }
      break;
    }
  }
}

OwnerDisplayName: Reto Meier

LastEditorDisplayName: Reto Meier


问:
How to copy fields from one structure to another
I have several input structures which I need to convert to some other structure so I can pass it to my method.

```<code>struct Source1
{
    public float x1;
    public float x2;
    public float x3;
}

struct Source2
{
    public float x1;
    public float x3;
    public float x2;
    public float x4;
}

struct Target
{
    public float x1;
    public float x2;
    public float x3;
}
</code>```

I am sure that source structure has required field (type and name is what matters) but that field's offset is unknown. Also source structure might contain some extra fields that I don't need.

How do I copy required fields from source structure to target structure. I need to do it as fast as possible.

In C there is a very simple recipe for that kind of problems.

```<code>#define COPY(x, y) \
{\
x.x1 = y.x1;\
x.x2 = y.x2;\
x.x3 = y.x3;\
}
</code>```

I was thinking about getting a collection of fields and then get field's value using its name as a key but it looks like slow solution to me.

答:
Have a squiz at https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-implement-user-defined-conversions-between-structs .

It details the use of implicit operators which are one approach to consider.

Some example code:

```<code>using System;

namespace Test
{
    struct Source1
    {
        public float x1;
        public float x2;
        public float x3;

        public static implicit operator Target(Source1 value)
        {
            return new Target() { x1 = value.x1, x2 = value.x2, x3 = value.x3 };
        }
    }

    struct Target
    {
        public float x1;
        public float x2;
        public float x3;
    }

    public class Program
    {
        static void Main(string[] args)
        {
            var source = new Source1() { x1 = 1, x2 = 2, x3 = 3 };
            Target target = source;

            Console.WriteLine(target.x2);

            Console.ReadLine();
        }
    }
}
</code>```

Another alternative is using AutoMapper. Performance will be slower though.

Body:
I have several input structures which I need to convert to some other structure so I can pass it to my method.

struct Source1
{
    public float x1;
    public float x2;
    public float x3;
}

struct Source2
{
    public float x1;
    public float x3;
    public float x2;
    public float x4;
}

struct Target
{
    public float x1;
    public float x2;
    public float x3;
}

I am sure that source structure has required field (type and name is what matters) but that field's offset is unknown. Also source structure might contain some extra fields that I don't need.

How do I copy required fields from source structure to target structure. I need to do it as fast as possible.

In C there is a very simple recipe for that kind of problems.

#define COPY(x, y) \
{\
x.x1 = y.x1;\
x.x2 = y.x2;\
x.x3 = y.x3;\
}

I was thinking about getting a collection of fields and then get field's value using its name as a key but it looks like slow solution to me.

Body:
Have a squiz at https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-implement-user-defined-conversions-between-structs .

It details the use of implicit operators which are one approach to consider.

Some example code:

using System;

namespace Test
{
    struct Source1
    {
        public float x1;
        public float x2;
        public float x3;

        public static implicit operator Target(Source1 value)
        {
            return new Target() { x1 = value.x1, x2 = value.x2, x3 = value.x3 };
        }
    }

    struct Target
    {
        public float x1;
        public float x2;
        public float x3;
    }

    public class Program
    {
        static void Main(string[] args)
        {
            var source = new Source1() { x1 = 1, x2 = 2, x3 = 3 };
            Target target = source;

            Console.WriteLine(target.x2);

            Console.ReadLine();
        }
    }
}

Another alternative is using AutoMapper. Performance will be slower though.


问:
Redirecttion error in .htaccess
I have this in my .htaccess file:

```<code>RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
</code>```

It should work fine but give me error

http://www.website.com/public_html/
Not Found

The requested URL /public_html/ was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an Error Document to handle the request.

答:
Force www:

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]
</code>```

Title: Redirecttion error in .htaccess

Body:
I have this in my .htaccess file:

RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

It should work fine but give me error

http://www.website.com/public_html/
Not Found

The requested URL /public_html/ was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an Error Document to handle the request.

Body:
Force www:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]


问:
PyMC installation error with pip
I am attempting to install PyMC using pip install pymc. I believe this command should install PyMC 2.3.6.

PyMC has a few dependencies, which I have in my PATH. I am running OSX 10.11.2 and my PATH includes Python 2.7.13, NumPy 1.12.0, Matplotlib 2.0.0, gcc, and gfortran.

Python (including pip) was installed using Homebrew. NumPy and Matplotlib were installed using pip. The gfortran compiler was downloaded and installed from the GCC Wiki for the purpose of this installation.

Executing pip install pymc yielded lots of output including the following lines.

```<code>Collecting pymc
  Using cached pymc-2.3.6.tar.gz
    Complete output from command python setup.py egg_info:
    running egg_info
    running build_src
    build_src
    building extension "pymc.flib" sources
    f2py options: ['skip:ppnd7']
    f2py:> build/src.macosx-10.11-x86_64-2.7/pymc/flibmodule.c
    creating build
    creating build/src.macosx-10.11-x86_64-2.7
    creating build/src.macosx-10.11-x86_64-2.7/pymc
    IOError: [Errno 2] No such file or directory: 'skip:ppnd7'. Skipping file "skip:ppnd7".
    updatevars:gradlike: attempt to change 'dimension(nx)' to 'dimension(na)'. Ignoring.
    updatevars:gradlike: attempt to change 'dimension(nx)' to 'dimension(nb)'. Ignoring.
    updatevars:gradlike: attempt to change 'dimension (nmu)' to 'dimension(nmu)'. Ignoring.
    updatevars:gradlike: attempt to change 'dimension (na)' to 'dimension(na)'. Ignoring.
    rmbadname1: Replacing "index" with "index_bn".
    Reading fortran codes...
        Reading file 'pymc/flib.f' (format:fix,strict)
    Line #34 in pymc/flib.f:"      PARAMETER (infinity = 1.7976931348623157d308)"
        get_parameters: got "unexpected EOF while parsing (<string>, line 0)" on ''
</code>```

...

```<code>Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/private/var/folders/2f/cr97n5v93mn04c3qbqd7r3q40000gn/T/pip-build-6Zmgcz/pymc/setup.py", line 124, in <module>
    **(config_dict))
  File "/usr/local/lib/python2.7/site-packages/numpy/distutils/core.py", line 169, in setup
    return old_setup(**new_attr)
</code>```

...

```<code>    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/2f/cr97n5v93mn04c3qbqd7r3q40000gn/T/pip-build-6Zmgcz/pymc/
</code>```

As suggested in these two pip installation threads about egg_info errors [1, 2], I ran pip install —upgrade setuptools and pip install ez_setup. Once these items were installed I ran into the same types of errors pasted above.

As noted in other package installation threads, I am willing to use conda to install PyMC if I cannot resolve these issues. However, I'd like to investigate this installation issue first.

Would anyone happen to know what my issue is here? Might there be some steps I can take to successfully install PyMC using pip?

答:
I also met this problem while trying to install pymc from pip or source code, but I found a solution that might be useful.
The reason that causes the problem might be the file setup.py, in which the script check the compile env. I didn't read the code very carefully, but in the function build_ext() I think the codes first check whether some compile environments have already been installed into OS. If installed, the script will use them as defaults; if not, use ones in somewhere else (the comment says 'from netlib sources').

I infer the problem is caused by the compile environments that have already been installed in the OS, so I modify the file setup.py to skip this part of codes, and let the script use the netlib source. Then I run sudo python setup.py install. There are some error and warning messages, but the folder 'pymc' emerges in python library, and some simple test codes run successfully.

Title: PyMC installation error with pip

Body:
I am attempting to install PyMC using pip install pymc. I believe this command should install PyMC 2.3.6.

PyMC has a few dependencies, which I have in my PATH. I am running OSX 10.11.2 and my PATH includes Python 2.7.13, NumPy 1.12.0, Matplotlib 2.0.0, gcc, and gfortran.

Python (including pip) was installed using Homebrew. NumPy and Matplotlib were installed using pip. The gfortran compiler was downloaded and installed from the GCC Wiki for the purpose of this installation.

Executing pip install pymc yielded lots of output including the following lines.

Collecting pymc
  Using cached pymc-2.3.6.tar.gz
    Complete output from command python setup.py egg_info:
    running egg_info
    running build_src
    build_src
    building extension "pymc.flib" sources
    f2py options: ['skip:ppnd7']
    f2py:> build/src.macosx-10.11-x86_64-2.7/pymc/flibmodule.c
    creating build
    creating build/src.macosx-10.11-x86_64-2.7
    creating build/src.macosx-10.11-x86_64-2.7/pymc
    IOError: [Errno 2] No such file or directory: 'skip:ppnd7'. Skipping file "skip:ppnd7".
    updatevars:gradlike: attempt to change 'dimension(nx)' to 'dimension(na)'. Ignoring.
    updatevars:gradlike: attempt to change 'dimension(nx)' to 'dimension(nb)'. Ignoring.
    updatevars:gradlike: attempt to change 'dimension (nmu)' to 'dimension(nmu)'. Ignoring.
    updatevars:gradlike: attempt to change 'dimension (na)' to 'dimension(na)'. Ignoring.
    rmbadname1: Replacing "index" with "index_bn".
    Reading fortran codes...
        Reading file 'pymc/flib.f' (format:fix,strict)
    Line #34 in pymc/flib.f:"      PARAMETER (infinity = 1.7976931348623157d308)"
        get_parameters: got "unexpected EOF while parsing (<string>, line 0)" on ''

...

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/private/var/folders/2f/cr97n5v93mn04c3qbqd7r3q40000gn/T/pip-build-6Zmgcz/pymc/setup.py", line 124, in <module>
    **(config_dict))
  File "/usr/local/lib/python2.7/site-packages/numpy/distutils/core.py", line 169, in setup
    return old_setup(**new_attr)

...

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/2f/cr97n5v93mn04c3qbqd7r3q40000gn/T/pip-build-6Zmgcz/pymc/

As suggested in these two pip installation threads about egg_info errors [1, 2], I ran pip install —upgrade setuptools and pip install ez_setup. Once these items were installed I ran into the same types of errors pasted above.

As noted in other package installation threads, I am willing to use conda to install PyMC if I cannot resolve these issues. However, I'd like to investigate this installation issue first.

Would anyone happen to know what my issue is here? Might there be some steps I can take to successfully install PyMC using pip?


答: The root ispublic_html so www.website.com goes to that folder as the document root.

Title: Redirecttion error in .htaccess


答:
DateTime.Parse("01/01 2010");
or use
DateTime.TryParse
if you aren't sure it converts every time, ie. not always a date, but sometimes blank.

Body:
I am  trying  to  convert from string to DataTime but an an error occurs.
I am using  VS 2003, .NET Framework 1.1

DateTime dt = Convert.ToDateTime("11/23/2010");
string s2 = dt.ToString("dd-MM-yyyy");
DateTime dtnew = Convert.ToString(s2);

Cannot implicitly convert type 'string' to 'System.DateTime'

Can any one  help me  me  with the  syntax  how  to  solve the error.


问:
You can't open the application "AppceleratorStudio" because it is not responding
I was unable to open my AppceleratorStudio.

When I click on AppceleratorStudio icon in mac system, I am getting below message

"You can't open the application AppceleratorStudio because it is not responding."

Can any one help me out how to resolve it?

Here is my environments:

Operating System           = Mac OS X 10.11

Node.js Version             = 0.12.7

npm Version                 = 2.11.3

Titanium CLI Version          = 5.0.5

Titanium Version              = 5.1.1.GA

Error Image:

答:
Try:

```<code> % killall Dock
 % killall Finder
 % sudo killall launchservicesd
</code>```

This will help you.

Body:
Try:

 % killall Dock
 % killall Finder
 % sudo killall launchservicesd

This will help you.


问:
How can I add font awesome icons into Custom Post Type UI Menu Icon area?
I want to add font awesome icons into Custom Post Type UI Menu Icon area but I couldn't add. How can I do any idea, guys? Thank you.

答:
In Custom Post type plugin, You can not add font awesome icons. You must be use dashicon class name or icon image url.

Ref. for dashicon class - https://developer.wordpress.org/resource/dashicons/

you can download icon from different different website and use it.
Ref. - http://www.flaticon.com/packs/font-awesome.

I hope it's usefull to you.


问:
biopython FeatureLocation comparison
I am using biopython to complete a simple task: from a specific genebank fill, extract a gene ID and related information into a table.

When I was trying to compare if the Seq.SeqFeature.SeqFeature.location from different SeqFeature, it gives me False every time. Even in the situation below:

```<code>    from Bio.SeqFeature import FeatureLocation
    location1 = FeatureLocation(0,0,strand = 1)
    location2 = FeatureLocation(0,0,strand = 1)
    print(location1 == location2) # will print False
</code>```

Only this will give me a desired result:

```<code>    print(location1.start == location2.start and location1.end == location2.end and location1.strand == location2.strand) # will print True.
</code>```

The problem was solved like this, but I am still wandering whether this is by design for some reason or the comparison method just haven't been built in yet.

Below are the process of why I come to this problem:

First I only extracted feat.type == 'CDS' information from genbank file, and found
all pseudo genes are lost.

Then I came up with the idea by recording the information in
feat.type == 'gene' and then look for either 'CDS' or
'misc_feature' to record more information for this gene.

This creates the need of confirming the 'CDS' or 'misc_feature'
is annotated at the same location in case there is multiple
'misc_feature' annotating some domains of the same gene.

答:
I am still wandering whether this is by design for some reason or the
  comparison method just haven't been built in yet.

The answer appears to be the latter.  As far as I can tell, an __eq__ method for FeatureLocation was supposed to be added in 2011 but didn't make it in.  Even other Biopython objects note the lack of ability to compare FeatureLocation objects in their source code comments.

However, it's in the source code for the in progress, not yet released Biopython 1.70

The only difference between the upcoming implementation and yours is comparison of the ref and ref_db fields which default to None, so if you're not using them, no problem.

For more background information, see pull request 1309.

Title: biopython FeatureLocation comparison

Body:
I am using biopython to complete a simple task: from a specific genebank fill, extract a gene ID and related information into a table.

When I was trying to compare if the Seq.SeqFeature.SeqFeature.location from different SeqFeature, it gives me False every time. Even in the situation below:

    from Bio.SeqFeature import FeatureLocation
    location1 = FeatureLocation(0,0,strand = 1)
    location2 = FeatureLocation(0,0,strand = 1)
    print(location1 == location2) # will print False

Only this will give me a desired result:

    print(location1.start == location2.start and location1.end == location2.end and location1.strand == location2.strand) # will print True.

The problem was solved like this, but I am still wandering whether this is by design for some reason or the comparison method just haven't been built in yet.

Below are the process of why I come to this problem:

First I only extracted feat.type == 'CDS' information from genbank file, and found
all pseudo genes are lost.

Then I came up with the idea by recording the information in
feat.type == 'gene' and then look for either 'CDS' or
'misc_feature' to record more information for this gene.

This creates the need of confirming the 'CDS' or 'misc_feature'
is annotated at the same location in case there is multiple
'misc_feature' annotating some domains of the same gene.


问:
How to use purrr to apply function based on parameters made in a dataframe
I have the following code:

library(MASS)
library(tidyverse)

# Get density of points in 2 dimensions.
# @param x A numeric vector.
# @param y A numeric vector.
# @param n Create a square n by n grid to compute density.
# @return The density within each square.
get_density <- function(x, y, n = 100) {
  dens <- MASS::kde2d(x = x, y = y, n = n)
  ix <- findInterval(x, dens$x)
  iy <- findInterval(y, dens$y)
  ii <- cbind(ix, iy)
  return(dens$z[ii])
}

dens_wrapper <- function (tbl=NULL, var1=NULL, var2=NULL) {
  tbl_pair <- tbl %>%
                select_(var1, var2)
  x <- tbl_pair %>% pull(var1)
  y <- tbl_pair %>% pull(var2)
  tbl_pair$density <- get_density(x,y)
  tbl_pair
}

tbl <- as.tibble(iris) %>%
        select(-Species)

dens_wrapper(tbl=tbl, var1="Sepal.Length",var2="Petal.Length")
#> # A tibble: 150 x 3
#>    Sepal.Length Petal.Length    density
#>           <dbl>        <dbl>      <dbl>
#>  1          5.1          1.4 0.15253089
#>  2          4.9          1.4 0.15139758
#>  3          4.7          1.3 0.12566689
#>  4          4.6          1.5 0.10828077
#>  5          5.0          1.4 0.15624282
#>  6          5.4          1.7 0.10998006
#>  7          4.6          1.4 0.10773843
#>  8          5.0          1.5 0.15908618
#>  9          4.4          1.4 0.06635717
#> 10          4.9          1.5 0.15379367
#> # ... with 140 more rows
```

<p>I'm trying to use <code>dens_wrapper()</code> function on the set of parameter
constructed by this:</p>

<pre class="lang-r prettyprint-override"><code>tbl_colnames <- colnames(tbl)
allcomb_var <- expand.grid(tbl_colnames, tbl_colnames)
allcomb_var
#>            Var1         Var2
#> 1  Sepal.Length Sepal.Length
#> 2   Sepal.Width Sepal.Length
#> 3  Petal.Length Sepal.Length
#> 4   Petal.Width Sepal.Length
#> 5  Sepal.Length  Sepal.Width
#> 6   Sepal.Width  Sepal.Width
#> 7  Petal.Length  Sepal.Width
#> 8   Petal.Width  Sepal.Width
#> 9  Sepal.Length Petal.Length
#> 10  Sepal.Width Petal.Length
#> 11 Petal.Length Petal.Length
#> 12  Petal.Width Petal.Length
#> 13 Sepal.Length  Petal.Width
#> 14  Sepal.Width  Petal.Width
#> 15 Petal.Length  Petal.Width
#> 16  Petal.Width  Petal.Width
</code>```

With this code:

allcomb_var %>%
  purrr:pmap(list(tbl=tbl, var1=Var1, var2=Var2), dens_wrapper)
```

<p>But it gives me this error:</p>

<pre class="lang-r prettyprint-override"><code>Error in as_function(.f, ...) : object 'Var1' not found
</code>```

What's the right way to do it?

@baptise solution gives this (not quite what I expect):

# A tibble: 2,400 x 5
   Sepal.Length    density Sepal.Width Petal.Length Petal.Width
          <dbl>      <dbl>       <dbl>        <dbl>       <dbl>
 1          5.1 0.35060831          NA           NA          NA
 2          4.9 0.32088818          NA           NA          NA
 3          4.7 0.23507822          NA           NA          NA
 4          4.6 0.18191675          NA           NA          NA
 5          5.0 0.34885589          NA           NA          NA
 6          5.4 0.32746528          NA           NA          NA
 7          4.6 0.18191675          NA           NA          NA
 8          5.0 0.34885589          NA           NA          NA
 9          4.4 0.09698895          NA           NA          NA
10          4.9 0.32088818          NA           NA          NA
# ... with 2,390 more rows
```

答:
something along those lines?</p>

```<code>allcomb_var <- expand.grid(var1 = tbl_colnames, var2 = tbl_colnames,
                           stringsAsFactors = FALSE)

allcomb_var %>%
  purrr::pmap(.f = dens_wrapper, tbl=tbl)
</code>```

Body:
I have the following code:

library(MASS)
library(tidyverse)

# Get density of points in 2 dimensions.
# @param x A numeric vector.
# @param y A numeric vector.
# @param n Create a square n by n grid to compute density.
# @return The density within each square.
get_density <- function(x, y, n = 100) {
  dens <- MASS::kde2d(x = x, y = y, n = n)
  ix <- findInterval(x, dens$x)
  iy <- findInterval(y, dens$y)
  ii <- cbind(ix, iy)
  return(dens$z[ii])
}

dens_wrapper <- function (tbl=NULL, var1=NULL, var2=NULL) {
  tbl_pair <- tbl %>%
                select_(var1, var2)
  x <- tbl_pair %>% pull(var1)
  y <- tbl_pair %>% pull(var2)
  tbl_pair$density <- get_density(x,y)
  tbl_pair
}

tbl <- as.tibble(iris) %>%
        select(-Species)

dens_wrapper(tbl=tbl, var1="Sepal.Length",var2="Petal.Length")
#> # A tibble: 150 x 3
#>    Sepal.Length Petal.Length    density
#>           <dbl>        <dbl>      <dbl>
#>  1          5.1          1.4 0.15253089
#>  2          4.9          1.4 0.15139758
#>  3          4.7          1.3 0.12566689
#>  4          4.6          1.5 0.10828077
#>  5          5.0          1.4 0.15624282
#>  6          5.4          1.7 0.10998006
#>  7          4.6          1.4 0.10773843
#>  8          5.0          1.5 0.15908618
#>  9          4.4          1.4 0.06635717
#> 10          4.9          1.5 0.15379367
#> # ... with 140 more rows

I'm trying to use dens_wrapper() function on the set of parameter
constructed by this:

tbl_colnames <- colnames(tbl)
allcomb_var <- expand.grid(tbl_colnames, tbl_colnames)
allcomb_var
#>            Var1         Var2
#> 1  Sepal.Length Sepal.Length
#> 2   Sepal.Width Sepal.Length
#> 3  Petal.Length Sepal.Length
#> 4   Petal.Width Sepal.Length
#> 5  Sepal.Length  Sepal.Width
#> 6   Sepal.Width  Sepal.Width
#> 7  Petal.Length  Sepal.Width
#> 8   Petal.Width  Sepal.Width
#> 9  Sepal.Length Petal.Length
#> 10  Sepal.Width Petal.Length
#> 11 Petal.Length Petal.Length
#> 12  Petal.Width Petal.Length
#> 13 Sepal.Length  Petal.Width
#> 14  Sepal.Width  Petal.Width
#> 15 Petal.Length  Petal.Width
#> 16  Petal.Width  Petal.Width

With this code:

allcomb_var %>%
  purrr:pmap(list(tbl=tbl, var1=Var1, var2=Var2), dens_wrapper)

But it gives me this error:

Error in as_function(.f, ...) : object 'Var1' not found

What's the right way to do it?

@baptise solution gives this (not quite what I expect):

# A tibble: 2,400 x 5
   Sepal.Length    density Sepal.Width Petal.Length Petal.Width
          <dbl>      <dbl>       <dbl>        <dbl>       <dbl>
 1          5.1 0.35060831          NA           NA          NA
 2          4.9 0.32088818          NA           NA          NA
 3          4.7 0.23507822          NA           NA          NA
 4          4.6 0.18191675          NA           NA          NA
 5          5.0 0.34885589          NA           NA          NA
 6          5.4 0.32746528          NA           NA          NA
 7          4.6 0.18191675          NA           NA          NA
 8          5.0 0.34885589          NA           NA          NA
 9          4.4 0.09698895          NA           NA          NA
10          4.9 0.32088818          NA           NA          NA
# ... with 2,390 more rows

Body:
something along those lines?

allcomb_var <- expand.grid(var1 = tbl_colnames, var2 = tbl_colnames,
                           stringsAsFactors = FALSE)

allcomb_var %>%
  purrr::pmap(.f = dens_wrapper, tbl=tbl)


问:
Numpy Float128 Polyfit
I'm using numpy's polyfit to find a best fit curve for a set of data. However, numpy's polyfit returns an array of float64 and because the calculated coefficients are so large/small (i.e. 1e-200), it's returning an overflow error that's encountered in multiply :

RuntimeWarning: overflow encountered in multiply
  scale = NX.sqrt((lhs*lhs).sum(axis=0))

I've tried casting the initial array to be float128, but that does not seem to work. Is there any way around this overflow issue / any way to handle such large coefficients?

答: You may use logarithmic version of your variables (np.log10), so when dealing with something like 1e-200 you will have -200, less memory and more efficiency.

Title: Numpy Float128 Polyfit


问:
How to create alert function in php?
i want insert user in db mysql, i have a controller php, im validate if user exist in db  through a function, then if or not exist i want show alert function an redirect to php page, for that im using:

```<code><?php

 if(dao::existUser($user)) {
    echo "<script type=\"text/javascript\">\n";
    echo "alert('user exist!');\n";
    echo "window.location = ('../insertUser.php');\n";
    echo "</script>";
 }
</code>```

this function works!! but
i want to encapsulate the function in a method to later call it

example:

```<code><?php
class Utils {
  static function responseText($message, $url) {
     echo "<script type=\"text/javascript\">\n";
     echo "alert('"+$message+"');\n";
     echo "window.location = ('"+$url+"');\n";
     echo "</script>";
  }
}
</code>```

then, in my controller:

```<code><?php

 if(dao::existUser($user)) {
   Utils::responseText("user exist",'../insertUser.php');
 }
</code>```

but not work, and after call responseText, my page  goes blank

答:
I don't know what is wrong ( likely a quoting issue ), but I would suggest using a HEREDOC style for this and return the text not output the HTML from the class by itself.  Latter it could be hard to track where this output is coming from by looking just in the class that calls it.  By doing echo Utills::.. you'll be able to easily see it's outputting something, whiteout having to look into what the class does.

So like this.

```<code><?php
class Utils {
  static function responseText($message, $url) {
     return <<<HTML
     <script type="text/javascript">
         alert('$message');
         window.location = '$url';
     </script>
HTML; //nothing can go here no space ( before or after ) and not even this comment, nothing but HTML; litterally
  }
}

echo Utils::responseText("user exist",'../insertUser.php');
</code>```

HEREDOCs are a way of doing a text block without using any quotes, beware of the note i put in comments...  In this case it makes the Javascript string so much more simple when you don't have to manage quote usage.

Another suggestion for this class if it is to be a collection of static methods, you can make it where it can't be instantiated ( created using new class() )  Like this

```<code><?php
class Utils {
    private function __construct(){}  //no instantion
    private function __clone(){}  //no cloning
</code>```

This way you don't accidentally do  $U = new Utils(); $U->responseText(..) It's a little thing but it will insure all the methods of this class stay static. It's just a design thing I like to do, on singletons and static classes

UPDATE your issue is you are using the + to concat in PHP where you should be using the .  The + is good for Javascript not so much for PHP

And the way you have it with " double quotes concat is unnecessary, instead of

```<code>echo "alert('"+$message+"');\n";
</code>```

Try

```<code>echo "alert('$message');\n";
</code>```

Title: How to create alert function in php?

Body:
i want insert user in db mysql, i have a controller php, im validate if user exist in db  through a function, then if or not exist i want show alert function an redirect to php page, for that im using:

<?php

 if(dao::existUser($user)) {
    echo "";
 }

this function works!! but
i want to encapsulate the function in a method to later call it

example:

<?php
class Utils {
  static function responseText($message, $url) {
     echo "";
  }
}

then, in my controller:

<?php

 if(dao::existUser($user)) {
   Utils::responseText("user exist",'../insertUser.php');
 }

but not work, and after call responseText, my page  goes blank

Body:
I don't know what is wrong ( likely a quoting issue ), but I would suggest using a HEREDOC style for this and return the text not output the HTML from the class by itself.  Latter it could be hard to track where this output is coming from by looking just in the class that calls it.  By doing echo Utills::.. you'll be able to easily see it's outputting something, whiteout having to look into what the class does.

So like this.

<?php
class Utils {
  static function responseText($message, $url) {
     return <<<HTML
     <script type="text/javascript">
         alert('$message');
         window.location = '$url';
     </script>
HTML; //nothing can go here no space ( before or after ) and not even this comment, nothing but HTML; litterally
  }
}

echo Utils::responseText("user exist",'../insertUser.php');

HEREDOCs are a way of doing a text block without using any quotes, beware of the note i put in comments...  In this case it makes the Javascript string so much more simple when you don't have to manage quote usage.

Another suggestion for this class if it is to be a collection of static methods, you can make it where it can't be instantiated ( created using new class() )  Like this

<?php
class Utils {
    private function __construct(){}  //no instantion
    private function __clone(){}  //no cloning

This way you don't accidentally do  $U = new Utils(); $U->responseText(..) It's a little thing but it will insure all the methods of this class stay static. It's just a design thing I like to do, on singletons and static classes

UPDATE your issue is you are using the + to concat in PHP where you should be using the .  The + is good for Javascript not so much for PHP

And the way you have it with " double quotes concat is unnecessary, instead of

echo "alert('"+$message+"');\n";

Try

echo "alert('$message');\n";


问:
Execute stored procedure using table adapter in C#
In VB.net I can simply execute a stored procedure in SQL Server 2008 using the query in image below, but in C# I got an error.

Can you help me about the proper syntax in C#?

Thanks

答:
```<code>using (SqlConnection conn = new SqlConnection(your-connection-string)) {
conn.Open();

// 1.  create a command object identifying the stored procedure
SqlCommand cmd  = new SqlCommand("your-procedure-name", conn);

// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;

// 3. add parameter to command, which will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("@Username", textBox1.Text));
cmd.Parameters.Add(new SqlParameter("@Password", textBox2.Text));

// execute the command
using (SqlDataReader result = cmd.ExecuteReader()) {
    // iterate through results, printing each to console
    while (result .Read())
    {
      // Name  and Password Should Match with your proc col name
      var userName  = result["Name"].toString();
      var password  = result["password"].toString();

    }
}
 }
</code>```

For More details Please Read this this

How to execute a stored procedure within C# program

Body:
using (SqlConnection conn = new SqlConnection(your-connection-string)) {
conn.Open();

// 1.  create a command object identifying the stored procedure
SqlCommand cmd  = new SqlCommand("your-procedure-name", conn);

// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;

// 3. add parameter to command, which will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("@Username", textBox1.Text));
cmd.Parameters.Add(new SqlParameter("@Password", textBox2.Text));

// execute the command
using (SqlDataReader result = cmd.ExecuteReader()) {
    // iterate through results, printing each to console
    while (result .Read())
    {
      // Name  and Password Should Match with your proc col name
      var userName  = result["Name"].toString();
      var password  = result["password"].toString();

    }
}
 }

For More details Please Read this this

How to execute a stored procedure within C# program


问:
Extjs: two parallel ajax call
my code creates two ajax call at the same time (i assume the parallelism would be more efficient). I want to load a table if both calls succeed. What's the proper way of doing this?</p>

答:
I'd use a delayed task personally:

```<code>var success = {
  one: false,
  two: false
};

// Task
var task = new Ext.util.DelayedTask(function(){
   // Check for success
   if (success.one && success.two) {
      // Callback
      doCallback();
   } else {
      task.delay(500);
   }
});
task.delay(500);

// First
Ext.Ajax.request({
   ...
   success: function() {
      success.one = true;
   }
   ...
});

// Second
Ext.Ajax.request({
   ...
   success: function() {
      success.two = true;
   }
   ...
});
</code>```

The task acts like a thread and will check on the status of the requests and sleep for every 500ms until they both complete.

Title: Extjs: two parallel ajax call

Body:
I'd use a delayed task personally:

var success = {
  one: false,
  two: false
};

// Task
var task = new Ext.util.DelayedTask(function(){
   // Check for success
   if (success.one && success.two) {
      // Callback
      doCallback();
   } else {
      task.delay(500);
   }
});
task.delay(500);

// First
Ext.Ajax.request({
   ...
   success: function() {
      success.one = true;
   }
   ...
});

// Second
Ext.Ajax.request({
   ...
   success: function() {
      success.two = true;
   }
   ...
});

The task acts like a thread and will check on the status of the requests and sleep for every 500ms until they both complete.


问:
How can I change the default location of log4j2.xml in Java Spring Boot?
Log4j2 is working nicely with Spring Boot through the log4j2.xml configuration file in the root classpath, exactly as the documentation states.

When trying to move this file to a different location though, I'm not able to pass the new location to Spring at startup. From the documentation:

The various logging systems can be activated by including the
  appropriate libraries on the classpath, and further customized by
  providing a suitable configuration file in the root of the classpath,
  or in a location specified by the Spring Environment property
  logging.config.

I tried setting the new location with a Java system property

```<code>java -jar -Dlogging.config="classpath:/config/log4j2.xml" target/app.jar
</code>```

or using an external application.properties containing the relevant property

```<code>logging.config=classpath:/config/log4j2.xml
</code>```

But I am regularly greeted by the following error message.

```<code>ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
</code>```

答:
I have the same problem in my project, besides log4j2.xml I also need other config files in the class path.
Here is my 2 solutions that works:

Soluation 1 : Start spring boot application with org.springframework.boot.loader.JarLauncher

```<code>java -classpath SpringBootProject.jar;./config org.springframework.boot.loader.JarLauncher
</code>```

Solution 2:  Write a './config' class path entry in the MANIFEST.MF in the jar

```<code>    <build>
    <plugins>
      <plugin>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
          <archive>
            <manifestEntries>
               <Class-Path>./config/</Class-Path>
            </manifestEntries>
          </archive>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>1.5.3.RELEASE</version>
        <executions>
          <execution>
            <goals>
              <goal>repackage</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</code>```

Body:
Log4j2 is working nicely with Spring Boot through the log4j2.xml configuration file in the root classpath, exactly as the documentation states.

When trying to move this file to a different location though, I'm not able to pass the new location to Spring at startup. From the documentation:

The various logging systems can be activated by including the
  appropriate libraries on the classpath, and further customized by
  providing a suitable configuration file in the root of the classpath,
  or in a location specified by the Spring Environment property
  logging.config.

I tried setting the new location with a Java system property

java -jar -Dlogging.config="classpath:/config/log4j2.xml" target/app.jar

or using an external application.properties containing the relevant property

logging.config=classpath:/config/log4j2.xml

But I am regularly greeted by the following error message.

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.

Body:
I have the same problem in my project, besides log4j2.xml I also need other config files in the class path.
Here is my 2 solutions that works:

Soluation 1 : Start spring boot application with org.springframework.boot.loader.JarLauncher

java -classpath SpringBootProject.jar;./config org.springframework.boot.loader.JarLauncher

Solution 2:  Write a './config' class path entry in the MANIFEST.MF in the jar

    <build>
    <plugins>
      <plugin>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
          <archive>
            <manifestEntries>
               <Class-Path>./config/</Class-Path>
            </manifestEntries>
          </archive>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>1.5.3.RELEASE</version>
        <executions>
          <execution>
            <goals>
              <goal>repackage</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>