问:
Contact Form 7 backend email to different Adress
I am looking to add a second Email to contact form without using wordpress dashboard.

I would like to add it into the contact form 7 SOURCE files on my server.

Do you have any IDEA where should I add the Email in the source file?

So that if someone fills the fotm out it the email will go to the Email entered in Wordpress Plugin Settings and also to the Email I have netered in the backend.

Could it be somewhere in this path?

wp-content\plugins\contact-form-7\admin\admin-functions.php:

```<code>if ( isset( $_POST['wpcf7-mail-recipient'] ) ) {
</code>```

$mail['recipient'] = trim( $_POST['wpcf7-mail-recipient'] );

答:
I am not sure bt I am supposing it as email address is statically predefined obviously.
So let' say you have email address
"admin@gmail.com"

So here

```<code>wp-content\plugins\contact-form-7\admin\admin-functions.php:
</code>```

mention one variable as

```<code>$email = "admin@gmail.com";
if ( isset( $_POST['wpcf7-mail-recipient'] )  && !empty($email))
{
  //Rest of the remaining code of plugin.
}
Also at the time of email
$mail['recipient'] = trim( $_POST['wpcf7-mail-recipient'] );
$mail['recipient'] = trim( $email );
</code>```

Note make $email as a global variable so it can be used anywhere.

Body:
I am looking to add a second Email to contact form without using wordpress dashboard.

I would like to add it into the contact form 7 SOURCE files on my server.

Do you have any IDEA where should I add the Email in the source file?

So that if someone fills the fotm out it the email will go to the Email entered in Wordpress Plugin Settings and also to the Email I have netered in the backend.

Could it be somewhere in this path?

wp-content\plugins\contact-form-7\admin\admin-functions.php:

if ( isset( $_POST['wpcf7-mail-recipient'] ) ) {

$mail['recipient'] = trim( $_POST['wpcf7-mail-recipient'] );

Body:
I am not sure bt I am supposing it as email address is statically predefined obviously.
So let' say you have email address
"admin@gmail.com"

So here

wp-content\plugins\contact-form-7\admin\admin-functions.php:

mention one variable as

$email = "admin@gmail.com";
if ( isset( $_POST['wpcf7-mail-recipient'] )  && !empty($email))
{
  //Rest of the remaining code of plugin.
}
Also at the time of email
$mail['recipient'] = trim( $_POST['wpcf7-mail-recipient'] );
$mail['recipient'] = trim( $email );

Note make $email as a global variable so it can be used anywhere.


来源: stackexchange

问:
Chat communication
I've an question about my chat application. If you communicate as user with an admin, you can see the communication from both sides, how can i call that from the DB.

DB,

```<code>record 1: user_from, user_to, message
record 2: user_to, user_from, message
</code>```

sql:

```<code>SELECT * FROM messages WHERE user_from = 1 AND user_to = 2
</code>```

But with this query i can get only one way. I can see now only the records where user_from 1 and user_to 2 is, but i also want to see where user_from 2 and user_to 1 is.

Can someone help me with this issue?

Thanks a lot!

答:
Use OR and add your second condition:

```<code>SELECT *
FROM messages
WHERE (user_from = 1 AND user_to = 2)
   OR (user_from = 2 AND user_to = 1)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Chat communication

Body:
I've an question about my chat application. If you communicate as user with an admin, you can see the communication from both sides, how can i call that from the DB.

DB,

record 1: user_from, user_to, message
record 2: user_to, user_from, message

sql:

SELECT * FROM messages WHERE user_from = 1 AND user_to = 2

But with this query i can get only one way. I can see now only the records where user_from 1 and user_to 2 is, but i also want to see where user_from 2 and user_to 1 is.

Can someone help me with this issue?

Thanks a lot!

Body:
Use OR and add your second condition:

SELECT *
FROM messages
WHERE (user_from = 1 AND user_to = 2)
   OR (user_from = 2 AND user_to = 1)


问:
ASPX User controls not usable whether registered on page or in web.config
I've tried Registering my user controls on the page as follows:

```<code><%@Register Src="path_to_usercontrol.ascx" TagPrefix="uc" Tagname="control" %>
</code>```

I've also tried registered my user controls on the web.config per this answer here:

```<code><pages>
    <controls>
        <add tagPrefix="uc" src="~/UserControls/ContractUserControl.ascx" tagName="Contract" />
    </controls>
</pages>
</code>```

In theory, both approaches should absolutely work, however, neither does.

Per the linked question, Intellisense doesn't show me that a "uc" namespace exists in the first place let alone that the controls I want to use exist there.

I've tried cleaning and buidling/rebuilding both the project and the solution but none of this seems to affect the problem in any way whatsoever.

None of the documentation I've seen has indicated that I've done anything wrong or that I've left anything out, so what am I supposed to do to fix this problem?

Edit

I went 1 step further with this cleaning thing and deleted the Bin folder and web.config files from my project folder. The idea was to more thoroughly clean the Solution per @chrisrogers comment on this answer about what Clean/Build/Rebuild do.

Even still, absolutely nothing has changed after a new build once this was done.

答:
You still have to create an instance of the Control in order for intellisense to find it.

```<code><div>
    <uc:control runat="server" ID="WebUserControl1" />
</div>
</code>```

Now you can access it in code behind with the ID of WebUserControl1

Body:
I've tried Registering my user controls on the page as follows:

<%@Register Src="path_to_usercontrol.ascx" TagPrefix="uc" Tagname="control" %>

I've also tried registered my user controls on the web.config per this answer here:

<pages>
    <controls>
        <add tagPrefix="uc" src="~/UserControls/ContractUserControl.ascx" tagName="Contract" />
    </controls>
</pages>

In theory, both approaches should absolutely work, however, neither does.

Per the linked question, Intellisense doesn't show me that a "uc" namespace exists in the first place let alone that the controls I want to use exist there.

I've tried cleaning and buidling/rebuilding both the project and the solution but none of this seems to affect the problem in any way whatsoever.

None of the documentation I've seen has indicated that I've done anything wrong or that I've left anything out, so what am I supposed to do to fix this problem?

Edit

I went 1 step further with this cleaning thing and deleted the Bin folder and web.config files from my project folder. The idea was to more thoroughly clean the Solution per @chrisrogers comment on this answer about what Clean/Build/Rebuild do.

Even still, absolutely nothing has changed after a new build once this was done.

Body:
You still have to create an instance of the Control in order for intellisense to find it.

<div>
    <uc:control runat="server" ID="WebUserControl1" />
</div>

Now you can access it in code behind with the ID of WebUserControl1


问:
AJAX Success function never true
I don't know why my success function isn't working. I mean although it passes the JSON data to the PHP file and changes the password.

```<code>// this is the id of the form
$("#password_form").submit(function(e) {

    e.preventDefault();
    $(".verify-user-loader").addClass("force-display-block");
    password = $("input#password-reset").val();
    url = 'reset-pass.php';

    $.ajax({

        type : 'POST',
        url : url,
        dataType : 'json',
        data : {
                cardnumber: <?php echo '\''.$cardnumber.'\''; ?>,
                act_token: <?php echo '\''.$activationToken.'\''; ?>,
                password: password
        },
        success : function(success){
            alert("success");
        },
        error : function(request, error) {
            console.log(arguments);
            alert(" Can't do because: " + error);
        }

    });

});
</code>```

This file works as expected, it changes the password using the POST data

reset-pass.php

```<code>include_once '/../login/user.class.php';

$activationToken = $_POST['act_token'];
$cardnumber = $_POST['cardnumber'];
$password = $_POST['password'];

$user = new User();

$verifyToken = $user->verifyToken( $activationToken, $cardnumber );

if ($verifyToken['status'] === true) {

    $tokenStatus = "inactive";
    $user->signUp( $cardnumber, $password );
    $user->changeTokenStatus( $cardnumber, $tokenStatus );

    $success = true;

    return $success;

}else{
    print_r($verifyToken);
}
</code>```

答:
1 )  you need to echo $success; instead of return $success;

Ajax response should be any browser out put (i.e like html or echo or print_r these are browser output ) . instead of return .

2) simple add data like this

```<code>........

data : {
           cardnumber: '<?php echo $cardnumber; ?>',
           act_token: '<?php echo $activationToken; ?>',
           password: password
        },

........
</code>```

Title: AJAX Success function never true

Body:
I don't know why my success function isn't working. I mean although it passes the JSON data to the PHP file and changes the password.

// this is the id of the form
$("#password_form").submit(function(e) {

    e.preventDefault();
    $(".verify-user-loader").addClass("force-display-block");
    password = $("input#password-reset").val();
    url = 'reset-pass.php';

    $.ajax({

        type : 'POST',
        url : url,
        dataType : 'json',
        data : {
                cardnumber: <?php echo '\''.$cardnumber.'\''; ?>,
                act_token: <?php echo '\''.$activationToken.'\''; ?>,
                password: password
        },
        success : function(success){
            alert("success");
        },
        error : function(request, error) {
            console.log(arguments);
            alert(" Can't do because: " + error);
        }

    });

});

This file works as expected, it changes the password using the POST data

reset-pass.php

include_once '/../login/user.class.php';

$activationToken = $_POST['act_token'];
$cardnumber = $_POST['cardnumber'];
$password = $_POST['password'];

$user = new User();

$verifyToken = $user->verifyToken( $activationToken, $cardnumber );

if ($verifyToken['status'] === true) {

    $tokenStatus = "inactive";
    $user->signUp( $cardnumber, $password );
    $user->changeTokenStatus( $cardnumber, $tokenStatus );

    $success = true;

    return $success;

}else{
    print_r($verifyToken);
}

Body:
1 )  you need to echo $success; instead of return $success;

Ajax response should be any browser out put (i.e like html or echo or print_r these are browser output ) . instead of return .

2) simple add data like this

........

data : {
           cardnumber: '<?php echo $cardnumber; ?>',
           act_token: '<?php echo $activationToken; ?>',
           password: password
        },

........


问:
Does the Android advertising id change when the android device is reset (Factory Reset)?
i want to know does the android advertising id change when the android device is reset.

In my project am handling condition with aid, when the device is rebooted it doesnt working.

答:
The answer is NO. AdvertisingId value is related to your Google acount, not specific phone.

Check: http://www.tomsguide.com/faq/id-2316491/reset-google-advertising-android.html

Cheers!


问:
my php script enters blank info into mysql db!
When I try to enter data from a form I have made it adds a new entry as i can see from phpmyadmin but does not transfer other details across

I am using a simple form that collects 9 fileds post is to update.php. Here is what I have in update.php

```<code><?php
$realname = $_POST['realname'];
$age = $_POST['age'];
$country = $_POST['country'];
$gamename = $_POST['gamename'];
$gamelevel = $_POST['gamelevel'];
$itemlevel = $_POST['itemlevel'];
$class = $_POST['class'];
$played = $_POST['played'];
$support = $_POST['support'];

mysql_connect ("localhost", "mydb_userid", "MYPASSWORD") or die ('Error: ' . mysql_error());
mysql_select_db ("mydb_recruitment");

$query="INSERT INTO applicants (ID, realname, age, country, gamename, gamelevel, itemlevel, class, played, support)VALUES ('NULL','".$realname."','".$age."','".$country."','".$gamename."','".$gamelevel."','".$itemlevel."','".$class."','".$played."','".$support."')";

mysql_query($query) or die ('Error updating DB');

echo "You have sucessfully sent an application. Your details will be reviewed and someone will get back to you";

?>
</code>```

Hope someone can help, searching the net seems to sugest something about global variables - but i dont know if i have control of that as its an hosted site.

this is the signup form:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Candidate Registration</title>
</head>

<body>

<form medthod="post" action="update.php">

Real Name:<br />
<input type="text" name="realname" size="50" /><br />

Age:<br />
<input type="text" name="age" size="10" /><br />

Country:<br />
<input type="text" name="country" size="20" /><br />

In Game Name:<br />
<input type="text" name="gamename" size="30" /><br />

In Game Level:<br />
<input type="text" name="gamelevel" size="10" /><br />

In Game Item Level:<br />
<input type="text" name="itemlevel" size="10" /><br />

Class Played:<br />
<input type="text" name="class" size="30" /><br />

How long have you played wow?:<br />
<input type="text" name="played" size="10" /><br />

Please enter a brief statement of why you want to join:<br />
<input type="text" name="support" size="5000" /><br />
<br />
<input type="submit" value="Update DB" />

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

this is the update.php form

```<code><?php
$realname = $_POST['realname'];
$age = $_POST['age'];
$country = $_POST['country'];
$gamename = $_POST['gamename'];
$gamelevel = $_POST['gamelevel'];
$itemlevel = $_POST['itemlevel'];
$class = $_POST['class'];
$played = $_POST['played'];
$support = $_POST['support'];

mysql_connect ("localhost", "mydb_daniel", "mypwd") or die ('Error: ' . mysql_error());
mysql_select_db ("mydb_recruitment");

$query="INSERT INTO applicants (ID, realname, age, country, gamename, gamelevel, itemlevel, class, played, support)VALUES ('NULL','".$realname."','".$age."','".$country."','".$gamename."','".$gamelevel."','".$itemlevel."','".$class."','".$played."','".$support."')";

mysql_query($query) or die ('Error updating DB');

echo "You have sucessfully sent an application. Your details will be reviewed and someone will get back to you";

?>
</code>```

I understand peoples concerns about sercurity, but please understand this only for me to mess around with and produce a basic signup form for my guild, i wont be requesting credit card details :)

答:
Is your form method set to POST? - unless you have explicitly added this the variables will be within the $_GET superglobal so your variables would be like this:

```<code>$realname = $_GET['realname'];
</code>```

If it is set to POST - please do a var_dump($_POST) at the top of your script and see if any variables are making it to your script.

Something else that i've seen before is caused when people are redirecting in a .htaccess from domain.com to www.domain.com and they post a script explicity to domain.com/script.php and the script then redirects to www.domain.com/script.php and this empties the POST.

EDIT

You have spelt method wrong in your form tag - if you update this then it should work as your misspelling will be causing the variables to be sent as GET vars.

You can fix your security issues in a basic way like this:

```<code>$realname = mysql_real_escape_string($_POST['realname']);
$age = mysql_real_escape_string($_POST['age']);
$country = mysql_real_escape_string($_POST['country']);
$gamename = mysql_real_escape_string($_POST['gamename']);
$gamelevel = mysql_real_escape_string($_POST['gamelevel']);
$itemlevel = mysql_real_escape_string($_POST['itemlevel']);
$class = mysql_real_escape_string($_POST['class']);
$played = mysql_real_escape_string($_POST['played']);
$support = mysql_real_escape_string($_POST['support']);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
When I try to enter data from a form I have made it adds a new entry as i can see from phpmyadmin but does not transfer other details across

I am using a simple form that collects 9 fileds post is to update.php. Here is what I have in update.php

<?php
$realname = $_POST['realname'];
$age = $_POST['age'];
$country = $_POST['country'];
$gamename = $_POST['gamename'];
$gamelevel = $_POST['gamelevel'];
$itemlevel = $_POST['itemlevel'];
$class = $_POST['class'];
$played = $_POST['played'];
$support = $_POST['support'];

mysql_connect ("localhost", "mydb_userid", "MYPASSWORD") or die ('Error: ' . mysql_error());
mysql_select_db ("mydb_recruitment");

$query="INSERT INTO applicants (ID, realname, age, country, gamename, gamelevel, itemlevel, class, played, support)VALUES ('NULL','".$realname."','".$age."','".$country."','".$gamename."','".$gamelevel."','".$itemlevel."','".$class."','".$played."','".$support."')";

mysql_query($query) or die ('Error updating DB');

echo "You have sucessfully sent an application. Your details will be reviewed and someone will get back to you";

?>

Hope someone can help, searching the net seems to sugest something about global variables - but i dont know if i have control of that as its an hosted site.

this is the signup form:

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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Candidate Registration</title>

<form medthod="post" action="update.php">

Real Name:

<input type="text" name="realname" size="50" />

Age:

<input type="text" name="age" size="10" />

Country:

<input type="text" name="country" size="20" />

In Game Name:

<input type="text" name="gamename" size="30" />

In Game Level:

<input type="text" name="gamelevel" size="10" />

In Game Item Level:

<input type="text" name="itemlevel" size="10" />

Class Played:

<input type="text" name="class" size="30" />

How long have you played wow?:

<input type="text" name="played" size="10" />

Please enter a brief statement of why you want to join:

<input type="text" name="support" size="5000" />

<input type="submit" value="Update DB" />

</form>

this is the update.php form

<?php
$realname = $_POST['realname'];
$age = $_POST['age'];
$country = $_POST['country'];
$gamename = $_POST['gamename'];
$gamelevel = $_POST['gamelevel'];
$itemlevel = $_POST['itemlevel'];
$class = $_POST['class'];
$played = $_POST['played'];
$support = $_POST['support'];

mysql_connect ("localhost", "mydb_daniel", "mypwd") or die ('Error: ' . mysql_error());
mysql_select_db ("mydb_recruitment");

$query="INSERT INTO applicants (ID, realname, age, country, gamename, gamelevel, itemlevel, class, played, support)VALUES ('NULL','".$realname."','".$age."','".$country."','".$gamename."','".$gamelevel."','".$itemlevel."','".$class."','".$played."','".$support."')";

mysql_query($query) or die ('Error updating DB');

echo "You have sucessfully sent an application. Your details will be reviewed and someone will get back to you";

?>

I understand peoples concerns about sercurity, but please understand this only for me to mess around with and produce a basic signup form for my guild, i wont be requesting credit card details :)

Body:
Is your form method set to POST? - unless you have explicitly added this the variables will be within the $_GET superglobal so your variables would be like this:

$realname = $_GET['realname'];

If it is set to POST - please do a var_dump($_POST) at the top of your script and see if any variables are making it to your script.

Something else that i've seen before is caused when people are redirecting in a .htaccess from domain.com to www.domain.com and they post a script explicity to domain.com/script.php and the script then redirects to www.domain.com/script.php and this empties the POST.

EDIT

You have spelt method wrong in your form tag - if you update this then it should work as your misspelling will be causing the variables to be sent as GET vars.

You can fix your security issues in a basic way like this:

$realname = mysql_real_escape_string($_POST['realname']);
$age = mysql_real_escape_string($_POST['age']);
$country = mysql_real_escape_string($_POST['country']);
$gamename = mysql_real_escape_string($_POST['gamename']);
$gamelevel = mysql_real_escape_string($_POST['gamelevel']);
$itemlevel = mysql_real_escape_string($_POST['itemlevel']);
$class = mysql_real_escape_string($_POST['class']);
$played = mysql_real_escape_string($_POST['played']);
$support = mysql_real_escape_string($_POST['support']);


问:
Correct syntax in php
I'am tryig to print an id this way

```<code><form action="upload.php" method="post" enctype="multipart/form-data" <?php isset($_REQUEST['code'])?echo'id="csv-form"':echo 'id="edit-form"'; ?> >
</code>```

But I get this error syntax error, unexpected 'echo'

How is the correct syntax?

答: echo is a statement, not a function and hence can not be used in ternary operators, while using ternaries, please use echo outside ....</p>

Title: Correct syntax in php

Body:
I'am tryig to print an id this way

<form action="upload.php" method="post" enctype="multipart/form-data" <?php isset($_REQUEST['code'])?echo'id="csv-form"':echo 'id="edit-form"'; ?> >

But I get this error syntax error, unexpected 'echo'

How is the correct syntax?


问:
If Tcpclient can't connect
I'm new in C# and now i trying learn TcpClient, TcpListener and NetworkStream.
On Youtube and other C# tutorials i can find basic Tcp connection between Client and server. I tried make something like

```<code>if (Client.connect(ServerIP, ServerPORT))
{
     MessagaToTxtbox("Connected");
}
else
{
     MessageToTxtbox("Can't connect. Reason can be :\r\n1.Server is down.\r\n2.You lost internet connection");
}
</code>```

I thought this gonna work based on my php knowledge, but seems i was wrong! :D

So my question is:
How to check if tcpclient.connect(ServerIP, ServerPORT) is success. As i know TcpClient.Connected is the way to check if connection is still on, i want to check if client is made connection, if not, i can drop message or do some other functions. :)

答:
Use exception handling mechanism and wrap it in a try .. catch block like below. So if at all connection establishing fails due to some reason, you catch it and show proper message to UI and log it if needed

```<code>try
{
  Client.connect(ServerIP, ServerPORT));
  MessagaToTxtbox("Connected");
}
catch(Exception ex)
{
MessageToTxtbox("Can't connect. Reason can be :\r\n1.Server is down.\r\n2.You lost internet connection");
}
</code>```

Title: If Tcpclient can't connect

Body:
I'm new in C# and now i trying learn TcpClient, TcpListener and NetworkStream.
On Youtube and other C# tutorials i can find basic Tcp connection between Client and server. I tried make something like

if (Client.connect(ServerIP, ServerPORT))
{
     MessagaToTxtbox("Connected");
}
else
{
     MessageToTxtbox("Can't connect. Reason can be :\r\n1.Server is down.\r\n2.You lost internet connection");
}

I thought this gonna work based on my php knowledge, but seems i was wrong! :D

So my question is:
How to check if tcpclient.connect(ServerIP, ServerPORT) is success. As i know TcpClient.Connected is the way to check if connection is still on, i want to check if client is made connection, if not, i can drop message or do some other functions. :)

Body:
Use exception handling mechanism and wrap it in a try .. catch block like below. So if at all connection establishing fails due to some reason, you catch it and show proper message to UI and log it if needed

try
{
  Client.connect(ServerIP, ServerPORT));
  MessagaToTxtbox("Connected");
}
catch(Exception ex)
{
MessageToTxtbox("Can't connect. Reason can be :\r\n1.Server is down.\r\n2.You lost internet connection");
}


问:
CakePHP 3 - Select rows of containing table by date (year)
I've a table like below and now I wan't to get the rows by year. But when I try this I will get the following error:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Matches.date' in 'where clause'

My "Matches" table

```<code>id | goalsfor   | goalsagainst  | date
1  | 5          | 4             | 2017-07-05 15:57:36
2  | 9          | 5             | 2017-07-05 17:06:31
3  | 7          | 8             | 2015-07-05 15:57:36
4  | 0          | 2             | 2014-07-05 15:57:36
6  | 5          | 4             | 2014-07-05 15:57:36
7  | 7          | 9             | 2014-07-05 15:57:36
</code>```

My query:

```<code> $playedMatches = $this->Players
    ->find()
    ->contain([
       'MatchePlayers' => [
          'Matches'
       ]
    ]);

 $playedMatches->where(['YEAR(Matches.date) =' => "2017"]);
</code>```

My associations:

```<code>class PlayersTable extends Table {

    public function initialize(array $config) {
        parent::initialize($config);

        $this->setTable('players');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->hasMany('MatchePlayers', [
            'className' => 'MatchPlayers',
            'foreignKey' => 'player_id',
            'propertyName' => 'matches',
            'dependent' => true
        ]);
    }
}

class MatchPlayersTable extends Table {

    public function initialize(array $config) {
        parent::initialize($config);

        $this->setTable('matches_players');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->belongsTo('Players', [
            'className' => 'Players',
            'foreignKey' => 'player_id',
            'propertyName' => 'player'
        ]);

        $this->belongsTo('Matches', [
            'className' => 'Matches',
            'foreignKey' => 'match_id',
            'propertyName' => 'match'
        ]);
    }
}
</code>```

答:
I find your choose of name confusing: MatchPlayers, MatchePlayers...

anyway: cake does not perform a single query when you have a belongsToMany relationship (and a Player belongsToMany matches trough matches_players)

so you have to specify your conditons in the contain clause

```<code>$playedMatches = $this->Players
->find()
->contain([
    'MatchePlayers.Matches' => function ($q)
    {
        return $q->where(['YEAR(Matches.date) =' => "2017"])
    }
]);
</code>```

Body:
I've a table like below and now I wan't to get the rows by year. But when I try this I will get the following error:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Matches.date' in 'where clause'

My "Matches" table

id | goalsfor   | goalsagainst  | date
1  | 5          | 4             | 2017-07-05 15:57:36
2  | 9          | 5             | 2017-07-05 17:06:31
3  | 7          | 8             | 2015-07-05 15:57:36
4  | 0          | 2             | 2014-07-05 15:57:36
6  | 5          | 4             | 2014-07-05 15:57:36
7  | 7          | 9             | 2014-07-05 15:57:36

My query:

 $playedMatches = $this->Players
    ->find()
    ->contain([
       'MatchePlayers' => [
          'Matches'
       ]
    ]);

 $playedMatches->where(['YEAR(Matches.date) =' => "2017"]);

My associations:

class PlayersTable extends Table {

    public function initialize(array $config) {
        parent::initialize($config);

        $this->setTable('players');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->hasMany('MatchePlayers', [
            'className' => 'MatchPlayers',
            'foreignKey' => 'player_id',
            'propertyName' => 'matches',
            'dependent' => true
        ]);
    }
}

class MatchPlayersTable extends Table {

    public function initialize(array $config) {
        parent::initialize($config);

        $this->setTable('matches_players');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->belongsTo('Players', [
            'className' => 'Players',
            'foreignKey' => 'player_id',
            'propertyName' => 'player'
        ]);

        $this->belongsTo('Matches', [
            'className' => 'Matches',
            'foreignKey' => 'match_id',
            'propertyName' => 'match'
        ]);
    }
}

Body:
I find your choose of name confusing: MatchPlayers, MatchePlayers...

anyway: cake does not perform a single query when you have a belongsToMany relationship (and a Player belongsToMany matches trough matches_players)

so you have to specify your conditons in the contain clause

$playedMatches = $this->Players
->find()
->contain([
    'MatchePlayers.Matches' => function ($q)
    {
        return $q->where(['YEAR(Matches.date) =' => "2017"])
    }
]);


问:
How to upload files through laravel api routes
I am creating an api to upload files. It works when I upload them through web routes file, but it doesn't work when I upload them through api routes file.

```<code>axios.defaults.headers.put['Content-Type'] = 'multipart/form-data';
axios.put('/api/pikirler', formData);
</code>```

If I change it to:

```<code>axios.defaults.headers.post['Content-Type'] = 'multipart/form-data';
axios.post('/upload', formData);
</code>```

It works fine. But I want to use it in api routes.

答:
You can use guzzle package in your controller. Following is the code to upload file with guzzle.

```<code>$options = [
      'multipart' => [
        [
          'name' => 'user_key'
        ],
        [
          'name' => 'file_names',
          'contents' => '[]'
        ],
        [
          'name' => 'file',
          'contents' => file_get_contents($filePath),
          'filename' => $fileName,
          'headers'  => [
            'Content-Type' => 'application/octet-stream'
          ]
        ]
      ]
    ];

      $httpClient = new GuzzleClient();
      $response   = $httpClient->request("POST", "someApiUrl", $options);
</code>```

Following is the documentation.
http://docs.guzzlephp.org/en/latest/overview.html

ContentLicense: CC BY-SA 4.0

Body:
I am creating an api to upload files. It works when I upload them through web routes file, but it doesn't work when I upload them through api routes file.

axios.defaults.headers.put['Content-Type'] = 'multipart/form-data';
axios.put('/api/pikirler', formData);

If I change it to:

axios.defaults.headers.post['Content-Type'] = 'multipart/form-data';
axios.post('/upload', formData);

It works fine. But I want to use it in api routes.

Body:
You can use guzzle package in your controller. Following is the code to upload file with guzzle.

$options = [
      'multipart' => [
        [
          'name' => 'user_key'
        ],
        [
          'name' => 'file_names',
          'contents' => '[]'
        ],
        [
          'name' => 'file',
          'contents' => file_get_contents($filePath),
          'filename' => $fileName,
          'headers'  => [
            'Content-Type' => 'application/octet-stream'
          ]
        ]
      ]
    ];

      $httpClient = new GuzzleClient();
      $response   = $httpClient->request("POST", "someApiUrl", $options);

Following is the documentation.
http://docs.guzzlephp.org/en/latest/overview.html


问:
Using CSS selectors to access specific table rows with selenium
If I have the following HTML:

```<code><tbody id="items">
<tr><td>Item 1</td></tr>
<tr><td>Item 2</td></tr>
<tr><td>Item 3</td></tr>
<tr><td>Item 4</td></tr>
<tr><td>Item 5</td></tr>
<tr><td>Item 6</td></tr>
</tbody>
</code>```

How would I use CSS selectors with Selenium to access Item 4(or really any item I wanted)?

答:
You can use nth-child selector:

```<code>#items tr:nth-child(4) {color:#F00;}
</code>```

Live example: https://jsfiddle.net/7ow15mv2/1/

But no idea if it works with Selenium.

But according to docs it should.

Currently the css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(:nth-of-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type, :visited, :hover, :active, :focus, :indeterminate) and pseudo elements(::first-line, ::first-letter, ::selection, ::before, ::after).

Body:
If I have the following HTML:

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

How would I use CSS selectors with Selenium to access Item 4(or really any item I wanted)?

Body:
You can use nth-child selector:

#items tr:nth-child(4) {color:#F00;}

Live example: https://jsfiddle.net/7ow15mv2/1/

But no idea if it works with Selenium.

But according to docs it should.

Currently the css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(:nth-of-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type, :visited, :hover, :active, :focus, :indeterminate) and pseudo elements(::first-line, ::first-letter, ::selection, ::before, ::after).


答:
You should use echo instead of return, because when you work without function you should need to use echo.

So the code will be

```<code> echo true; // or you can write  echo $success = true;
 exit(); // exit is use to stop further processing of code.
</code>```

Title: AJAX Success function never true

Body:
You should use echo instead of return, because when you work without function you should need to use echo.

So the code will be

 echo true; // or you can write  echo $success = true;
 exit(); // exit is use to stop further processing of code.


问:
Unable to display array content
```<code>        var dataHolder = [
        {
            "letterA" : "Fruits",
            "letterB" : "Veges",
            "letterC" : "Meat"
        }
    ];
    console.log(dataHolder[0].letterA);
    var result = "";
    function getData(myLetter) {
        for (var i = 0; i < dataHolder.length; i++) {
           if(dataHolder[i][myLetter] === myLetter){
               console.log(dataHolder[i][myLetter]);
           }
           else{
               console.log("No data found");
           }
            }
        }
    getData("letterA");
</code>```

This is my code and i'm just trying to match the content of the array with the passed parameter, but every time it's giving No data found as output and not the matching content, it seems i'm missing something very basic here.
Any help would be highly appreciated.Thanks!!

答:
You matching was wrong.
 you are matching the letters == fruites .You should  check is the key exist or not ,that's enough  using hasOwnProperty()

Check this below. i was mention the error

var dataHolder = [{
  "letterA": "Fruits",
  "letterB": "Veges",
  "letterC": "Meat"
}];

var result = "";

function getData(myLetter) {
  for (var i = 0; i < dataHolder.length; i++) {
  console.log('this is the pblm  '+dataHolder[i][myLetter] +' != '+myLetter)
     if (dataHolder[i].hasOwnProperty(myLetter)) {
      console.log(dataHolder[i][myLetter]);
    } else {
      console.log("No data found");
    }
  }
}
getData("letterA");```
</div>
</div>
</p>

<p>For  your way use with <code>for...in</code>
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var dataHolder = [{
  "letterA": "Fruits",
  "letterB": "Veges",
  "letterC": "Meat"
}];

var result = "";

function getData(myLetter) {
  for (var i in dataHolder) {
    if (dataHolder[i].hasOwnProperty(myLetter)) {
      console.log(dataHolder[i][myLetter]);
    } else {
      console.log("No data found");
    }
  }
}
getData("letterA")</code>```

Title: Unable to display array content

Body:
        var dataHolder = [
        {
            "letterA" : "Fruits",
            "letterB" : "Veges",
            "letterC" : "Meat"
        }
    ];
    console.log(dataHolder[0].letterA);
    var result = "";
    function getData(myLetter) {
        for (var i = 0; i < dataHolder.length; i++) {
           if(dataHolder[i][myLetter] === myLetter){
               console.log(dataHolder[i][myLetter]);
           }
           else{
               console.log("No data found");
           }
            }
        }
    getData("letterA");

This is my code and i'm just trying to match the content of the array with the passed parameter, but every time it's giving No data found as output and not the matching content, it seems i'm missing something very basic here.
Any help would be highly appreciated.Thanks!!

Body:
You matching was wrong.
 you are matching the letters == fruites .You should  check is the key exist or not ,that's enough  using hasOwnProperty()

Check this below. i was mention the error

var dataHolder = [{
  "letterA": "Fruits",
  "letterB": "Veges",
  "letterC": "Meat"
}];

var result = "";

function getData(myLetter) {
  for (var i = 0; i < dataHolder.length; i++) {
  console.log('this is the pblm  '+dataHolder[i][myLetter] +' != '+myLetter)
     if (dataHolder[i].hasOwnProperty(myLetter)) {
      console.log(dataHolder[i][myLetter]);
    } else {
      console.log("No data found");
    }
  }
}
getData("letterA");

For  your way use with for...in

var dataHolder = [{
  "letterA": "Fruits",
  "letterB": "Veges",
  "letterC": "Meat"
}];

var result = "";

function getData(myLetter) {
  for (var i in dataHolder) {
    if (dataHolder[i].hasOwnProperty(myLetter)) {
      console.log(dataHolder[i][myLetter]);
    } else {
      console.log("No data found");
    }
  }
}
getData("letterA")


问:
How to efficiently compute the heat map of two Gaussian distribution in Python?
I am trying to produce a heat map where the pixel values are governed by two independent 2D Gaussian distributions. Let them be Kernel1 (muX1, muY1, sigmaX1, sigmaY1) and Kernel2 (muX2, muY2, sigmaX2, sigmaY2) respectively. To be more specific, the length of each kernel is three times its standard deviation. The first Kernel has sigmaX1 = sigmaY1 and the second Kernel has sigmaX2 < sigmaY2. Covariance matrix of both kernels are diagonal (X and Y are independent). Kernel1 is usually completely inside Kernel2.

I tried the following two approaches and the results are both unsatisfactory. Can someone give me some advice?

Approach1:

Iterate over all pixel value pairs (i, j) on the map and compute the value of I(i,j) given by I(i,j) = P(i, j | Kernel1, Kernel2) = 1 - (1 - P(i, j | Kernel1)) * (1 - P(i, j | Kernel2)). Then I got the following result, which is good in terms of smoothness. But it takes 10 seconds to run on my computer, which is too slow.

Codes:

```<code>def genDensityBox(self, height, width, muY1, muX1, muY2, muX2, sigmaK1, sigmaY2, sigmaX2):
    densityBox = np.zeros((height, width))
    for y in range(height):
        for x in range(width):
            densityBox[y, x] += 1. - (1. - multivariateNormal(y, x, muY1, muX1, sigmaK1, sigmaK1)) * (1. - multivariateNormal(y, x, muY2, muX2, sigmaY2, sigmaX2))
    return densityBox

def multivariateNormal(y, x, muY, muX, sigmaY, sigmaX):
    return norm.pdf(y, loc=muY, scale=sigmaY) * norm.pdf(x, loc=muX, scale=sigmaX)
</code>```

Approach2:

Generate two images corresponding to two kernels separately and then blend them together using certain alpha value. Each image is generated by taking the outer product of two one-dimensional Gaussian filter. Then I got the following result, which is very crude. But the advantage of this approach is that it is very fast due to the use of outer product between two vectors.

Since the first one is slow and the second on is crude, I am trying to find a new approach that achieves good smoothness and low time-complexity at the same time. Can someone give me some help?

Thanks!

For the second approach, the 2D Gaussian map can be easily generated as mentioned here:

```<code>def gkern(self, sigmaY, sigmaX, yKernelLen, xKernelLen, nsigma=3):
    """Returns a 2D Gaussian kernel array."""
    yInterval = (2*nsigma+1.)/(yKernelLen)
    yRow = np.linspace(-nsigma-yInterval/2.,nsigma+yInterval/2.,yKernelLen + 1)
    kernelY = np.diff(st.norm.cdf(yRow, 0, sigmaY))
    xInterval = (2*nsigma+1.)/(xKernelLen)
    xRow = np.linspace(-nsigma-xInterval/2.,nsigma+xInterval/2.,xKernelLen + 1)
    kernelX = np.diff(st.norm.cdf(xRow, 0, sigmaX))
    kernelRaw = np.sqrt(np.outer(kernelY, kernelX))
    kernel = kernelRaw / (kernelRaw.sum())
    return kernel
</code>```

答:
Your approach is fine other than that you shouldn't loop over norm.pdf but just push all values at which you want the kernel(s) evaluated, and then reshape the output to the desired shape of the image.

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal

# create 2 kernels
m1 = (-1,-1)
s1 = np.eye(2)
k1 = multivariate_normal(mean=m1, cov=s1)

m2 = (1,1)
s2 = np.eye(2)
k2 = multivariate_normal(mean=m2, cov=s2)

# create a grid of (x,y) coordinates at which to evaluate the kernels
xlim = (-3, 3)
ylim = (-3, 3)
xres = 100
yres = 100

x = np.linspace(xlim[0], xlim[1], xres)
y = np.linspace(ylim[0], ylim[1], yres)
xx, yy = np.meshgrid(x,y)

# evaluate kernels at grid points
xxyy = np.c_[xx.ravel(), yy.ravel()]
zz = k1.pdf(xxyy) + k2.pdf(xxyy)

# reshape and plot image
img = zz.reshape((xres,yres))
plt.imshow(img); plt.show()
</code>```

This approach shouldn't take too long:

```<code>In [26]: %timeit zz = k1.pdf(xxyy) + k2.pdf(xxyy)
1000 loops, best of 3: 1.16 ms per loop
</code>```

Body:
I am trying to produce a heat map where the pixel values are governed by two independent 2D Gaussian distributions. Let them be Kernel1 (muX1, muY1, sigmaX1, sigmaY1) and Kernel2 (muX2, muY2, sigmaX2, sigmaY2) respectively. To be more specific, the length of each kernel is three times its standard deviation. The first Kernel has sigmaX1 = sigmaY1 and the second Kernel has sigmaX2 < sigmaY2. Covariance matrix of both kernels are diagonal (X and Y are independent). Kernel1 is usually completely inside Kernel2.

I tried the following two approaches and the results are both unsatisfactory. Can someone give me some advice?

Approach1:

Iterate over all pixel value pairs (i, j) on the map and compute the value of I(i,j) given by I(i,j) = P(i, j | Kernel1, Kernel2) = 1 - (1 - P(i, j | Kernel1)) * (1 - P(i, j | Kernel2)). Then I got the following result, which is good in terms of smoothness. But it takes 10 seconds to run on my computer, which is too slow.

Codes:

def genDensityBox(self, height, width, muY1, muX1, muY2, muX2, sigmaK1, sigmaY2, sigmaX2):
    densityBox = np.zeros((height, width))
    for y in range(height):
        for x in range(width):
            densityBox[y, x] += 1. - (1. - multivariateNormal(y, x, muY1, muX1, sigmaK1, sigmaK1)) * (1. - multivariateNormal(y, x, muY2, muX2, sigmaY2, sigmaX2))
    return densityBox

def multivariateNormal(y, x, muY, muX, sigmaY, sigmaX):
    return norm.pdf(y, loc=muY, scale=sigmaY) * norm.pdf(x, loc=muX, scale=sigmaX)

Approach2:

Generate two images corresponding to two kernels separately and then blend them together using certain alpha value. Each image is generated by taking the outer product of two one-dimensional Gaussian filter. Then I got the following result, which is very crude. But the advantage of this approach is that it is very fast due to the use of outer product between two vectors.

Since the first one is slow and the second on is crude, I am trying to find a new approach that achieves good smoothness and low time-complexity at the same time. Can someone give me some help?

Thanks!

For the second approach, the 2D Gaussian map can be easily generated as mentioned here:

def gkern(self, sigmaY, sigmaX, yKernelLen, xKernelLen, nsigma=3):
    """Returns a 2D Gaussian kernel array."""
    yInterval = (2*nsigma+1.)/(yKernelLen)
    yRow = np.linspace(-nsigma-yInterval/2.,nsigma+yInterval/2.,yKernelLen + 1)
    kernelY = np.diff(st.norm.cdf(yRow, 0, sigmaY))
    xInterval = (2*nsigma+1.)/(xKernelLen)
    xRow = np.linspace(-nsigma-xInterval/2.,nsigma+xInterval/2.,xKernelLen + 1)
    kernelX = np.diff(st.norm.cdf(xRow, 0, sigmaX))
    kernelRaw = np.sqrt(np.outer(kernelY, kernelX))
    kernel = kernelRaw / (kernelRaw.sum())
    return kernel

Body:
Your approach is fine other than that you shouldn't loop over norm.pdf but just push all values at which you want the kernel(s) evaluated, and then reshape the output to the desired shape of the image.

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal

# create 2 kernels
m1 = (-1,-1)
s1 = np.eye(2)
k1 = multivariate_normal(mean=m1, cov=s1)

m2 = (1,1)
s2 = np.eye(2)
k2 = multivariate_normal(mean=m2, cov=s2)

# create a grid of (x,y) coordinates at which to evaluate the kernels
xlim = (-3, 3)
ylim = (-3, 3)
xres = 100
yres = 100

x = np.linspace(xlim[0], xlim[1], xres)
y = np.linspace(ylim[0], ylim[1], yres)
xx, yy = np.meshgrid(x,y)

# evaluate kernels at grid points
xxyy = np.c_[xx.ravel(), yy.ravel()]
zz = k1.pdf(xxyy) + k2.pdf(xxyy)

# reshape and plot image
img = zz.reshape((xres,yres))
plt.imshow(img); plt.show()

This approach shouldn't take too long:

In [26]: %timeit zz = k1.pdf(xxyy) + k2.pdf(xxyy)
1000 loops, best of 3: 1.16 ms per loop


问:
How to get language ID for a language culture in nopCommerce 3.9?
Working with nopCommerce 3.9 how can find out the LanguageId (the ID stored in the nopCommerce DataBase) for a language if I only know the language culture?

For instance, when I want to add a locale resource in the Install() method of my plugin, I can achieve that by specifying the culture as string value

```<code>this.AddOrUpdatePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.AdditionalFee",
     "Additional fee", "en-US");
</code>```

But other methods require the language ID and don't accept a culture string. (e.g. the SaveLocalizedSetting extension method for settings)

```<code>checkMoneyOrderPaymentSettings.SaveLocalizedSetting(x => x.DescriptionText,
                    languageId, //how to find out the ID for "en-US"
                    "my localized text");
</code>```

How can I get the ID for "en-US" if I only know the locale resource at that point of execution?

答:
You can try bellow code. Add reference Nop.Services at your plugin.</p>

```<code>var langId = _languageService.GetAllLanguages().Where(x => x.LanguageCulture == "en-US").FirstOrDefault().Id;
</code>```

Body:
Working with nopCommerce 3.9 how can find out the LanguageId (the ID stored in the nopCommerce DataBase) for a language if I only know the language culture?

For instance, when I want to add a locale resource in the Install() method of my plugin, I can achieve that by specifying the culture as string value

this.AddOrUpdatePluginLocaleResource("Plugins.Payment.CheckMoneyOrder.AdditionalFee",
     "Additional fee", "en-US");

But other methods require the language ID and don't accept a culture string. (e.g. the SaveLocalizedSetting extension method for settings)

checkMoneyOrderPaymentSettings.SaveLocalizedSetting(x => x.DescriptionText,
                    languageId, //how to find out the ID for "en-US"
                    "my localized text");

How can I get the ID for "en-US" if I only know the locale resource at that point of execution?

Body:
You can try bellow code. Add reference Nop.Services at your plugin.

var langId = _languageService.GetAllLanguages().Where(x => x.LanguageCulture == "en-US").FirstOrDefault().Id;


问:
php - How do I weed out similar items from an associative array?
UPDATE: someone edited my question incorrectly, but it's fixed now

Let's say I have the following associative array:

```<code>Array (
[Postponement no issue for Man Utd (BBC) ] => 8
[Postponement no issue for Man Utd ] => 7
[Postponement no issue for Man Utd: Manchester United say they have no issue over Sunday's game at Chelsea being ... ] => 3
)
</code>```

You'll notice that the term "Postponement no issue for Man Utd" appears in all three keys. I want to turn this array into a new array like this:

```<code>Array ( [Postponement no issue for Man Utd] => 18 )
</code>```

Where 18 is the sum of all values where the key contains "Postponement no issue for Man Utd".

In other words: if one key appears inside another key, the latter is dropped fom the new array and it's value is added on to the former key's value.

Is this possible and how? Thanks in advance.

答:
A simple approach could be:</p>

```<code>$original_array = array(...); // The original array with keys and values
asort($original_array); // Sort the array by its keys
$clean_array = array();
foreach ($original_array as $key => $value)
{
  foreach (array_keys($clean_array) as $clean_key)
  {
    $found = false;

    if (preg_match('/'.preg_quote($clean_key).'/', $key))
    {
      $clean_array[$clean_key] += $value;
      $found = true;

      break;
    }

    if (!$found) $clean_array[$key] = $value;
  }
}
</code>```

Body:
UPDATE: someone edited my question incorrectly, but it's fixed now

Let's say I have the following associative array:

Array (
[Postponement no issue for Man Utd (BBC) ] => 8
[Postponement no issue for Man Utd ] => 7
[Postponement no issue for Man Utd: Manchester United say they have no issue over Sunday's game at Chelsea being ... ] => 3
)

You'll notice that the term "Postponement no issue for Man Utd" appears in all three keys. I want to turn this array into a new array like this:

Array ( [Postponement no issue for Man Utd] => 18 )

Where 18 is the sum of all values where the key contains "Postponement no issue for Man Utd".

In other words: if one key appears inside another key, the latter is dropped fom the new array and it's value is added on to the former key's value.

Is this possible and how? Thanks in advance.

Body:
A simple approach could be:

$original_array = array(...); // The original array with keys and values
asort($original_array); // Sort the array by its keys
$clean_array = array();
foreach ($original_array as $key => $value)
{
  foreach (array_keys($clean_array) as $clean_key)
  {
    $found = false;

    if (preg_match('/'.preg_quote($clean_key).'/', $key))
    {
      $clean_array[$clean_key] += $value;
      $found = true;

      break;
    }

    if (!$found) $clean_array[$key] = $value;
  }
}


问:
Elasticsearch Bulk data insertion - JsonParseException[Unexpected character - Using PHP
While indexing the bulk data using PHP curl method I am getting the exception as "error":"JsonParseException[Unexpected character (':' (code 58)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n at [Source: [B@14abb68; line: 1, column: 18]]","status":500}

Kindly find below code which I am using for the same and do let me know what could be wrong over here.

```<code><?php
 $ch = curl_init();
$method = "POST";
$url = "http://192.168.1.204/myindex/test/_bulk";

$qry = '
{"index":{"_index": "myindex","_type":"test"}}
{
    "product_id": 1,
    "title": "mobile"
}
{"index":{"_index": "myindex","_type":"test"}}
{
    "product_id": 2,
    "title": "laptop",
}
';

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PORT, 9200);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);

$result = curl_exec($ch);
curl_close($ch);
  echo $result;

?>
</code>```

答:
You are not using the correct format (and there is an additional comma at the second element).
It should be:

```<code>action_and_meta_data\n
optional_source\n
action_and_meta_data\n
optional_source\n
....
action_and_meta_data\n
optional_source\n
</code>```

Extracted from the documentation of elasticsearch - bulk

So, you should add the data using the following format:

```<code>{"index":{"_index": "myindex","_type":"test"}}
{"product_id": 1,"title": "mobile"}
{"index":{"_index": "myindex","_type":"test"}}
{"product_id": 2,"title": "laptop"}
</code>```

Body:
While indexing the bulk data using PHP curl method I am getting the exception as "error":"JsonParseException[Unexpected character (':' (code 58)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n at [Source: [B@14abb68; line: 1, column: 18]]","status":500}

Kindly find below code which I am using for the same and do let me know what could be wrong over here.

<?php
 $ch = curl_init();
$method = "POST";
$url = "http://192.168.1.204/myindex/test/_bulk";

$qry = '
{"index":{"_index": "myindex","_type":"test"}}
{
    "product_id": 1,
    "title": "mobile"
}
{"index":{"_index": "myindex","_type":"test"}}
{
    "product_id": 2,
    "title": "laptop",
}
';

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PORT, 9200);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);

$result = curl_exec($ch);
curl_close($ch);
  echo $result;

?>

Body:
You are not using the correct format (and there is an additional comma at the second element).
It should be:

action_and_meta_data\n
optional_source\n
action_and_meta_data\n
optional_source\n
....
action_and_meta_data\n
optional_source\n

Extracted from the documentation of elasticsearch - bulk

So, you should add the data using the following format:

{"index":{"_index": "myindex","_type":"test"}}
{"product_id": 1,"title": "mobile"}
{"index":{"_index": "myindex","_type":"test"}}
{"product_id": 2,"title": "laptop"}


问:
Where I must put my jsp files in SpringBoot?
I am writting to you because I don't know where I must put my JSP files in a SpringBoot application..

A screen of my application's files

Thank you in advance for your response,
Noman.

PS: Sorry I can't say Hello at the beginning of my post, it is always deleted..

答:
its esey to add jsp files in spring
the following steps is important for that:
- create folder in src/main called webapp
- create inside it folder called WEB-INF
- add this lines to your pom file

```<code>    <!-- Spring MVC framework -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <!-- JSTL -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>${jstl.version}</version>
    </dependency>

    <!-- for compile only, your container should have this -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>${servletapi.version}</version>
        <scope>provided</scope>
    </dependency>

</dependencies>
</code>```

create the mvc-dispatcher-servlet.xml

create the web.xml file

you can visit the URl for more details about the steps press here

Body:
its esey to add jsp files in spring
the following steps is important for that:
- create folder in src/main called webapp
- create inside it folder called WEB-INF
- add this lines to your pom file

    <!-- Spring MVC framework -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <!-- JSTL -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>${jstl.version}</version>
    </dependency>

    <!-- for compile only, your container should have this -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>${servletapi.version}</version>
        <scope>provided</scope>
    </dependency>

</dependencies>

create the mvc-dispatcher-servlet.xml

create the web.xml file

you can visit the URl for more details about the steps press here


问:
Sort string data as Int in jquery DataTable
I have string Data in my ProviderQualificationTime field.So it doesn't sort this column properly since the data is a string. How can I make the datatable to treat it as Int Column and sort according to that?
Possible?
Sample Data in ProviderQualificationTime field:

"1","10","11","NotAccpeted"

Code:

```<code>$('#tblProviders').dataTable({
                            "autoWidth": false,
                            "searching": false,
                            "pageLength": 6,
                            "lengthMenu": [6, 10, 25, 50, 75, 100],
                            "bDestroy": true,
                            data: obj.data.ProviderQualificationDetails,
                            columns: [
                                       { "data": "ProviderName" },
                                       { "data": "ProviderQualificationTime" },
                                       { "data": "TotalServiceableOffers" }
                            ]
                        });
</code>```

答:
Just add the given below parameter:

"sType": "string"

For more details visit the link [https://datatables.net/forums/discussion/24284/column-sort-wrong-data-always-string]

Body:
I have string Data in my ProviderQualificationTime field.So it doesn't sort this column properly since the data is a string. How can I make the datatable to treat it as Int Column and sort according to that?
Possible?
Sample Data in ProviderQualificationTime field:

"1","10","11","NotAccpeted"

Code:

$('#tblProviders').dataTable({
                            "autoWidth": false,
                            "searching": false,
                            "pageLength": 6,
                            "lengthMenu": [6, 10, 25, 50, 75, 100],
                            "bDestroy": true,
                            data: obj.data.ProviderQualificationDetails,
                            columns: [
                                       { "data": "ProviderName" },
                                       { "data": "ProviderQualificationTime" },
                                       { "data": "TotalServiceableOffers" }
                            ]
                        });


问:
In OMNeT++/SimuLTE is it possible to reassign bands?
I have implemented a Device2Device-capable LTE scheduler for the SimuLTE framework for OMNeT++. It needs to reassign resource blocks. In typical LTE networks, each resource blocks is assigned to at most 1 node. With the advent of D2D, uplink resource blocks can be reassigned to D2D users.

The simulator knows both resource blocks and bands. A band is a logical collection of transmission frequencies. If numBands == numRBs then each band corresponds to one resource block.

So to try things out, I set numRbs = 1 = numBands and have two nodes. My scheduler simply assigns the first band to the first node, and then attempts to reassign the same band to the second node. The SchedulingResult tells me I should TERMINATE here - which seems like reassignment is not supported at all.

However, both nodes transmit UDP packets and if I run the simulation to the end, I find that both actually got to send out the same number of packets. Going through the logs I find that every 5th scheduling round (the number 5 might be specific to my setup), the second node still gets the TERMINATE answer, but is granted a resource block anyway. This seems to happen within the eNodeB Main Loop. How, why, what's going on? Does anyone know?

答:
Turns out that one of the two notions of bands and resource blocks are obsolete and likely to be removed in a later version. Users of the framework should set numBands==numRBs! The number of resource blocks is absolute, so this means that per band there's going to be one resource block available.

Note that band reassignment is not currently supported. Trying to do so will always end in the TERMINATE answer as described in the question, because there's a check that makes sure that the number of unassigned resource blocks is >0, which is not true if the band has already been assigned (and therefore the resource block linked to it).


问:
commandline tool Glassfish appclient doesn't see deployed EJB
I'm working my way through a book about "Java EE 7 for Glassfish", with the server installed on Fedora Linux.

I have a simple stateless session bean SimpleSessionBean deployed on the server and I am trying to approach that SimpleSessionBean via SessionBeanClient and the Glassfish command line tool appclient, running a client jar. Everything from the book, so it should work. The client however can't find SimpleSessionBean. Apparently a class path issue. In the server logs nothing happened.

I can't find any pointers how Glassfish should be properly installed. Everything works within the server. I can approach installed war files from facelets running in a browser.

It is probably a matter of setting $PATH right or something or some other environment variable. Any pointers to relevant literature?

Thanks in advance for any suggestions!

UPDATE1: error message

From the bash terminal window where I run appclient:

[fedora@localhost bin]$ ./appclient -client /home/fedora/Downloads/6886EN_04_Code/ch04_src/simplesessionbeanclient/target/simplesessionbeanclient.jar

Jul 06, 2017 12:52:57 PM org.glassfish.apf.impl.DefaultErrorHandler error
SEVERE: Class [ Lnet/ensode/glassfishbook/SimpleSession; ] not found.

Error while loading [ class net.ensode.glassfishbook.SessionBeanClient ]
Exception in thread "main" java.lang.NoClassDefFoundError: net/ensode/glassfishbook/SimpleSession
    at net.ensode.glassfishbook.SessionBeanClient.invokeSessionBeanMethods(SessionBeanClient.java:12)
    at net.ensode.glassfishbook.SessionBeanClient.main(SessionBeanClient.java:19)
Caused by: java.lang.ClassNotFoundException: net.ensode.glassfishbook.SimpleSession
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at org.glassfish.appclient.client.acc.ACCClassLoader.findClass(ACCClassLoader.java:237)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

UPDATE2: From the Glassfish book:

We are using Maven to build our code. For this example, we used
the Maven Assembly plugin (http://maven.apache.org/plugins/maven-assembly-plugin/) to build a client JAR file
that includes all dependencies; this frees us from having to specify
all the dependent JAR files in the -classpath command-line option
of the appclient utility. To build this JAR file, simply invoke mvn
assembly:assembly from the command line.

SOLUTION: the missing link was producing a client jar with additional jar's "on board" so to speak. Proceed as follows (at least in Eclipse): select pom.xml > right-click > Run As > Maven build... > enter in Goals field: assembly:assembly> Apply/Run.

The result will be that you will find TWO jars under your target folder: xxxclient.jar and xxxclient-jar-with-dependencies.jar.
From the command line in bash execute from the folder with latter jar:

/path_to/appclient -client xxxclient-jar-with-dependencies.jar

After a very long wait (on my $200 mini Linux box) the HelloWorld-ish server EJB gets finally properly called.

答:
Your assumption is right.

You are missing net.ensode.glassfishbook.SimpleSession in your classpath.

From an older book online:

...executed through the appclient utility. This utility can be found at
  [glassfish installation directory]/glassfish/bin/. Assuming this path
  is in the PATH environment variable, and assuming we placed our client
  code in a JAR file called simplesessionbeanclient.jar, we would
  execute the above client code by typing the following command in the
  command line:

appclient -client simplesessionbeanclient.jar

It seems that you've started from

.../bin/./appclient -client
  /home/fedora/Downloads/6886EN_04_Code/ch04_src/simplesessionbeanclient/target/simplesessionbeanclient.jar

You need SimpleSession.class in your CLASSPATH (or in a jar in that classpath).
Usually java checks the current directory first (which is your bin folder). If the class is not found (its not, since its in your simplesessionbeanclient folder), it searches for that class in the classpath (where you did not add the simplesessionbeanclient folder).

Try

```<code>appclient -client simplesessionbeanclient.jar
</code>```

from the folder where simplesessionbeanclient.jar is located.
If you don't want to add the appclient folder to your path start with

```<code>/your/path/to/appclient -client simplesessionbeanclient.jar
</code>```

(again from the folder where simplesessionbeanclient.jar is located)

Update:
If you still get a ClassNotFoundException have a look if it is missing in your jar file (jars are Zip-File, you could use your Zip-Tools):

```<code>jar tf simplesessionbeanclient.jar
</code>```

if there is a SimpleSession.class

Body:
Your assumption is right.

You are missing net.ensode.glassfishbook.SimpleSession in your classpath.

From an older book online:

...executed through the appclient utility. This utility can be found at
  [glassfish installation directory]/glassfish/bin/. Assuming this path
  is in the PATH environment variable, and assuming we placed our client
  code in a JAR file called simplesessionbeanclient.jar, we would
  execute the above client code by typing the following command in the
  command line:

appclient -client simplesessionbeanclient.jar

It seems that you've started from

.../bin/./appclient -client
  /home/fedora/Downloads/6886EN_04_Code/ch04_src/simplesessionbeanclient/target/simplesessionbeanclient.jar

You need SimpleSession.class in your CLASSPATH (or in a jar in that classpath).
Usually java checks the current directory first (which is your bin folder). If the class is not found (its not, since its in your simplesessionbeanclient folder), it searches for that class in the classpath (where you did not add the simplesessionbeanclient folder).

Try

appclient -client simplesessionbeanclient.jar

from the folder where simplesessionbeanclient.jar is located.
If you don't want to add the appclient folder to your path start with

/your/path/to/appclient -client simplesessionbeanclient.jar

(again from the folder where simplesessionbeanclient.jar is located)

Update:
If you still get a ClassNotFoundException have a look if it is missing in your jar file (jars are Zip-File, you could use your Zip-Tools):

jar tf simplesessionbeanclient.jar

if there is a SimpleSession.class


问:
AlphaVantage API Stock Market Indices
I'm using python and its framework flask to build a frontEnd backEnd project.
The project needs stock data. I used Yahoo's Api before it stopped working and now I'm using Alpha Vantage API. It's working pretty well but I'm having difficulties with stock market Indices like Nasdaq, Dow Jones.. with yahoo I was using their tickers(like symboles) (^IXIC, ^DJI...) but it doesn't seem to work with alpha vantage. Has anyone worked with alpha vantage?

example of url to get data for Microsoft:

https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT&outputsize=full&apikey=CN3J

Python code:

```<code>@app.route('/pfa/medaf/IndAct', methods = ['POST'])
def donnee():
Action1 = request.form['code1']
Action2 = request.form['code2']
Indice = request.form['Ind']

url="https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol="
urlInd=url+Indice+"&apikey=CN3J"
urlAct1=url+Action1+"&apikey=CN3J"
urlAct2=url+Action2+"&apikey=CN3J"

respInd = urlopen(urlInd)
dataInd = json.loads(respInd.read().decode(respInd.info().get_param('charset') or 'utf-8'))

coursIndice=[]
listInd=[]
for elt in dataInd['Time Series (Daily)'].keys():
    listInd.append(elt)
listInd.sort(reverse=True)
for e in listInd:
    coursIndice.append(float(dataInd['Time Series (Daily)'][e]['4. close']))

lenIndice = len(coursIndice)

rentabIndice=[]
for j in range(lenIndice-1):
    rentabIndice.append(100*(coursIndice[j+1]/coursIndice[j] -1 ))

moyenneMarche=sum(rentabIndice)/len(rentabIndice)
</code>```

HTML code:

```<code><section class="cols pad_left1">
    <form action = "http://localhost:5000/pfa/medaf/IndAct" method = "post">
    Tickers:
    <input type = "text" name = "code1" placeholder="Ticker here"><br>
    <input type = "text" name = "code2" placeholder="Ticker here"><br><br>
    Indice:<br>
    <select name="Ind" size="1" >
    <option   value="^IXIC" > NASDAQ Composite    </option>
    <option   value="^FCHI" > CAC40    </option>
    <option   value="^DJI" > Dow Jones</option>
    </select><br><br>
    <input type = "submit" value = "submit" />
    </form>
</section>
</code>```

答: I have a python library for alphavantage (MIT licensed) https://github.com/RomelTorres/alpha_vantage you can have a look at it. I have shared some examples there on how to work with the library.</p>

Title: AlphaVantage API Stock Market Indices

Body:
I'm using python and its framework flask to build a frontEnd backEnd project.
The project needs stock data. I used Yahoo's Api before it stopped working and now I'm using Alpha Vantage API. It's working pretty well but I'm having difficulties with stock market Indices like Nasdaq, Dow Jones.. with yahoo I was using their tickers(like symboles) (^IXIC, ^DJI...) but it doesn't seem to work with alpha vantage. Has anyone worked with alpha vantage?

example of url to get data for Microsoft:

https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT&outputsize=full&apikey=CN3J

Python code:

@app.route('/pfa/medaf/IndAct', methods = ['POST'])
def donnee():
Action1 = request.form['code1']
Action2 = request.form['code2']
Indice = request.form['Ind']

url="https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol="
urlInd=url+Indice+"&apikey=CN3J"
urlAct1=url+Action1+"&apikey=CN3J"
urlAct2=url+Action2+"&apikey=CN3J"

respInd = urlopen(urlInd)
dataInd = json.loads(respInd.read().decode(respInd.info().get_param('charset') or 'utf-8'))

coursIndice=[]
listInd=[]
for elt in dataInd['Time Series (Daily)'].keys():
    listInd.append(elt)
listInd.sort(reverse=True)
for e in listInd:
    coursIndice.append(float(dataInd['Time Series (Daily)'][e]['4. close']))

lenIndice = len(coursIndice)

rentabIndice=[]
for j in range(lenIndice-1):
    rentabIndice.append(100*(coursIndice[j+1]/coursIndice[j] -1 ))

moyenneMarche=sum(rentabIndice)/len(rentabIndice)

HTML code:

    <form action = "http://localhost:5000/pfa/medaf/IndAct" method = "post">
    Tickers:
    <input type = "text" name = "code1" placeholder="Ticker here">

    <input type = "text" name = "code2" placeholder="Ticker here">

    Indice:

    <select name="Ind" size="1" >
    <option   value="^IXIC" > NASDAQ Composite    </option>
    <option   value="^FCHI" > CAC40    </option>
    <option   value="^DJI" > Dow Jones</option>
    </select>

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


问:
Abstract types and type inference
Suppose I have a module that hides some type:

```<code>module Test : sig
  type t
  val make_t : unit -> t
end = struct
  type t = int option
  let make_t () = Some 42
end
</code>```

And I also have a function that operates on optioms:

```<code>let do_work : 'a option -> unit = function
  | Some x -> Printf.printf "Some\n"
  | None   -> Printf.printf "None\n"
</code>```

Not surprisingly, when I call do_work on t instance I get a type error:

```<code>let () =
  do_work @@ Test.make_t ()
</code>```

Error: This expression has type Test.t but an expression was expected of type 'a option

In my application I have t more complex than just int option and I don't want to expose its internals outward. However, I want to tell the compiler that t is actually something option. How can I achieve that?

答:
It seems that what you want is to make t a private type:

```<code>module T : sig
  type t = private int option
  val mk: unit -> t
end = struct
  type t = int option
  let mk () = Some 42
end

let do_work: int option -> unit =
  function
  | None -> print_endline "None"
  | Some i -> print_endline (string_of_int i)

let () =
  do_work (T.mk () :> int option)
</code>```

As with the abstract type solution, it allows some control of the creation of instances of t, but allow to deconstruct such instances (which encapsulation prevents).

Title: Abstract types and type inference

Body:
Suppose I have a module that hides some type:

module Test : sig
  type t
  val make_t : unit -> t
end = struct
  type t = int option
  let make_t () = Some 42
end

And I also have a function that operates on optioms:

let do_work : 'a option -> unit = function
  | Some x -> Printf.printf "Some\n"
  | None   -> Printf.printf "None\n"

Not surprisingly, when I call do_work on t instance I get a type error:

let () =
  do_work @@ Test.make_t ()

Error: This expression has type Test.t but an expression was expected of type 'a option

In my application I have t more complex than just int option and I don't want to expose its internals outward. However, I want to tell the compiler that t is actually something option. How can I achieve that?

Body:
It seems that what you want is to make t a private type:

module T : sig
  type t = private int option
  val mk: unit -> t
end = struct
  type t = int option
  let mk () = Some 42
end

let do_work: int option -> unit =
  function
  | None -> print_endline "None"
  | Some i -> print_endline (string_of_int i)

let () =
  do_work (T.mk () :> int option)

As with the abstract type solution, it allows some control of the creation of instances of t, but allow to deconstruct such instances (which encapsulation prevents).


问:
Vue component not binding style
Hi I'm new at Vue so maybe I am missing something obvious.
I have a component SliderItem which I want to set top position so I add a property to data:

```<code>data () {
    return {
    /*more data*/
     topSliderText: '120px'
    }
}
</code>```

This is the Vue instance

```<code>import { Slider } from 'vue-easy-slider'
var SliderItem = require('./components/easy-slider-item.vue');

new Vue( {
  el: '#slider',
  data () {
    return {
      list: [
        { background: "url('/images/sliders/be.png')", width: '100%', height: '100%' },
      ]
    }
  },
  components: {
    Slider,
    SliderItem
    },
    mounted() {

    }
} );
</code>```

and then in the view

```<code><div class="" id="slider">
<slider animation="fade">
  <slider-item v-bind:style="{top: topSliderText}" v-for="(i, index) in list" :key="index">
    <div :style="i">
        <div class="slider-text">
             <p style="font-size: 5rem; text-align: center;">Page @{{ index +1 }}</p>
        </div>

    </div>
  </slider-item>
</slider>
</code>```

But is not working, the SliderItem has no style, and I get this warn on console

vue-slider.js:561 [Vue warn]: Property or method "topSliderText" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

vue-slider.js:562 [Vue warn]: The computed property "topSliderText" is already defined in data

But when I use Vue chrome extension to see the component, it has the property so... I don't know what I'm doing wrong...

Thanks in advance.

答:
You defined the topSliderText in SliderItem component but making use of it in the Parent Component.

That is the reason you get vue [warn] as vue searches for topSliderText in the parent component's properties.

So define topSliderText as a data property in  the parent component itself

Title: Vue component not binding style

Body:
Hi I'm new at Vue so maybe I am missing something obvious.
I have a component SliderItem which I want to set top position so I add a property to data:

data () {
    return {
    /*more data*/
     topSliderText: '120px'
    }
}

This is the Vue instance

import { Slider } from 'vue-easy-slider'
var SliderItem = require('./components/easy-slider-item.vue');

new Vue( {
  el: '#slider',
  data () {
    return {
      list: [
        { background: "url('/images/sliders/be.png')", width: '100%', height: '100%' },
      ]
    }
  },
  components: {
    Slider,
    SliderItem
    },
    mounted() {

    }
} );

and then in the view

<slider animation="fade">
  <slider-item v-bind:style="{top: topSliderText}" v-for="(i, index) in list" :key="index">

Page @{{ index +1 }}

  </slider-item>
</slider>

But is not working, the SliderItem has no style, and I get this warn on console

vue-slider.js:561 [Vue warn]: Property or method "topSliderText" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

vue-slider.js:562 [Vue warn]: The computed property "topSliderText" is already defined in data

But when I use Vue chrome extension to see the component, it has the property so... I don't know what I'm doing wrong...

Thanks in advance.


问:
Transfer iOS app from one Apple account to other
I want to transfer my iOS app from one apple store account to other. For both accounts I have team agent role and I have logged in with same access details.

At documentation, I found this article and I want to follow similar steps from my side - Transferring and Deleting Apps

But at above reference link, I found this option/link - Transfer App:

When I actually logged into my account, I can't able to find this kind of option to move app from one account to another. Here is screenshot for my account:

So actually where is the app transfer option?

答:
If you haven't published a version of the app yet, don't worry about transferring it, because you can't.

Log into the team you want to transfer to.

Click on My Apps.

Click the + to create a new app, as you did in the other account.

Fill it in.

Forget about the old record - it's just metadata. If it bothers you, you can change almost everything about the unpublished record and use it for something else.

When To Transfer Apps

There's no point in transferring an empty app record. Simply create a new entry in the other iTunes Connect account. The whole point of an app transfer is to preserve reviews and the upgrade path for users. If those weren't a concern, you'd just create a new app entry anyway.

The only downside to this is that you lose the original app identifier (com.example.appname) but since nobody sees that, it doesn't really matter. Adjust your code signing certificates and you'll be fine.

When Transferring Apps Is Allowed

According to the documentation, there are a few conditions for transferring apps:

Both developer accounts must be completely set up.

The app must have a published version.

The app cannot use entitlements for iCloud or Passbook.

The app cannot use (or have ever used) In-App Purchase subscriptions

The app cannot be cannot be In Review.

Any in-app purchases for the app must also not be in review.

Any in-app purchases for the app must not have product IDs that are the same as in-app purchase products on the destination account.

What Transfers, What Doesn't

These things transfer over:

Bundle ID: The app's bundle identifier

iTunes Connect App Record: Metadata (the description and the rest of the app store entry.) The new team name will appear under the app name once the transfer is complete.

User Upgrades: Users will see the next update from the new account.

These things don't transfer over:

Download Stats: App download number don't transfer over. The new developer account will start from zero downloads.

Keychain Access: Keychain access is lost for transferred apps, because the team prefix changes.

Handoff, Universal Links, Shared Web Credentials: If you're using an apple-app-site-association file, you'll need to modify it to include the old app identifier as well as the new one. You want both, because you don't want to break functionality for users who didn't upgrade yet.


问:
Kafka consumer reading messages parallel
Can we have multiple consumers to consume from a topic to achieve parallel processing in kafka.
My use case is to read messages from a single partition in parallel.  </p>

答:
Simply saying we can't achieve partition level parallelism for Consumers by default.

But you can try Akka Streams Kafka (Reactive kafka). Once go through thsese docs.


问:
Modify pre-exist joomla website in localhost
I want to modify a pre-exist Joomla website from web server in localhost. The source files are able to access in cPanel. How do I modify it in localhost?</p>

答:
I understand you want a development setup where you can work while the current setup is unaffected? You can download your current database (using phpmyadmin export) and all files to your own computer, and setup everything there (the procedure will differ on different systems).

An alternative method is to setup a development environment on the existing server:

Setup a subdomain in cpanel, pointing to another folder on your server

Set a password for the subdomain in cpanel (to prevent unauthorized access to your dev site)

Copy your files to the subfolder

Export your database (with phpmyadmin)

In the export sql-file, replace all your table prefixes (something_) with another prefix (testsomething_)

Import the file using phpmyadmin

Change the table profix for your installation in the subdomain

test your site at http://subdomain.yoursite.com

Now you can quite safely develop in your subdomain without affecting the live site. You might affect the live site if there are absolute references to the live site in your code, or if you do stuff that affects the whole server, but in general this should work without problems.


问:
UIMA RUTA annotation at the beginning of sequence
I have sequence of annotations that are instances of the same type (e.g. sequence of CW annotations). I need to remove the first of them (more formally: remove annotation that has no annotations of the same type before in document). Less formally: to remove an annotation at the beginning of document. Example document: "Software StageTools"
So, I tried many variants:

```<code>"Software"{-AFTER(CW) -> UNMARK(CW)} CW+;             //does not work
"Software"{BEFORE(CW) -> UNMARK(CW)} CW+;             //does not work
"Software"{-STARTSWITH(Document) -> UNMARK(CW)} CW+;  //does not work
CW{0, 0} "Software"{-> UNMARK(CW)} CW+;               //getting parsing error
</code>```

...and some other ones. Obviously, no one works (may be, I can refer to begin feature of annotation, but this will not solve formal issue).

At last, the question is - how can I say RUTA to remove annotation that has no annotations of the same type before in document?

答:
There are many ways to do this. Here are two examples:

```<code># cw:CW.ct=="Software"{-> UNMARK(cw)} CW;
</code>```

Remove the first CW "Software" in the document if there is another CW following.

```<code>ANY{-PARTOF(CW)} cw:@CW.ct=="Software"{-> UNMARK(cw)} CW;
</code>```

Remove any CW "Software" if there is a CW following and there is no CW preceding. If the document can start with the pattern, you need a second rule.

Your second rule actually works for me. The last rule has no valid syntax. The min/max quantifier requires different brackets like [0,0]. However, this would not have the effect you want.

DISCLAIMER: I am a developer of UIMA Ruta

Body:
I have sequence of annotations that are instances of the same type (e.g. sequence of CW annotations). I need to remove the first of them (more formally: remove annotation that has no annotations of the same type before in document). Less formally: to remove an annotation at the beginning of document. Example document: "Software StageTools"
So, I tried many variants:

"Software"{-AFTER(CW) -> UNMARK(CW)} CW+;             //does not work
"Software"{BEFORE(CW) -> UNMARK(CW)} CW+;             //does not work
"Software"{-STARTSWITH(Document) -> UNMARK(CW)} CW+;  //does not work
CW{0, 0} "Software"{-> UNMARK(CW)} CW+;               //getting parsing error

...and some other ones. Obviously, no one works (may be, I can refer to begin feature of annotation, but this will not solve formal issue).

At last, the question is - how can I say RUTA to remove annotation that has no annotations of the same type before in document?

Body:
There are many ways to do this. Here are two examples:

# cw:CW.ct=="Software"{-> UNMARK(cw)} CW;

Remove the first CW "Software" in the document if there is another CW following.

ANY{-PARTOF(CW)} cw:@CW.ct=="Software"{-> UNMARK(cw)} CW;

Remove any CW "Software" if there is a CW following and there is no CW preceding. If the document can start with the pattern, you need a second rule.

Your second rule actually works for me. The last rule has no valid syntax. The min/max quantifier requires different brackets like [0,0]. However, this would not have the effect you want.

DISCLAIMER: I am a developer of UIMA Ruta


问:
Find an unused number in a bunch of numbers
I have a huge table filled with numbers (1001001..1009999) and there are certainly a bunch of unused numbers in that area. So, I could have all these numbers returned by doing:

```<code>SELECT MY_IDENTIFIER FROM MY_TABLE
</code>```

that would return all used numbers. How could I get a list of unused numbers from that table? I work serverside (rhino/jaxer) with JavaScript and my database is Oracle 10g.

Thanks,

答:
The following query will give you what you need:

```<code>SELECT seq_num
  FROM (SELECT (lvl + &&v_from - 1) seq_num
          FROM (SELECT *
                  FROM (    SELECT LEVEL lvl
                              FROM DUAL
                        CONNECT BY LEVEL <= (&&v_to - &&v_from) + 1)))
 WHERE seq_num NOT IN (SELECT my_identifier FROM my_table);
</code>```

Replace &&v_to and &&v_from with your boundary numbers.

Reference: http://oraqa.com/2006/01/20/how-to-generate-sequence-numbers-between-two-numbers/

Body:
I have a huge table filled with numbers (1001001..1009999) and there are certainly a bunch of unused numbers in that area. So, I could have all these numbers returned by doing:

SELECT MY_IDENTIFIER FROM MY_TABLE

that would return all used numbers. How could I get a list of unused numbers from that table? I work serverside (rhino/jaxer) with JavaScript and my database is Oracle 10g.

Thanks,

Body:
The following query will give you what you need:

SELECT seq_num
  FROM (SELECT (lvl + &&v_from - 1) seq_num
          FROM (SELECT *
                  FROM (    SELECT LEVEL lvl
                              FROM DUAL
                        CONNECT BY LEVEL <= (&&v_to - &&v_from) + 1)))
 WHERE seq_num NOT IN (SELECT my_identifier FROM my_table);

Replace &&v_to and &&v_from with your boundary numbers.

Reference: http://oraqa.com/2006/01/20/how-to-generate-sequence-numbers-between-two-numbers/


问:
How to fix PDO sqlsrv connection timeout in Laravel?
developer!

I'm using Laravel framework and I need to connect to MS SQL 2014 Express database. I've made all the proper configurations in .env (and I even tried tried to put connection parameters straight away to the database.php config) but on the first request i'm always getting timeouted with error:

```<code>PDOException in Connector.php line 55:
SQLSTATE[08001]: [Microsoft][ODBC Driver 11 for SQL Server]TCP Provider: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
</code>```

After the timeout I always get this php fatal:

```<code>FatalErrorException in Connector.php line 55
Invalid handle returned.
</code>```

As a dev tools I'm using XAMPP, and when I'm restarting apache server, sometimes I can establish connection successfully, but only in 1 out of 20-30 tries.

Laravel is using PDO driver, so i tried to use sqlsrv_connect() - and it worked! No errors, everything is fine.

Can somebody help me configure PDO to work? Laravel only uses PDO driver, so I can't just switch to sqlsrv_connect.

答: I had this problem running on my local machine. I restarted the laravel server and ensured that the ms sql localdb was running and the problem resolved it self.</p>

Body:
developer!

I'm using Laravel framework and I need to connect to MS SQL 2014 Express database. I've made all the proper configurations in .env (and I even tried tried to put connection parameters straight away to the database.php config) but on the first request i'm always getting timeouted with error:

PDOException in Connector.php line 55:
SQLSTATE[08001]: [Microsoft][ODBC Driver 11 for SQL Server]TCP Provider: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

After the timeout I always get this php fatal:

FatalErrorException in Connector.php line 55
Invalid handle returned.

As a dev tools I'm using XAMPP, and when I'm restarting apache server, sometimes I can establish connection successfully, but only in 1 out of 20-30 tries.

Laravel is using PDO driver, so i tried to use sqlsrv_connect() - and it worked! No errors, everything is fine.

Can somebody help me configure PDO to work? Laravel only uses PDO driver, so I can't just switch to sqlsrv_connect.


问:
(Language Agnostic) Design Pattern for Unreliable Data Partner
What is the (generic, any OO) design pattern for the use case where you have a client that puts/gets data from the server, but the server isn't always available?</p>

答:
If the concern is only about availability and the api/system can work with asynchronous communication, I recommend using messaging solutions.

I have personally used:

Custom platform based on Apache Active MQ . Highly scale-able infra piece. You can consider this if you require a solution across your organization or across several service

Apache Camel This is implementation of Enterprise Integration Pattern. If your use case requires integration over numerous technologies and stacks , you can go with Camel.

Not used till now:

JMS Java messaging Queues

Amazon SNS Amazon AWS solution.

Azure Service Bus

There are  a lot more custom libraries for specific stack/language and use cases. You can search for specific ones on google.
You can go through them and select what suits your usecase.


问:
logback encoder pattern with custom string values
Below is my current logback encoder pattern,

```<code><encoder>
            <pattern>%d{yyyy.MM.dd HH:mm:ss} | %-5level | [%thread] | \(%class{25}:%line\) - %msg%n</pattern>
</encoder>
</code>```

Eg:
2017-06-05 11:15:21 | DEBUG | [Thread-10] | (c.s.n.f.s.m.NmsngMessagingImpl:450) - Control reached send()

in java classes, an example of logger is as shown below,

logger.info("request received for the message " + messRecv);

The above pattern works fine for the example shown.

Now i have another example as shown below,

[timestamp][loglevel][systemid][package][class][method][id]message

systemId and id are new entries which are custom values.

May i know how to pass them through logger.

答:
You can add them to the MDC:

```<code>MDC.put("systemId", "value");
MDC.put("id", "value2");
</code>```

The MDC (mapped diagnostic context) is a map of key-value pairs that are managed on a per thread basis.

They can be referenced in the configuration via %X{mdcName}, so your pattern would look like this:

```<code><pattern>%d{yyyy.MM.dd HH:mm:ss} | %-5level | %X{systemId} ... %msg%n</pattern>
</code>```

%X{systemId} will be replaced with the thread's value for "systemId" in the MDC.

Body:
Below is my current logback encoder pattern,

<encoder>
            <pattern>%d{yyyy.MM.dd HH:mm:ss} | %-5level | [%thread] | \(%class{25}:%line\) - %msg%n</pattern>
</encoder>

Eg:
2017-06-05 11:15:21 | DEBUG | [Thread-10] | (c.s.n.f.s.m.NmsngMessagingImpl:450) - Control reached send()

in java classes, an example of logger is as shown below,

logger.info("request received for the message " + messRecv);

The above pattern works fine for the example shown.

Now i have another example as shown below,

[timestamp][loglevel][systemid][package][class][method][id]message

systemId and id are new entries which are custom values.

May i know how to pass them through logger.

Body:
You can add them to the MDC:

MDC.put("systemId", "value");
MDC.put("id", "value2");

The MDC (mapped diagnostic context) is a map of key-value pairs that are managed on a per thread basis.

They can be referenced in the configuration via %X{mdcName}, so your pattern would look like this:

<pattern>%d{yyyy.MM.dd HH:mm:ss} | %-5level | %X{systemId} ... %msg%n</pattern>

%X{systemId} will be replaced with the thread's value for "systemId" in the MDC.


问:
etcd server output some error
I started up with an etcdv3 single server, etcdctl get / put is ok but the server console has some error logs and how to fix it

```<code>2017-06-19 09:26:42.225787 I | etcdserver/api/v3rpc: grpc: addrConn.resetTransport failed to create client transport: connection error: desc = "transport: dial tcp [::]:2379: connect: cannot assign requested address"; Reconnecting to {[::]:2379 <nil>}
2017-06-19 09:27:01.415397 I | etcdserver/api/v3rpc: grpc: addrConn.resetTransport failed to create client transport: connection error: desc = "transport: dial tcp [::]:2379: connect: cannot assign requested address"; Reconnecting to {[::]:2379 <nil>}
2017-06-19 09:27:08.209185 I | etcdserver/api/v3rpc: grpc: addrConn.resetTransport failed to create client transport: connection error: desc = "transport: dial tcp [::]:2379: connect: cannot assign requested address"; Reconnecting to {[::]:2379 <nil>}
2017-06-19 09:27:22.992708 I | etcdserver/api/v3rpc: grpc: addrConn.resetTransport failed to create client transport: connection error: desc = "transport: dial tcp [::]:2379: connect: cannot assign requested address"; Reconnecting to {[::]:2379 <nil>}
2017-06-19 09:27:40.156845 I | etcdserver/api/v3rpc: grpc: addrConn.resetTransport failed to create client transport: connection error: desc = "transport: dial tcp [::]:2379: connect: cannot assign requested address"; Reconnecting to {[::]:2379 <nil>}
</code>```

server start script is :

```<code>docker run \
  --rm \
  -p 2379:2379 \
  -p 2380:2380 \
  --name etcd-v3 \
  --volume=/data/docker/etcd-sigle-data:/etcd-data \
  quay.io/coreos/etcd:v3.2.0 \
  /usr/local/bin/etcd \
  --name my-etcd \
  --data-dir /etcd-data \
  --listen-client-urls http://0.0.0.0:2379 \
  --advertise-client-urls http://xxx.xxx.xxx.xxx:2379
  --listen-peer-urls http://0.0.0.0:2380 \
  --initial-advertise-peer-urls http://xxx.xxx.xxx.xxx:2380 \
  --initial-cluster my-etcd=http://xxx.xxx.xxx.xxx:2380 \
  --initial-cluster-token etcd-cluster-token \
  --initial-cluster-state new \
  --auto-compaction-retention 1
</code>```

答: Looks like the trouble is related to connecting via ipv6. Try switching to ipv4 by specifiying proper IP address instead of 0.0.0.0 wildcard in --listen-client-urls.

Title: etcd server output some error

Body:
I started up with an etcdv3 single server, etcdctl get / put is ok but the server console has some error logs and how to fix it

2017-06-19 09:26:42.225787 I | etcdserver/api/v3rpc: grpc: addrConn.resetTransport failed to create client transport: connection error: desc = "transport: dial tcp [::]:2379: connect: cannot assign requested address"; Reconnecting to {[::]:2379 <nil>}
2017-06-19 09:27:01.415397 I | etcdserver/api/v3rpc: grpc: addrConn.resetTransport failed to create client transport: connection error: desc = "transport: dial tcp [::]:2379: connect: cannot assign requested address"; Reconnecting to {[::]:2379 <nil>}
2017-06-19 09:27:08.209185 I | etcdserver/api/v3rpc: grpc: addrConn.resetTransport failed to create client transport: connection error: desc = "transport: dial tcp [::]:2379: connect: cannot assign requested address"; Reconnecting to {[::]:2379 <nil>}
2017-06-19 09:27:22.992708 I | etcdserver/api/v3rpc: grpc: addrConn.resetTransport failed to create client transport: connection error: desc = "transport: dial tcp [::]:2379: connect: cannot assign requested address"; Reconnecting to {[::]:2379 <nil>}
2017-06-19 09:27:40.156845 I | etcdserver/api/v3rpc: grpc: addrConn.resetTransport failed to create client transport: connection error: desc = "transport: dial tcp [::]:2379: connect: cannot assign requested address"; Reconnecting to {[::]:2379 <nil>}

server start script is :

docker run \
  --rm \
  -p 2379:2379 \
  -p 2380:2380 \
  --name etcd-v3 \
  --volume=/data/docker/etcd-sigle-data:/etcd-data \
  quay.io/coreos/etcd:v3.2.0 \
  /usr/local/bin/etcd \
  --name my-etcd \
  --data-dir /etcd-data \
  --listen-client-urls http://0.0.0.0:2379 \
  --advertise-client-urls http://xxx.xxx.xxx.xxx:2379
  --listen-peer-urls http://0.0.0.0:2380 \
  --initial-advertise-peer-urls http://xxx.xxx.xxx.xxx:2380 \
  --initial-cluster my-etcd=http://xxx.xxx.xxx.xxx:2380 \
  --initial-cluster-token etcd-cluster-token \
  --initial-cluster-state new \
  --auto-compaction-retention 1