问:
Failed query in mysql Database
Good afternoon,
I dont get to see any error in my code and i have been getting Mysql Errors along the line.

My code looks like this

```<code><?php
include 'account_numgen.php';
require_once('inc/config.php');

$con = mysqli_connect($host,$user,$pass, $db)or die ('Cannot Connect :'.mysqli_error());

$account_number = mysqli_real_escape_string($con,$_POST['account_number']);
$first_name = mysqli_real_escape_string($con,$_POST['first_name']);
$mi = mysqli_real_escape_string($con,$_POST['mi']);
$last_name = mysqli_real_escape_string($con,$_POST['last_name']);
$address = mysqli_real_escape_string($con,$_POST['address']);
$address2 = mysqli_real_escape_string($con,$_POST['address2']);
$city = mysqli_real_escape_string($con,$_POST['city']);
$tel = mysqli_real_escape_string($con,$_POST['tel']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$nok_1 = mysqli_real_escape_string($con,$_POST['nok_1']);
$nok1_address = mysqli_real_escape_string($con,$_POST['nok1_address']);
$nok1_address2 = mysqli_real_escape_string($con,$_POST['nok1_address2']);
$nok1_city = mysqli_real_escape_string($con,$_POST['nok1_city']);
$nok_2 = mysqli_real_escape_string($con,$_POST['nok_2']);
$nok2_address = mysqli_real_escape_string($con,$_POST['nok2_address']);
$nok2_address2 = mysqli_real_escape_string($con,$_POST['nok2_address2']);
$nok2_city = mysqli_real_escape_string($con,$_POST['nok2_city']);
$id_type = mysqli_real_escape_string($con,$_POST['id_type']);
$id_number = mysqli_real_escape_string($con,$_POST['id_number']);
$open_bal = mysqli_real_escape_string($con,$_POST['open_bal']);
$passport_name = $_FILES['passport']['name'];
$passport_size = $_FILES['passport']['size'];
$passport_type = $_FILES['passport']['type'];
$passporttmp_name = $_FILES['passport']['tmp_name'];

$signature_name = $_FILES['signature']['name'];
$signature_size = $_FILES['signature']['size'];
$signature_type = $_FILES['signature']['type'];
$signaturetmp_name = $_FILES['signature']['tmp_name'];

$sql = "insert into bank_details(account_number,first_name,mi,last_name,address,address2,city,tel,email,nok_1,nok1_address,nok1_address2,nok1_city,nok_2,nok2_address,nok2_address2,nok2_city,id_type,id_number,open_bal,passport_name,passport_size,passport_type,passporttmp_name,signature_name,signature_size,signature_type,signaturetmp_name) values ('".$account_number."','".$first_name."','".$mi."','".$last_name."','".$address."','".$address2."','".$city."','".$tel."','".$email."','".$nok_1."','".$nok1_address."','".$nok1_address2."','".$nok1_city."','".$nok_2."','".$nok2_address."','".$nok2_address2."','".$nok2_city."','".$id_type."','".$id_number."','".$open_bal."','".$passport_name."','".$passport_size."','".$passport_type."','".$passporttmp_name."','".$signature_name."','".$signature_size."','".$signature_type."','".$signaturetmp_name."')";
mysqli_query($con,$sql) or die ('Failed Query: '.mysqli_error($con));

$passport_dir = 'passport/';
$signature_dir = 'signature/';

$filePath1 = $passport_dir . $passport_name;
$filePath2 = $signature_dir . $signature_name;

$result1 = move_uploaded_file($passporttmp_name,$filePath1);
$result2 = move_uploaded_file($signaturetmp_name,$filePath2);

echo ('
<SCRIPT LANGUAGE="JavaScript">
   window.alert("Account Information \n Account Number: '.$account_number.'\n First Name: '.$first_name.'\n Last Name: '.$last_name.'\n Last Name: '.$open_bal.'")
   window.location.href="index.html";
</SCRIPT>
');

?>
</code>```

Now i get this Error

```<code>Failed Query: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 's_Signature.png','78716','image/png','C:\xampp\tmp\phpD784.tmp')' at line 1
</code>```

Why is this so? i dont get to see any errors in My code, How ever it has stopped posting to the database on My Local host.

Edit

When i add mysqli_real_escape_string($con, $_FILES[....]) it works fine, but it doesnt send the images from the application to the localhost server what exactly can be the case?

答:
Use mysqli_real_escape_string on all the fields, including what you get in $_FILES

Apparently there is a quote in the name...
And the way you used it the path would be wrong, because it should be \\ instead of every \, otherwise \t is a tab.

Title: Failed query in mysql Database

Body:
Good afternoon,
I dont get to see any error in my code and i have been getting Mysql Errors along the line.

My code looks like this

<?php
include 'account_numgen.php';
require_once('inc/config.php');

$con = mysqli_connect($host,$user,$pass, $db)or die ('Cannot Connect :'.mysqli_error());

$account_number = mysqli_real_escape_string($con,$_POST['account_number']);
$first_name = mysqli_real_escape_string($con,$_POST['first_name']);
$mi = mysqli_real_escape_string($con,$_POST['mi']);
$last_name = mysqli_real_escape_string($con,$_POST['last_name']);
$address = mysqli_real_escape_string($con,$_POST['address']);
$address2 = mysqli_real_escape_string($con,$_POST['address2']);
$city = mysqli_real_escape_string($con,$_POST['city']);
$tel = mysqli_real_escape_string($con,$_POST['tel']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$nok_1 = mysqli_real_escape_string($con,$_POST['nok_1']);
$nok1_address = mysqli_real_escape_string($con,$_POST['nok1_address']);
$nok1_address2 = mysqli_real_escape_string($con,$_POST['nok1_address2']);
$nok1_city = mysqli_real_escape_string($con,$_POST['nok1_city']);
$nok_2 = mysqli_real_escape_string($con,$_POST['nok_2']);
$nok2_address = mysqli_real_escape_string($con,$_POST['nok2_address']);
$nok2_address2 = mysqli_real_escape_string($con,$_POST['nok2_address2']);
$nok2_city = mysqli_real_escape_string($con,$_POST['nok2_city']);
$id_type = mysqli_real_escape_string($con,$_POST['id_type']);
$id_number = mysqli_real_escape_string($con,$_POST['id_number']);
$open_bal = mysqli_real_escape_string($con,$_POST['open_bal']);
$passport_name = $_FILES['passport']['name'];
$passport_size = $_FILES['passport']['size'];
$passport_type = $_FILES['passport']['type'];
$passporttmp_name = $_FILES['passport']['tmp_name'];

$signature_name = $_FILES['signature']['name'];
$signature_size = $_FILES['signature']['size'];
$signature_type = $_FILES['signature']['type'];
$signaturetmp_name = $_FILES['signature']['tmp_name'];

$sql = "insert into bank_details(account_number,first_name,mi,last_name,address,address2,city,tel,email,nok_1,nok1_address,nok1_address2,nok1_city,nok_2,nok2_address,nok2_address2,nok2_city,id_type,id_number,open_bal,passport_name,passport_size,passport_type,passporttmp_name,signature_name,signature_size,signature_type,signaturetmp_name) values ('".$account_number."','".$first_name."','".$mi."','".$last_name."','".$address."','".$address2."','".$city."','".$tel."','".$email."','".$nok_1."','".$nok1_address."','".$nok1_address2."','".$nok1_city."','".$nok_2."','".$nok2_address."','".$nok2_address2."','".$nok2_city."','".$id_type."','".$id_number."','".$open_bal."','".$passport_name."','".$passport_size."','".$passport_type."','".$passporttmp_name."','".$signature_name."','".$signature_size."','".$signature_type."','".$signaturetmp_name."')";
mysqli_query($con,$sql) or die ('Failed Query: '.mysqli_error($con));

$passport_dir = 'passport/';
$signature_dir = 'signature/';

$filePath1 = $passport_dir . $passport_name;
$filePath2 = $signature_dir . $signature_name;

$result1 = move_uploaded_file($passporttmp_name,$filePath1);
$result2 = move_uploaded_file($signaturetmp_name,$filePath2);

echo ('

');

?>

Now i get this Error

Failed Query: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 's_Signature.png','78716','image/png','C:\xampp\tmp\phpD784.tmp')' at line 1

Why is this so? i dont get to see any errors in My code, How ever it has stopped posting to the database on My Local host.

Edit

When i add mysqli_real_escape_string($con, $_FILES[....]) it works fine, but it doesnt send the images from the application to the localhost server what exactly can be the case?


来源: stackexchange

问:
VueJs. Is it possible to pass one <slot> througth another?
Example (jsfiddle):
I wont to pass <component-a> into slot 'two' in the <component-c>

//file #1

```<code><component-b>
    <component-a slot="... ? ..."></component-a>
</component-b>
</code>```

I have problem in the file #2. I don't understand how I can pass <component-a> through <component-b> to slot='two' in component .

//file #2 with <component-b>

```<code><div>
    <components-c>
        // I was thinking to do it this way,
        // but as I see It doesn't work:
        // <slot name='one' slot='one'></slot>
        // <slot name='two' slot='two'></slot>
    </components-c>
</div>
</code>```

//file #3  with <component-c>

```<code><components-c>
    <div id='one'>
        <slot name="one"></slot>
    </div>
    <div id='two'>
        <slot name="two"></slot>
    </div>
</components-c>
</code>```

答:
It's not possible for a <slot> to be the source for another slot (by using the slot attribute) in the parent component. To allow this would mean that a single element (i.e. VNode) would need to have more than one slot value for the slots that it would be rendered within as you go up the node tree.

This is not allowed:

```<code><slot slot="one"></slot>
</code>```

It will work if you wrap your slot in a div first like this:

```<code><div slot="one">
  <slot name="one"></slot>
</div>
</code>```

Here's a fiddle with your updated example.

ContentLicense: CC BY-SA 3.0

Body:
Example (jsfiddle):
I wont to pass <component-a> into slot 'two' in the <component-c>

//file #1

<component-b>
    <component-a slot="... ? ..."></component-a>
</component-b>

I have problem in the file #2. I don't understand how I can pass <component-a> through <component-b> to slot='two' in component .

//file #2 with <component-b>

    <components-c>
        // I was thinking to do it this way,
        // but as I see It doesn't work:
        // <slot name='one' slot='one'></slot>
        // <slot name='two' slot='two'></slot>
    </components-c>

//file #3  with <component-c>

<components-c>

        <slot name="one"></slot>

        <slot name="two"></slot>

</components-c>

Body:
It's not possible for a <slot> to be the source for another slot (by using the slot attribute) in the parent component. To allow this would mean that a single element (i.e. VNode) would need to have more than one slot value for the slots that it would be rendered within as you go up the node tree.

This is not allowed:

<slot slot="one"></slot>

It will work if you wrap your slot in a div first like this:

<div slot="one">
  <slot name="one"></slot>
</div>

Here's a fiddle with your updated example.


问:
Prism VM binding with View within Page code behind
Using Xamarin Forms & PCL

I saw a lot of examples and snippets About binding VM with View in the Page.Xaml

using this block

```<code>xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
      prism:ViewModelLocator.AutowireViewModel="True"
</code>```

And what if I want to bind the view model within the page code behind (Page.cs).

答:
That case you have to pass the both parameter on class instantiated because you are have required two parameter in constructor.Try the below code.</p>

```<code> public Page()
{
    InitializeComponent();
    this.BindingContext = new PageViewModel(Navigation,PageDialogService);
}
</code>```

Body:
Using Xamarin Forms & PCL

I saw a lot of examples and snippets About binding VM with View in the Page.Xaml

using this block

xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
      prism:ViewModelLocator.AutowireViewModel="True"

And what if I want to bind the view model within the page code behind (Page.cs).

Body:
That case you have to pass the both parameter on class instantiated because you are have required two parameter in constructor.Try the below code.

 public Page()
{
    InitializeComponent();
    this.BindingContext = new PageViewModel(Navigation,PageDialogService);
}


问:
how to optimise a view having derived tabels
I have a situation , i have one view , whose structure is like following

```<code>select x.*,d.*

from x

left join (

select x, y,z,poleid from y -- and pivot is done here

) as d

on x.poleid=d.poleid

where x.country =1

  I am calling it like so, select * from view1 where country=1
</code>```

q1) I have seen the plan, it filters on table x but  it takes time in left join, because it gets whole data and then pivot it,

if i could put the filter y.country =1 in side,
then it would have been fast.

```<code> but that can not be done as view does not take parameter.
</code>```

so please suggest is there any way to speed up the view.

yours sincerely

答:
Perhaps consider a TVF (Table-Valued Function)

Example

```<code>CREATE Function [dbo].[MyFuncName] (@country int)
Returns Table
Return (
    Select x.*,d.*
     From  x
     Left Join (select x, y,z,poleid from y ) as d on x.poleid=d.poleid
     where x.country = @country
)
</code>```

Usage

```<code>Select * From [dbo].[MyFuncName](1)
</code>```

Body:
I have a situation , i have one view , whose structure is like following

select x.*,d.*

from x

left join (

select x, y,z,poleid from y -- and pivot is done here

) as d

on x.poleid=d.poleid

where x.country =1

  I am calling it like so, select * from view1 where country=1

q1) I have seen the plan, it filters on table x but  it takes time in left join, because it gets whole data and then pivot it,

if i could put the filter y.country =1 in side,
then it would have been fast.

 but that can not be done as view does not take parameter.

so please suggest is there any way to speed up the view.

yours sincerely

Body:
Perhaps consider a TVF (Table-Valued Function)

Example

CREATE Function [dbo].[MyFuncName] (@country int)
Returns Table
Return (
    Select x.*,d.*
     From  x
     Left Join (select x, y,z,poleid from y ) as d on x.poleid=d.poleid
     where x.country = @country
)

Usage

Select * From [dbo].[MyFuncName](1)


问:
Assigning Number Values to String Array
I am trying to find a way to make an array with strings have values such as [1, 2, 3, 4,...] and so on.I believe I saw a way to do it utilizing 'indexOf + 1' thanks for any help.</p>

```<code>function sortGrades(lst){
var grades = ["VB", "V0", "V0+","V1", "V2", "V3", "V4", "V5", "V6", "V7",
"V8",` "V9", "V10", "V11", "V12", "V13", "V14", "V15", "V16", "V17"];

 }
</code>```

答:
You can simply using map:

var grades = ["VB", "V0", "V0+","V1", "V2", "V3", "V4", "V5", "V6", "V7",
"V8", "V9", "V10", "V11", "V12", "V13", "V14", "V15", "V16", "V17"];
var numericGrades = grades.map((grade, index) => index + 1);

console.log(numericGrades);```

Title: Assigning Number Values to String Array

Body:
I am trying to find a way to make an array with strings have values such as [1, 2, 3, 4,...] and so on.I believe I saw a way to do it utilizing 'indexOf + 1' thanks for any help.

function sortGrades(lst){
var grades = ["VB", "V0", "V0+","V1", "V2", "V3", "V4", "V5", "V6", "V7",
"V8",` "V9", "V10", "V11", "V12", "V13", "V14", "V15", "V16", "V17"];

 }


问:
How to get state from child to parent react
I'm new in React

I have two components. Parent Square, child Row.

I want to get setValues cellTop and cellLeft from Row to parent and use it.

How can I do it.

My code is bellow

var Square = React.createClass({

 getInitialState: function () {

  return {

  countRow: 4,
  countCol: 4,
  mouseOnTable: false,
  onDelRow: false,
  onDelCol: false

  }

 },

 appendCol: function() {

  var countColNew = this.state.countCol + 1;

  this.setState({countCol: countColNew});  //change initiale state "countCol" (add new column)

  //console.log(this.state.countCol)

 },

 appendRow: function() {

  var countRowNew = this.state.countRow + 1;

  this.setState({countRow: countRowNew});  //change initiale state "countRow" (add new row)

  //console.log(this.state.countRow)

 },

 deleteCol: function() {

  var countColNew = this.state.countCol - 1;

  this.setState({countCol: countColNew});  //change initiale state "countCol" (delete col)

  //console.log(this.state.countCol)

 },

 deleteRow: function() {

  var countRowNew = this.state.countRow - 1;

  this.setState({countRow: countRowNew});  //change initiale state (delete row)

  //console.log(this.state.countRow)

 },

 hiddenButtons: function(){
  var mouseOnTableNew = true;
  this.setState({mouseOnTable: mouseOnTableNew})
 },

 showButtons: function(){
  var mouseOnTableNew = false;
  this.setState({mouseOnTable: mouseOnTableNew})
 },

 render: function() {

  var timeOut;

  return (

 {timeOut=setTimeout(this.showButtons,200)}}>

       <Row countRow={this.state.countRow}
         countCol={this.state.countCol}
         ref={(ref) => this.state}

         />

       <button className="square__button square__button_append square__button_col-append"
         onClick={this.appendCol}>
       </button>

             <button className="square__button square__button_delete square__button_col-delete"
               style={this.state.countCol===1 ||
                   this.state.mouseOnTable===false ||
                   this.state.onDelRow===true ? {visibility: "hidden"} : {visibility: "visible"}}

               onClick={this.deleteCol}
               onMouseOver={() => {clearTimeout(timeOut);
                    this.setState({onDelCol:true})}}
               onMouseLeave={() => {this.setState({onDelCol:false})}}>
             </button>

             <button className="square__button square__button_append square__button_row-append"
               onClick={this.appendRow}>
             </button>

             <button className="square__button square__button_delete square__button_row-delete"
               style={this.state.countRow===1 ||
                   this.state.mouseOnTable===false ||
                   this.state.onDelCol===true ? {visibility: "hidden"} : {visibility: "visible"}}

               onClick={this.deleteRow}

               onMouseOver={() => {clearTimeout(timeOut);
                    this.setState({onDelRow:true})}}

               onMouseLeave={() => {this.setState({onDelRow:false})}}>
             </button>

  )

 }

})

//==================================================

var Row = React.createClass({

 getInitialState: function(){
  return {

   cellTop: 0,
   cellLeft: 0,

  }

 },

 createCol: function() {

  var columns = [];

  for(let i = 0; i < this.props.countCol; i++){
   columns.push(this.createCell)
  }

  return columns;

 },

 createRow: function (k) {

  return (

    {this.createCol().map(function(cell,key){
     return (
       cell(key)
      )
    })}

  )
 },

 createCell: function(k){

  return (

  )

 },

 getMousePosition: function(element){

  let coordinates = element.target.getBoundingClientRect();
  let top = coordinates.top;
  let left = coordinates.left;

  this.setState({
   cellTop: top,
   cellLeft: left
  })

 },

 render: function(){

   var lines = []
   for (let i = 0; i < this.props.countRow; i++) {
   lines.push(this.createRow(i))
  }

  return (

    {lines}

  )
 }

})```

答:
I would recommend you to not use state in components at all. This just leads to problems when you want to control parent component from child.

Instead,

make all components to receive data via props

move state and all data into external object (store)

make the store update your components when the data changes

from components just update store

Look at https://github.com/reflux/refluxjs

```<code>+---------+       +--------+       +-----------------+
¦ Actions ¦------>¦ Stores ¦------>¦ View Components ¦
+---------+       +--------+       +-----------------+
     ^                                      ¦
     +--------------------------------------+
</code>```

Body:
I would recommend you to not use state in components at all. This just leads to problems when you want to control parent component from child.

Instead,

make all components to receive data via props

move state and all data into external object (store)

make the store update your components when the data changes

from components just update store

Look at https://github.com/reflux/refluxjs

+---------+       +--------+       +-----------------+
¦ Actions ¦------>¦ Stores ¦------>¦ View Components ¦
+---------+       +--------+       +-----------------+
     ^                                      ¦
     +--------------------------------------+


问:
How do I prevent Google Chrome from blocking my popup?
On my website there is a button that just used to call a function that calls window.open, however, recently an adjustment was needed to do a server-side check before the popup was opened.

Ever since the code was added that does the AJAX call, browsers blocks the popup, that is opened in the success callback of the AJAX call. I read that browsers might block the popup if it's not called by a user click event, so I tried setting the AJAX request to async: false, which solved the problem in Firefox, but Google Chrome still keeps blocking my popup. Is there any way to get around this?

I could move the server-side check to the page that gets opened in the popup, but I'd like to do it before opening the popup, if possible.

Code:

```<code><a id="attackButton" href="#">Attack Base!</a>

<script type="text/javascript">
$(function() {
    $('#attackButton').click(function() {
        $.ajax({
            url: baseurl + '/index.php?option=com_pbbgs&format=raw&getinfo=goingame',
            data: { 'gameid': 618 },
            dataType: 'text',
            async: false,
            type: 'POST',
            success: function(data) {
                eval(data);

                if (window.gameURL) {
                    goingameRaw();
                }
            }
        });

        return false;
    });
});

function goingameRaw()
{
    window.open(window.gameURL,'test','left=20,top=20,width=1024,height=640,toolbar=0,resizable=0,location=0');
}
</script>
</code>```

Example response body:

```<code>window.gameURL="http://mydomain.com/index.php?option=com_pbbgs&format=raw&startgame=618&width=1024&height=640";checktutorial('js','attack');
</code>```

答:
I use this method:

Redirect to the same page with download url added as parameter:

window.location.href = window.location.protocol + '//' +
                    window.location.host + window.location.pathname +
                    "?download=" + encodeURIComponent(urlToDownload)
```

<ol start="2">
<li>Detect this parameter on page initialization and redirect to download:</li>
</ol>

<pre class="lang-js prettyprint-override"><code>function param(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (!results) { return 0; }
    return results[1] || 0;
}

var downloadParam = param('download');
if (downloadParam) {
    window.location = decodeURIComponent(downloadParam);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
On my website there is a button that just used to call a function that calls window.open, however, recently an adjustment was needed to do a server-side check before the popup was opened.

Ever since the code was added that does the AJAX call, browsers blocks the popup, that is opened in the success callback of the AJAX call. I read that browsers might block the popup if it's not called by a user click event, so I tried setting the AJAX request to async: false, which solved the problem in Firefox, but Google Chrome still keeps blocking my popup. Is there any way to get around this?

I could move the server-side check to the page that gets opened in the popup, but I'd like to do it before opening the popup, if possible.

Code:

Attack Base!

Example response body:

window.gameURL="http://mydomain.com/index.php?option=com_pbbgs&format=raw&startgame=618&width=1024&height=640";checktutorial('js','attack');

Body:
I use this method:

Redirect to the same page with download url added as parameter:

window.location.href = window.location.protocol + '//' +
                    window.location.host + window.location.pathname +
                    "?download=" + encodeURIComponent(urlToDownload)

Detect this parameter on page initialization and redirect to download:

function param(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (!results) { return 0; }
    return results[1] || 0;
}

var downloadParam = param('download');
if (downloadParam) {
    window.location = decodeURIComponent(downloadParam);
}


问:
How can I use multiple guard (or if let) statements without exiting the code in Swift?
I tried to perform simple mathematical calculations based on input from several textfields. When one field is not filled in, I would like to continue the calculation for other fields. However, this does not work with my use of the (inappropriate?) guard statement.

Put simply:

If field1 is filled in, perform calculation (i.e. multiply that amount by 0.5) and store the result.

If field2 is filled in, perform calculation (i.e. multiply that amount by 0.2) and store the result.

etc.

As an absolute beginner, I tried this:

```<code>@IBAction func calculate(_ sender: Any) {
    //amount 1
    guard let amount1 = textField1.text else{
        return}
    guard let amount1double = Double(amount1) else{
        return}

    var amt1 = amount1double
    amt1 = amt1 * 0.5

    //amount 2
    guard let amount2 = textField2.text else{
        return }

    guard let amount2double = Double(amount2) else{
        return }

    var amt2 = amount2double
    amt2 = amt2 * 0.2
}
</code>```

The above code will stop if textField1 is not filled in. However I want the code to continue to calculate amount2 if textField1 is empty.

I read about if let statements to maybe continue with the rest of the code after a nil in the texfField, however I could not make it work. Furthermore I understand this will only allow me to access that value within that block.

The goal is to ultimately get the highest / maximum amount from all calculated amounts, if available.

答:
Hi you can do like this:</p>

```<code>@IBAction func calculate(_ sender: Any) {
    //amount 1
    let amount1double = calculateAmountTxt1()
    //amount 2
    let amount2double = calculateAmountTxt2()

    var amt1 = amount1double
    amt1 = amt1 * 0.5

    var amt2 = amount2double
    amt2 = amt2 * 0.2
}

func calculateAmountTxt1()->CGFloat{
     //amount 1
    guard let amount1 = textField1.text, let amount1double = Double(amount1)else {
       return 0
    }
    return amount1double
}

func calculateAmountTxt2()->CGFloat{
    //amount 2
    guard let let amount2 = textField2.text,let amount2double = Double(amount2)else {
       return 0
    }
    return amount2double
}
</code>```

Body:
I tried to perform simple mathematical calculations based on input from several textfields. When one field is not filled in, I would like to continue the calculation for other fields. However, this does not work with my use of the (inappropriate?) guard statement.

Put simply:

If field1 is filled in, perform calculation (i.e. multiply that amount by 0.5) and store the result.

If field2 is filled in, perform calculation (i.e. multiply that amount by 0.2) and store the result.

etc.

As an absolute beginner, I tried this:

@IBAction func calculate(_ sender: Any) {
    //amount 1
    guard let amount1 = textField1.text else{
        return}
    guard let amount1double = Double(amount1) else{
        return}

    var amt1 = amount1double
    amt1 = amt1 * 0.5

    //amount 2
    guard let amount2 = textField2.text else{
        return }

    guard let amount2double = Double(amount2) else{
        return }

    var amt2 = amount2double
    amt2 = amt2 * 0.2
}

The above code will stop if textField1 is not filled in. However I want the code to continue to calculate amount2 if textField1 is empty.

I read about if let statements to maybe continue with the rest of the code after a nil in the texfField, however I could not make it work. Furthermore I understand this will only allow me to access that value within that block.

The goal is to ultimately get the highest / maximum amount from all calculated amounts, if available.

Body:
Hi you can do like this:

@IBAction func calculate(_ sender: Any) {
    //amount 1
    let amount1double = calculateAmountTxt1()
    //amount 2
    let amount2double = calculateAmountTxt2()

    var amt1 = amount1double
    amt1 = amt1 * 0.5

    var amt2 = amount2double
    amt2 = amt2 * 0.2
}

func calculateAmountTxt1()->CGFloat{
     //amount 1
    guard let amount1 = textField1.text, let amount1double = Double(amount1)else {
       return 0
    }
    return amount1double
}

func calculateAmountTxt2()->CGFloat{
    //amount 2
    guard let let amount2 = textField2.text,let amount2double = Double(amount2)else {
       return 0
    }
    return amount2double
}


问:
Redirect to custom error page if there is error in the page
I am new to PHP web development. I want to know is there any code in PHP that redirects me to a page(let's name it "myerrorpage.php") if there is some error on the page?

In JSP it's possible using the following code

```<code><%@ page errorPage="myerrorpage.jsp" %>
</code>```

I want to know is there any above JSP type of code in PHP?is yes then please help

Any help is appreciated...

答:
It's simple..

You just need to enable by configuring httpd.conf file which is located in xampp/apache/conf/httpd.conf

Search for <Directory "C:/xampp/htdocs">.

Under the section, look for #AllowOverride All

Just Remove the '#' which means comment and you're ready for the further step.

The next thing you need to do is create a file named '.htaccess' on you root directory.

Make sure it is just .htaccess

Edit using your favorite text editor(Sublime, Atom, Notepad++, etc)

Write the code....

.

```<code>ErrorDocument 404 YourDirectory/error page
</code>```

eg.

```<code>ErrorDocument 404 http://localhost/project/error.php
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to PHP web development. I want to know is there any code in PHP that redirects me to a page(let's name it "myerrorpage.php") if there is some error on the page?

In JSP it's possible using the following code

<%@ page errorPage="myerrorpage.jsp" %>

I want to know is there any above JSP type of code in PHP?is yes then please help

Any help is appreciated...

Body:
It's simple..

You just need to enable by configuring httpd.conf file which is located in xampp/apache/conf/httpd.conf

Search for <Directory "C:/xampp/htdocs">.

Under the section, look for #AllowOverride All

Just Remove the '#' which means comment and you're ready for the further step.

The next thing you need to do is create a file named '.htaccess' on you root directory.

Make sure it is just .htaccess

Edit using your favorite text editor(Sublime, Atom, Notepad++, etc)

Write the code....

.

ErrorDocument 404 YourDirectory/error page

eg.

ErrorDocument 404 http://localhost/project/error.php


问:
Click one div in order to open only it's children and not other with same class
So I tried obviously using $('this .classname') but it toggle closes the whole div.
I'm trying to have each div (image is placed) be clicked and only it's ul be opened.

HTML

```<code><div class="col-md-12 col-xs-12">

    <div class="recipePicContainer">
        <div id="checkBoxes">
                <li class="recipe" id="recipe01"><label>Cocktail</label></li>
                       <ul class="recipes">
                           <li class="ingredient"><input type="checkbox"> ingredient 1</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 2</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 3</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 4</li>
                            <li class="instructions">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
                       </ul>
                </div>
            </div>

        <div class="recipePicContainer">
            <div class="checkBoxes">
                <li class="recipe" id="recipe02"><label>Main Dish</label></li>
                       <ul class="recipes">
                           <li class="ingredient"><input type="checkbox"> ingredient 1</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 2</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 3</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 4</li>
                            <li class="instructions">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
                       </ul>
                </div>
            </div>

        <div class="recipePicContainer">
            <div class="checkBoxes">
                <li class="recipe" id="recipe03"><label>Dessert</label></li>
                       <ul class="recipes">
                           <li class="ingredient"><input type="checkbox"> ingredient 1</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 2</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 3</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 4</li>
                            <li class="instructions">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
                       </ul>
                </div>
            </div>

</div>
</code>```

JS

```<code>var main = function() {
    $(document).ready(function () {
        $('ul').hide();
        $('.recipe').click(function () {
            $('.recipes').toggle("slow").toggleClass('selected');
        });
    });
};
$(document).ready(main);
</code>```

答:
var main = function() {
  $(document).ready(function () {
      $('.recipe').click(function(e){
        e.stopPropagation();
        $(this).siblings('.recipes').toggle('slow');
      });
  });
}
$(document).ready(main);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.recipes{
  display:none;
}
.recipe{
  padding-left:20px;
}</code>```

Cocktail

<input type="checkbox"> ingredient 1

<input type="checkbox"> ingredient 2

<input type="checkbox"> ingredient 3

<input type="checkbox"> ingredient 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Main Dish

<input type="checkbox"> ingredient 1

<input type="checkbox"> ingredient 2

<input type="checkbox"> ingredient 3

<input type="checkbox"> ingredient 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Dessert

<input type="checkbox"> ingredient 1

<input type="checkbox"> ingredient 2

<input type="checkbox"> ingredient 3

<input type="checkbox"> ingredient 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

```

Body:
So I tried obviously using $('this .classname') but it toggle closes the whole div.
I'm trying to have each div (image is placed) be clicked and only it's ul be opened.

HTML

Cocktail

<input type="checkbox"> ingredient 1

<input type="checkbox"> ingredient 2

<input type="checkbox"> ingredient 3

<input type="checkbox"> ingredient 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Main Dish

<input type="checkbox"> ingredient 1

<input type="checkbox"> ingredient 2

<input type="checkbox"> ingredient 3

<input type="checkbox"> ingredient 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Dessert

<input type="checkbox"> ingredient 1

<input type="checkbox"> ingredient 2

<input type="checkbox"> ingredient 3

<input type="checkbox"> ingredient 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

JS

var main = function() {
    $(document).ready(function () {
        $('ul').hide();
        $('.recipe').click(function () {
            $('.recipes').toggle("slow").toggleClass('selected');
        });
    });
};
$(document).ready(main);

Body:
var main = function() {
  $(document).ready(function () {
      $('.recipe').click(function(e){
        e.stopPropagation();
        $(this).siblings('.recipes').toggle('slow');
      });
  });
}
$(document).ready(main);

.recipes{
  display:none;
}
.recipe{
  padding-left:20px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 col-xs-12">

    <div class="recipePicContainer">
        <div id="checkBoxes">
        <ul class="recipe" id="recipe01">
          <li>Cocktail</li>
        </ul>
                       <ul class="recipes">
                           <li class="ingredient"><input type="checkbox"> ingredient 1</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 2</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 3</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 4</li>
                            <li class="instructions">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
                       </ul>
                </div>
            </div>

        <div class="recipePicContainer">
            <div class="checkBoxes">
              <ul class="recipe" id="recipe02">
                <li>Main Dish</li>
              </ul>
                       <ul class="recipes">
                           <li class="ingredient"><input type="checkbox"> ingredient 1</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 2</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 3</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 4</li>
                            <li class="instructions">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
                       </ul>
                </div>
            </div>

        <div class="recipePicContainer">
            <div class="checkBoxes">
              <ul class="recipe" id="recipe03">
                <li>Dessert</li>
               </ul>
                       <ul class="recipes">
                           <li class="ingredient"><input type="checkbox"> ingredient 1</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 2</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 3</li>
                           <li class="ingredient"><input type="checkbox"> ingredient 4</li>
                            <li class="instructions">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li>
                       </ul>
                </div>
            </div>

</div>


问:
How to change the Jupyter start-up folder
I tried following the instructions given on the Jupyter Notebook documentation.

Unfortunately, I haven't been able to figure it out. Where exactly is this "start in" field?

I've a windows 7 (64 bit) system, with Anaconda3 installed (not in C drive). I want to change Jupyter start folder location.

答:
agree to most answers except that in jupyter_notebook_config.py, you have to put

```<code>#c.NotebookApp.notebook_dir='c:\\test\\your_root'
</code>```

double \\ is the key answer

Body:
agree to most answers except that in jupyter_notebook_config.py, you have to put

#c.NotebookApp.notebook_dir='c:\\test\\your_root'

double \\ is the key answer


问:
How to enable atom-racer documentation in popup list?
The popup list works, but doesn't display the documentation of the selected item.

In package settings the "Show Documentation" and "Include Signature in Documentation" options are enabled.

How to make it look like this?

I'm using:

autocomplete-racer 0.1.3

Racer 2.0.6

Atom 1.13.1

Rust 1.16.0

Gentoo x86_64

答:
If you still haven't figured this out, simply try disabling or uninstalling the racer package.

The autocomplete-racer package implements its own autocomplete provider which includes the documentation you're after. Based on what you're reporting, the racer package is probably taking precedence and as such you'd be limited to its autocomplete provider. Use one or the other, not both.


问:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: ; <an identifier>
I am executing an update query

```<code>begin

 update active_cus
 set Global_indicator = 'Y' where cust_id = '3311' ;

end;
</code>```

I get the sql error

PLS-00103: Encountered the symbol "end-of-file" when expecting one of
  the following:

;   The symbol
  ";" was substituted for "end-of-file" to continue.

答:
Does it work without the BEGIN ... END; ?

If your script is longer than the sample you posted, another END; may be missing.

Title: PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: ; <an identifier> <a double-quoted delimited-identifier>

Body:
I am executing an update query

begin

 update active_cus
 set Global_indicator = 'Y' where cust_id = '3311' ;

end;

I get the sql error

PLS-00103: Encountered the symbol "end-of-file" when expecting one of
  the following:

;   The symbol
  ";" was substituted for "end-of-file" to continue.


问:
spring-cloud-stream retry policy per exception
In the documentation of the spring-cloud-stream project the only retry mechanism that I have saw was a single backoff policy.

The behavior that I would like to achieve is three different retry policies in case that an exception is thrown while consuming a message:

Unrecoverable exception - this kind of messages wouldn't be tried to be processed again.

Recoverable exception - this kind of messages would be retried number of times before being discarded.

Transient exception - this kind of messages would be retried forever.

Is there a way to define a different retry policy for each kind of exception?
I know that in spring-kafka there was an ability to provide a RetryTemplate and achieve the above-mentioned behavior.

I thought that maybe with the DLQ mechanism there would be a way to achieve this behavior.

Edit: I am using Kafka as the messaging middleware.

答:
It is not currently possible to configure the retry to that extent; there is an open new feature request.

However, you can always implement your own logic within your listener, using a RetryTemplate and disable the binder's retries.

If you are using the Rabbit binder, you could use the DLQ and republishToDlq=true and the DLQ messages will contain exception headers. You can then have another app consume those messages and take appropriate action based on the exception type.


答:
1) zoo  Probably the easiest is to convert it to "zoo" class and from that to "ts" class.  "yearmon" class is a class provided in the zoo package for representing monthly data and closely corresponds to frequency 12 data in ts.  The result is a "ts" class series having the same length as the number of rows in df.

```<code>library(zoo)
as.ts(read.zoo(df, FUN = as.yearmon))

##        Jan   Feb   Mar   Apr   May   Jun   Jul   Aug   Sep   Oct   Nov   Dec
## 2015  6434  5595  3101  3475  6519  7251  4200  3622  4782  6503  9460 15623
## 2016 18393 14410 11210 10582 14316 11876 13676 12466 17326 15845 15569 24933
## 2017 35050 26008 25767 17858 21089 13570
</code>```

Depending on what you want to do you may prefer to just leave it as a "zoo" class time series in which case omit the as.ts .

1a) An alternative way to use zoo would be:

```<code>ts(df$inflow, start = as.yearmon(df$date[1]), freq = 12)
</code>```

2) base  This is longer but does not use any packages:

```<code>mo <- as.numeric(format(df$date[1], "%m"))
yr <- as.numeric(format(df$date[1], "%Y"))
ts(df$inflow, start = c(yr, mo), freq = 12)
</code>```

If it were known that the series always starts in January then we could omit the definition of mo and write:

```<code>ts(df$inflow, start = yr, freq = 12)
</code>```

Note: The input df from the question is:

```<code>df <-
structure(list(date = structure(c(16436, 16467, 16495, 16526,
16556, 16587, 16617, 16648, 16679, 16709, 16740, 16770, 16801,
16832, 16861, 16892, 16922, 16953, 16983, 17014, 17045, 17075,
17106, 17136, 17167, 17198, 17226, 17257, 17287, 17318), class = "Date"),
inflow = c(6434L, 5595L, 3101L, 3475L, 6519L, 7251L, 4200L,
3622L, 4782L, 6503L, 9460L, 15623L, 18393L, 14410L, 11210L,
10582L, 14316L, 11876L, 13676L, 12466L, 17326L, 15845L, 15569L,
24933L, 35050L, 26008L, 25767L, 17858L, 21089L, 13570L)), row.names =
c(NA, 30L), class = "data.frame", .Names = c("date", "inflow"))
</code>```

Title: convert data frame to time series in R

Body:
I have monthly data fro last two and half year. I want to convert my data frame to time series. So that I should have

Start :: 2015-01-01

End :: 2017-06-01

Frequency : 1

I have tried

ts (df [, -1], start = df [1, 1], end = df [29, 1])

But I get this really wired output from this.

    Time Series:
    Start = 16436
    End = 17287
   Frequency = 1

            date inflow
   1  2015-01-01   6434

   2  2015-02-01   5595

   3  2015-03-01   3101

   4  2015-04-01   3475

   5  2015-05-01   6519

   6  2015-06-01   7251

   7  2015-07-01   4200

   8  2015-08-01   3622

   9  2015-09-01   4782

   10 2015-10-01   6503

   11 2015-11-01   9460

   12 2015-12-01  15623

   13 2016-01-01  18393

   14 2016-02-01  14410

   15 2016-03-01  11210

   16 2016-04-01  10582

   17 2016-05-01  14316

   18 2016-06-01  11876

   19 2016-07-01  13676

   20 2016-08-01  12466

   21 2016-09-01  17326

   22 2016-10-01  15845

   23 2016-11-01  15569

   24 2016-12-01  24933

   25 2017-01-01  35050

   26 2017-02-01  26008

   27 2017-03-01  25767

   28 2017-04-01  17858

   29 2017-05-01  21089

dput(df)
structure(list(date = structure(c(16436, 16467, 16495, 16526,
16556, 16587, 16617, 16648, 16679, 16709, 16740, 16770, 16801,
16832, 16861, 16892, 16922, 16953, 16983, 17014, 17045, 17075,
17106, 17136, 17167, 17198, 17226, 17257, 17287, 17318), class = "Date"),
    inflow = c(6434L, 5595L, 3101L, 3475L, 6519L, 7251L, 4200L,
    3622L, 4782L, 6503L, 9460L, 15623L, 18393L, 14410L, 11210L,
    10582L, 14316L, 11876L, 13676L, 12466L, 17326L, 15845L, 15569L,
    24933L, 35050L, 26008L, 25767L, 17858L, 21089L, 13570L)), row.names = c(NA,
-30L), class = "data.frame", .Names = c("date", "inflow"))

Many thanks in advance!!

Body:
1) zoo  Probably the easiest is to convert it to "zoo" class and from that to "ts" class.  "yearmon" class is a class provided in the zoo package for representing monthly data and closely corresponds to frequency 12 data in ts.  The result is a "ts" class series having the same length as the number of rows in df.

library(zoo)
as.ts(read.zoo(df, FUN = as.yearmon))

##        Jan   Feb   Mar   Apr   May   Jun   Jul   Aug   Sep   Oct   Nov   Dec
## 2015  6434  5595  3101  3475  6519  7251  4200  3622  4782  6503  9460 15623
## 2016 18393 14410 11210 10582 14316 11876 13676 12466 17326 15845 15569 24933
## 2017 35050 26008 25767 17858 21089 13570

Depending on what you want to do you may prefer to just leave it as a "zoo" class time series in which case omit the as.ts .

1a) An alternative way to use zoo would be:

ts(df$inflow, start = as.yearmon(df$date[1]), freq = 12)

2) base  This is longer but does not use any packages:

mo <- as.numeric(format(df$date[1], "%m"))
yr <- as.numeric(format(df$date[1], "%Y"))
ts(df$inflow, start = c(yr, mo), freq = 12)

If it were known that the series always starts in January then we could omit the definition of mo and write:

ts(df$inflow, start = yr, freq = 12)

Note: The input df from the question is:

df <-
structure(list(date = structure(c(16436, 16467, 16495, 16526,
16556, 16587, 16617, 16648, 16679, 16709, 16740, 16770, 16801,
16832, 16861, 16892, 16922, 16953, 16983, 17014, 17045, 17075,
17106, 17136, 17167, 17198, 17226, 17257, 17287, 17318), class = "Date"),
inflow = c(6434L, 5595L, 3101L, 3475L, 6519L, 7251L, 4200L,
3622L, 4782L, 6503L, 9460L, 15623L, 18393L, 14410L, 11210L,
10582L, 14316L, 11876L, 13676L, 12466L, 17326L, 15845L, 15569L,
24933L, 35050L, 26008L, 25767L, 17858L, 21089L, 13570L)), row.names =
c(NA, 30L), class = "data.frame", .Names = c("date", "inflow"))


问:
current time tooltip when i hover on a slider html5 video
Hello friends i was working on making a html5 video player and i got stuck with the problem. I want that whenever we hover on the seekbar a small box should appear and display the time at the point on the seekbar. Any suggestions will be appreciated.</p>

答:
Update Guys:

At last i have got a way to make the current Time tooltip in a more responsive way than ever here is a simple Example:

var video = $('video')[0];
var timeDrag = false;
  $('.seek-con').on('mousedown', function(e) {
    timeDrag = true;
  updatebar(e.pageX);
 });
 $(document).on('mouseup', function(e) {
  if(timeDrag) {
   timeDrag = false;
   updatebar(e.pageX);
  }
 });
 $(document).on('mousemove', function(e) {
  if(timeDrag) {
   updatebar(e.pageX);
  }
 });
 var updatebar = function(x) {
  var progress = $('.seek-con');

  //calculate drag position
  //and update video currenttime
  //as well as progress bar
  var maxduration = video.duration;
  var position = x - progress.offset().left;
  var percentage = 100 * position / progress.width();
  if(percentage > 100) {
   percentage = 100;
  }
  if(percentage < 0) {
   percentage = 0;
  }
  $('.seek-inner').css('width',percentage+'%');
  video.currentTime = maxduration * percentage / 100;
 };
  $('.seek-con').mousemove(function(e){
       var progress = $('.seek-con');
  //calculate drag position
  //and update video currenttime
  //as well as progress bar
  var maxduration = video.duration;
  var position = e.pageX - progress.offset().left;
  var percentage = 100 * position / progress.width();
  if(percentage > 100) {
   percentage = 100;
  }
  if(percentage < 0) {
   percentage = 0;
  }
    var x = percentage / 100 * video.duration;
   $('.tooltip-con')[0].innerHTML = timeFormat(x);
   var offestY = progress.offset().top;
    var y = e.clientX - 33;
    $('.tooltip-con')[0].style.top = progress[0].offsetTop-62 + "px";
$('.tooltip-con').css('margin-left',y+'px');
  });
  $('.seek-con').hover(function(){
    $('.tooltip-con').fadeIn();
  },function(){
    $('.tooltip-con').fadeOut();
  });
var timeFormat = function(seconds){
  var m = Math.floor(seconds/60)<10 ? "0"+Math.floor(seconds/60) : Math.floor(seconds/60);
  var s = Math.floor(seconds-(m*60))<10 ? "0"+Math.floor(seconds-(m*60)) : Math.floor(seconds-(m*60));
  return m+":"+s;
 };
   $('video').on('timeupdate',function(){
       var width = 100 / video.duration * video.currentTime;
        $('.seek-inner').css('width',width+'%');
   });
 ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.seek-con{
    height:10px;
    width:100%;
    background-color:#222;
}
.seek-inner{
    height:100%;
    width:50%;
    background-color:cyan;
}
.tooltip-con{
   background-color:#555;
   padding:10px;
   width:40px;
   color:white;
}</code>```

<video src="https://givemesomething.000webhostapp.com/video.mp4" height="100%" width="100%" controls></video>

00:00

```

Body:
Update Guys:

At last i have got a way to make the current Time tooltip in a more responsive way than ever here is a simple Example:

var video = $('video')[0];
var timeDrag = false;
  $('.seek-con').on('mousedown', function(e) {
    timeDrag = true;
  updatebar(e.pageX);
 });
 $(document).on('mouseup', function(e) {
  if(timeDrag) {
   timeDrag = false;
   updatebar(e.pageX);
  }
 });
 $(document).on('mousemove', function(e) {
  if(timeDrag) {
   updatebar(e.pageX);
  }
 });
 var updatebar = function(x) {
  var progress = $('.seek-con');

  //calculate drag position
  //and update video currenttime
  //as well as progress bar
  var maxduration = video.duration;
  var position = x - progress.offset().left;
  var percentage = 100 * position / progress.width();
  if(percentage > 100) {
   percentage = 100;
  }
  if(percentage < 0) {
   percentage = 0;
  }
  $('.seek-inner').css('width',percentage+'%');
  video.currentTime = maxduration * percentage / 100;
 };
  $('.seek-con').mousemove(function(e){
       var progress = $('.seek-con');
  //calculate drag position
  //and update video currenttime
  //as well as progress bar
  var maxduration = video.duration;
  var position = e.pageX - progress.offset().left;
  var percentage = 100 * position / progress.width();
  if(percentage > 100) {
   percentage = 100;
  }
  if(percentage < 0) {
   percentage = 0;
  }
    var x = percentage / 100 * video.duration;
   $('.tooltip-con')[0].innerHTML = timeFormat(x);
   var offestY = progress.offset().top;
    var y = e.clientX - 33;
    $('.tooltip-con')[0].style.top = progress[0].offsetTop-62 + "px";
$('.tooltip-con').css('margin-left',y+'px');
  });
  $('.seek-con').hover(function(){
    $('.tooltip-con').fadeIn();
  },function(){
    $('.tooltip-con').fadeOut();
  });
var timeFormat = function(seconds){
  var m = Math.floor(seconds/60)<10 ? "0"+Math.floor(seconds/60) : Math.floor(seconds/60);
  var s = Math.floor(seconds-(m*60))<10 ? "0"+Math.floor(seconds-(m*60)) : Math.floor(seconds-(m*60));
  return m+":"+s;
 };
   $('video').on('timeupdate',function(){
       var width = 100 / video.duration * video.currentTime;
        $('.seek-inner').css('width',width+'%');
   });

.seek-con{
    height:10px;
    width:100%;
    background-color:#222;
}
.seek-inner{
    height:100%;
    width:50%;
    background-color:cyan;
}
.tooltip-con{
   background-color:#555;
   padding:10px;
   width:40px;
   color:white;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video src="https://givemesomething.000webhostapp.com/video.mp4" height="100%" width="100%" controls></video>
<!--- The Seek bar --->
<div class="tooltip-con">00:00</div>
<div class="seek-con">
   <div class="seek-inner"></div>
</div>


问:
Vuejs: How to properly pass props to component data
i'm playing with Vue 2.0, but there is something unclear..
how can i pass the props to the internal data of a component?
Looking at the documentation it seems that i have done right.

HTML

```<code><lista-servizi :servizi="modello"></lista-servizi>
</code>```

the "modello" is a data already defined.

THE VUE COMPONENT

```<code>Vue.component('lista-servizi', {
 template:
 '<span class="blu">{{listaServizi.lineaGialla.descrizione}}</span>',
    props: ['servizi'],
    data: function(){
    return{
       listaServizi : this.servizi
    }
</code>```

basically i try to give to data listaServizi the same value as props servizi,
but in the console i have the following message:

```<code>[Vue warn]: Error in render function: "TypeError: Cannot read property 'descrizione' of undefined"

found in

---> <ListaServizi>
       <Root>
</code>```

答:
Most likely you have a problem with modello.
By defining the modello, your code works fine. Below is an example based on your code that works:

```<code><div id="app-1">
<lista-servizi :servizi="modello"></lista-servizi>
</div>

Vue.component('lista-servizi', {
  template: '<span class="blu">{{listaServizi.lineaGialla.descrizione}}</span>',
  props: ['servizi'],
  data: function(){
    return{
     listaServizi : this.servizi
    }
  }
})

var app1 = new Vue({
 el: '#app-1',
 data: {
 modello: {
  lineaGialla : {
    descrizione : " This is a description"
    }
  }
}
})
</code>```

Here is a link to a working bin
https://jsbin.com/qoloqoz/1/edit?html,js,output

Body:
i'm playing with Vue 2.0, but there is something unclear..
how can i pass the props to the internal data of a component?
Looking at the documentation it seems that i have done right.

HTML

<lista-servizi :servizi="modello"></lista-servizi>

the "modello" is a data already defined.

THE VUE COMPONENT

Vue.component('lista-servizi', {
 template:
 '{{listaServizi.lineaGialla.descrizione}}',
    props: ['servizi'],
    data: function(){
    return{
       listaServizi : this.servizi
    }

basically i try to give to data listaServizi the same value as props servizi,
but in the console i have the following message:

[Vue warn]: Error in render function: "TypeError: Cannot read property 'descrizione' of undefined"

found in

---> <ListaServizi>
       <Root>

Body:
Most likely you have a problem with modello.
By defining the modello, your code works fine. Below is an example based on your code that works:

<div id="app-1">
<lista-servizi :servizi="modello"></lista-servizi>
</div>

Vue.component('lista-servizi', {
  template: '<span class="blu">{{listaServizi.lineaGialla.descrizione}}</span>',
  props: ['servizi'],
  data: function(){
    return{
     listaServizi : this.servizi
    }
  }
})

var app1 = new Vue({
 el: '#app-1',
 data: {
 modello: {
  lineaGialla : {
    descrizione : " This is a description"
    }
  }
}
})

Here is a link to a working bin
https://jsbin.com/qoloqoz/1/edit?html,js,output


问:
how to replace a character INSIDE the text content of many files automatically?
I have a folder /myfolder containing many latex tables.

I need to replace a character in each of them, namely replacing any minus sign -, by an en dash –.

Just to be sure: we are replacing hypens INSIDE all of the tex file in that folder. I dont care about the tex file names.

Doing that manually would be a nightmare (too many files, too many minuses). Is there a way to loop over the files automatically and do the replacement? A solution in Python/R would be great.

Thanks!

答:
Try with sed

```<code>find /home/milenko/pr -type f -exec \
sed -i 's/-/–/g' {} +
</code>```

from command line(if you are using Linux)

More about  type

The find utility -exec clause is using {} to represent the matched files.

Body:
Try with sed

find /home/milenko/pr -type f -exec \
sed -i 's/-/–/g' {} +

from command line(if you are using Linux)

More about  type

The find utility -exec clause is using {} to represent the matched files.


答:
sed -i -e 's/-/–/g' /myfolder/* should work.

The expression does a search globally and replaces all - inside the files the shell expands from /myfolder/* with –. Sed does the change in-place, that is, overwriting the original file (you need to explicitly specify a backup-file on MacOS, I can't remember the parameter though).

Absolutely no care is taken about wether or not the - is a verbatim hyphen or part of the latex syntax. Be aware of that.

Title: how to replace a character INSIDE the text content of many files automatically?

Body:
I have a folder /myfolder containing many latex tables.

I need to replace a character in each of them, namely replacing any minus sign -, by an en dash –.

Just to be sure: we are replacing hypens INSIDE all of the tex file in that folder. I dont care about the tex file names.

Doing that manually would be a nightmare (too many files, too many minuses). Is there a way to loop over the files automatically and do the replacement? A solution in Python/R would be great.

Thanks!


问:
Mysql subselect extremely slow (doesn't seem to be using indexes)
This query doesn't complete in a reasonable amount of time:

```<code>mysql> select * from prices where symbol='GOOG' and date in
(select max(date) from prices where symbol='GOOG' and yearweek(date) > 201001
 group by yearweek(date));
</code>```

'prices' is keyed off id, and has a secondary unique index of (symbol, date):

```<code>mysql> show index from prices;
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| Table  | Non_unique | Key_name        | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| prices |          0 | PRIMARY         |            1 | id          | A         |      468915 |     NULL | NULL   |      | BTREE      |         |
| prices |          0 | SECONDARY_INDEX |            1 | date        | A         |       10905 |     NULL | NULL   | YES  | BTREE      |         |
| prices |          0 | SECONDARY_INDEX |            2 | symbol      | A          |      468915 |     NULL | NULL   | YES  | BTREE      |         |
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
3 rows in set (0.00 sec)
</code>```

From looking at the EXPLAIN output, it seems as though MySql is not using the index on (date, symbol).  Does the combination of WHERE symbol='GOOG' and date IN (...)) require a full table scan and not use the secondary unique index?

```<code>mysql> EXPLAIN select * from prices where symbol='GOOG' and date in (select max(date) from prices where symbol='GOOG' and yearweek(date) > 201001 group by yearweek(date));
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
| id | select_type        | table  | type  | possible_keys | key             | key_len | ref  | rows   | Extra                                                     |
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
|  1 | PRIMARY            | prices | ALL   | NULL          | NULL            | NULL    | NULL | 468915 | Using where                                               |
|  2 | DEPENDENT SUBQUERY | prices | index | NULL          | SECONDARY_INDEX | 17      | NULL | 468915 | Using where; Using index; Using temporary; Using filesort |
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
2 rows in set (0.00 sec)
</code>```

答:
Can you not just do this?</p>

```<code>  SELECT *
    FROM prices
   WHERE symbol = 'GOOG'
     AND date >  '2010-12-18 23:59:59'
ORDER BY date DESC
GROUP BY yearweek(date)
   LIMIT 1
</code>```

Body:
This query doesn't complete in a reasonable amount of time:

mysql> select * from prices where symbol='GOOG' and date in
(select max(date) from prices where symbol='GOOG' and yearweek(date) > 201001
 group by yearweek(date));

'prices' is keyed off id, and has a secondary unique index of (symbol, date):

mysql> show index from prices;
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| Table  | Non_unique | Key_name        | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| prices |          0 | PRIMARY         |            1 | id          | A         |      468915 |     NULL | NULL   |      | BTREE      |         |
| prices |          0 | SECONDARY_INDEX |            1 | date        | A         |       10905 |     NULL | NULL   | YES  | BTREE      |         |
| prices |          0 | SECONDARY_INDEX |            2 | symbol      | A          |      468915 |     NULL | NULL   | YES  | BTREE      |         |
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
3 rows in set (0.00 sec)

From looking at the EXPLAIN output, it seems as though MySql is not using the index on (date, symbol).  Does the combination of WHERE symbol='GOOG' and date IN (...)) require a full table scan and not use the secondary unique index?

mysql> EXPLAIN select * from prices where symbol='GOOG' and date in (select max(date) from prices where symbol='GOOG' and yearweek(date) > 201001 group by yearweek(date));
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
| id | select_type        | table  | type  | possible_keys | key             | key_len | ref  | rows   | Extra                                                     |
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
|  1 | PRIMARY            | prices | ALL   | NULL          | NULL            | NULL    | NULL | 468915 | Using where                                               |
|  2 | DEPENDENT SUBQUERY | prices | index | NULL          | SECONDARY_INDEX | 17      | NULL | 468915 | Using where; Using index; Using temporary; Using filesort |
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
2 rows in set (0.00 sec)

Body:
Can you not just do this?

  SELECT *
    FROM prices
   WHERE symbol = 'GOOG'
     AND date >  '2010-12-18 23:59:59'
ORDER BY date DESC
GROUP BY yearweek(date)
   LIMIT 1


问:
How to get value from json with random ID
I have a problem with retrieving values from JSON

I do not know how to retrieve a value [NAME] that is given after id (which is random)

```<code>    "allplayers": {
    "76561197979570214": {
        "clan": "FBÏ",
        "name": "phr",
        "observer_slot": 6,
        "team": "T",
    },
    "76561198156373160": {
        "clan": "ZOWIE",
        "name": "TOAO",
        "observer_slot": 7,
        "team": "T",
    },
    "76561198071702537": {
        "clan": "Team Biceps",
        "name": "snatchie",
        "observer_slot": 8,
        "team": "T",
    },
},
</code>```

With constant values

```<code>"map": {
    "mode": "competitive",
    "name": "de_overpass",
    "phase": "live",
    "round": 7,
    "team_ct": {
        "score": 7,
        "name": "Team Kinguin",
        "flag": "PL",
        "timeouts_remaining": 1,
        "matches_won_this_series": 0
    },
    "team_t": {
        "score": 0,
        "name": "Samsung4Gamers",
        "flag": "PL",
        "timeouts_remaining": 1,
        "matches_won_this_series": 0
    },
    "num_matches_to_win_series": 0,
    "current_spectators": 3,
    "souvenirs_last_round": 0,
    "souvenirs_total": 0
},
</code>```

Im using

```<code>data = JSON.parse(msg);
$("#ct_score").text(data.map.team_ct.score);
</code>```

Can anyone help me? Thanks!

答:
You can loop through you result object's properties and check if the current propertie is it's own, like this :

   allplayers = {
    "76561197979570214": {
        "clan": "FBÏ",
        "name": "phr",
        "observer_slot": 6,
        "team": "T",
    },
    "76561198156373160": {
        "clan": "ZOWIE",
        "name": "TOAO",
        "observer_slot": 7,
        "team": "T",
    },
    "76561198071702537": {
        "clan": "Team Biceps",
        "name": "snatchie",
        "observer_slot": 8,
        "team": "T",
    },
};

for(var key in allplayers){
    if(allplayers.hasOwnProperty(key)){
        if(allplayers[key].hasOwnProperty('name')){
          console.log(allplayers[key].name);
        }
    }
}```

Body:
I have a problem with retrieving values from JSON

I do not know how to retrieve a value [NAME] that is given after id (which is random)

    "allplayers": {
    "76561197979570214": {
        "clan": "FBÏ",
        "name": "phr",
        "observer_slot": 6,
        "team": "T",
    },
    "76561198156373160": {
        "clan": "ZOWIE",
        "name": "TOAO",
        "observer_slot": 7,
        "team": "T",
    },
    "76561198071702537": {
        "clan": "Team Biceps",
        "name": "snatchie",
        "observer_slot": 8,
        "team": "T",
    },
},

With constant values

"map": {
    "mode": "competitive",
    "name": "de_overpass",
    "phase": "live",
    "round": 7,
    "team_ct": {
        "score": 7,
        "name": "Team Kinguin",
        "flag": "PL",
        "timeouts_remaining": 1,
        "matches_won_this_series": 0
    },
    "team_t": {
        "score": 0,
        "name": "Samsung4Gamers",
        "flag": "PL",
        "timeouts_remaining": 1,
        "matches_won_this_series": 0
    },
    "num_matches_to_win_series": 0,
    "current_spectators": 3,
    "souvenirs_last_round": 0,
    "souvenirs_total": 0
},

Im using

data = JSON.parse(msg);
$("#ct_score").text(data.map.team_ct.score);

Can anyone help me? Thanks!


答:
To rename file names, use

```<code>rename 's/-/–/g' *
</code>```

it will rename all the hyphens to en dash.

To replace all contents from hyphens to en dash, use

```<code> sed -i 's/-/–/g' *tex
</code>```

Body:
To rename file names, use

rename 's/-/–/g' *

it will rename all the hyphens to en dash.

To replace all contents from hyphens to en dash, use

 sed -i 's/-/–/g' *tex


问:
Start automaticly Function JavaScript
```<code> <div  class="scroll-btn hidden-sm hidden-xs wow bounceInDown" data-wow-delay="1.4s">
     <a id="introjs" href="javascript:void(0)" onclick="introJs().start();">
         <span class="mouse">
         <span class="weel">
         <span></span>
         </span>
         </span>
     </a>
 </div>
</code>```

Can i start to onclick funtion automatic on page load or on page ready.
Not on click #introjs element.

答:
Either use JQuery's $(document).ready()

or without JQuery, something like this would work in about 98% of browsers:

```<code>document.addEventListener("DOMContentLoaded", function(event) {
  //do work
});
</code>```

There's a great answer here with a bit more detail on the subject https://stackoverflow.com/a/800010/8055700

Title: Start automaticly Function JavaScript

Body:
Either use JQuery's $(document).ready()

or without JQuery, something like this would work in about 98% of browsers:

document.addEventListener("DOMContentLoaded", function(event) {
  //do work
});

There's a great answer here with a bit more detail on the subject https://stackoverflow.com/a/800010/8055700


问:
How to probe if a file was download using Selenium/WebdriverIO
I want to know how I can verify if a file was downloaded using Selenium Webdriver after I click the download button.</p>

答:
TL;DR: Unless your web-app has some kind of visual/GUI trigger once the download finishes (some text, an image/icon-font, push-notification, etc.), then the answer is a resounding NO.

Webdriver can't go outside the scope of your browser, but your underlying framework can. Especially if you're using NodeJS. :)

Off the top of my head I can think of a few ways I've been able to do this in the past. Choose as applicable:

1. Verify if the file has been downloaded using Node's File System (aka fs)

Since you're running WebdriverIO, under a NodeJS environment, then you can make use its powerful lib tool-suite. I would use fs.exists, or fs.existsSync to verify if the file is in the expected folder.

If you want to be diligent, then also use fs.statSync in conjunction with fs.exists & poll the file until it has the expected size (e.g.: > 2560 bytes)

There are multiple examples online that can help you put together such a script. Use the fs documentation, but other resources as well. Lastly, you can add said script inside your it/describe statement (I remember your were using Mocha).

2. Use child_process's exec command to launch third-party scripts

Though this method requires more work to setup, I find it more relevant on the long run.

!!! Caution: Apart from launching the script, you need to write a script in a third-party framework.

Using an AutoIT script;

Using a Sikuli script;

Using a TestComplete (not linking it, I don't like it that much), or [insert GUI verification script here] script;

Note: All the above frameworks can generate an .exe file that you can trigger from your WebdriverIO test-cases in order to check if your file has been downloaded, or not.

Steps to take:

create one of the stand-alone scripts like mentioned above;

place the script's .exe file inside your project in a known folder;

use child_process.exec to launch the script and assert its result after it finishes its execution;

Example:

```<code>exec = require('child_process').exec;
// Make sure you also remove the .exe from scriptName
var yourScript = pathToScript + scriptName;

var child = exec(yourScript);
child.on('close', function (code, signal) {
    if (code!==0) {
        callback.fail(online.online[module][code]);
    } else {
        callback();
    }
});
</code>```

Finally: I'm sure there are other ways to do it. But, your main take-away from such a vague question should be: YES, you can verify if the file has been downloaded if you absolutely must, expecially if this test-case is CRITICAL to your regression-run.

Body:
TL;DR: Unless your web-app has some kind of visual/GUI trigger once the download finishes (some text, an image/icon-font, push-notification, etc.), then the answer is a resounding NO.

Webdriver can't go outside the scope of your browser, but your underlying framework can. Especially if you're using NodeJS. :)

Off the top of my head I can think of a few ways I've been able to do this in the past. Choose as applicable:

1. Verify if the file has been downloaded using Node's File System (aka fs)

Since you're running WebdriverIO, under a NodeJS environment, then you can make use its powerful lib tool-suite. I would use fs.exists, or fs.existsSync to verify if the file is in the expected folder.

If you want to be diligent, then also use fs.statSync in conjunction with fs.exists & poll the file until it has the expected size (e.g.: > 2560 bytes)

There are multiple examples online that can help you put together such a script. Use the fs documentation, but other resources as well. Lastly, you can add said script inside your it/describe statement (I remember your were using Mocha).

2. Use child_process's exec command to launch third-party scripts

Though this method requires more work to setup, I find it more relevant on the long run.

!!! Caution: Apart from launching the script, you need to write a script in a third-party framework.

Using an AutoIT script;

Using a Sikuli script;

Using a TestComplete (not linking it, I don't like it that much), or [insert GUI verification script here] script;

Note: All the above frameworks can generate an .exe file that you can trigger from your WebdriverIO test-cases in order to check if your file has been downloaded, or not.

Steps to take:

create one of the stand-alone scripts like mentioned above;

place the script's .exe file inside your project in a known folder;

use child_process.exec to launch the script and assert its result after it finishes its execution;

Example:

exec = require('child_process').exec;
// Make sure you also remove the .exe from scriptName
var yourScript = pathToScript + scriptName;

var child = exec(yourScript);
child.on('close', function (code, signal) {
    if (code!==0) {
        callback.fail(online.online[module][code]);
    } else {
        callback();
    }
});

Finally: I'm sure there are other ways to do it. But, your main take-away from such a vague question should be: YES, you can verify if the file has been downloaded if you absolutely must, expecially if this test-case is CRITICAL to your regression-run.


问:
How to get css pseudo-element content with python selenium
enter image description here

How could I locate the pseudo element using selenium?
My desired output is the address "http: //www.meishij.net/alldish.php?id=1799616".

答:
Why not try with BeautifulSoup:

```<code>import requests
from bs4 import BeautifulSoup
pages = requests.get('http://www.meishij.net/zuofa/qingjiaosansi.html')
soup =BeautifulSoup(pages.content, 'html.parser')
result = soup.find('a',{'title':"青椒三丝"}).get('href')
print(result)
</code>```

result will be:

```<code>http://www.meishij.net/alldish.php?id=1799616
</code>```

Body:
Why not try with BeautifulSoup:

import requests
from bs4 import BeautifulSoup
pages = requests.get('http://www.meishij.net/zuofa/qingjiaosansi.html')
soup =BeautifulSoup(pages.content, 'html.parser')
result = soup.find('a',{'title':"青椒三丝"}).get('href')
print(result)

result will be:

http://www.meishij.net/alldish.php?id=1799616


问:
Advice in caching for python
I am using Flask- Restful for a Python API, which is working well.
Now, there are few DB operations which I want to cache, how do I go about that? I have searched online and there were a couple of options like flask cache and CacheTools and I am not able to decide.

Flask cache was mainly about caching the requests rather than the data used inside, correct me if I am wrong.

Cachetools has useful methods like lru_cache etc. which could be of use to me?

PS: I am primarily a Java guy and used to use guava with spring boot in my previous services, so looking for something like that in python.

答:
Earlier, I had this problem, too.
In the end, I use Redis.

And in  werkeug, there is a cache lib, which makes Redis easy to use.

from werkzeug.contrib.cache import RedisCache

for more information, see the doc

By the way, if your app runs in single process(multithread is also OK), you can just use the codes below.

```<code>class CachedItem:
    def __init__(self, item, duration):
        self.item = item
        self.duration = duration
        self.time_stamp = time.time()

    def __repr__(self):
        return '<CachedItem {%s} expires at: %s>' % (self.item, time.time() + self.duration)

class CachedDict(dict):
    def __init__(self, *args, **kwargs):
        super(CachedDict, self).__init__(*args, **kwargs)
        self.lock = threading.Lock()

    def get_cache(self, key, default=None, duration=300):
        with self.lock:
            self._clean()
            if key in self:
                return self[key].item
            else:
                self[key] = CachedItem(default, duration)
            return self[key].item

    def set_cache(self, key, value, duration=300):
        with self.lock:
            self[key] = CachedItem(value, duration)

    def _clean(self):
        for key in list(self.keys()): # [self.keys()] error, we get dict_keys type
            if self[key].time_stamp + self[key].duration <= time.time():
                self.pop(key)
</code>```

Title: Advice in caching for python

Body:
Earlier, I had this problem, too.
In the end, I use Redis.

And in  werkeug, there is a cache lib, which makes Redis easy to use.

from werkzeug.contrib.cache import RedisCache

for more information, see the doc

By the way, if your app runs in single process(multithread is also OK), you can just use the codes below.

class CachedItem:
    def __init__(self, item, duration):
        self.item = item
        self.duration = duration
        self.time_stamp = time.time()

    def __repr__(self):
        return '<CachedItem {%s} expires at: %s>' % (self.item, time.time() + self.duration)

class CachedDict(dict):
    def __init__(self, *args, **kwargs):
        super(CachedDict, self).__init__(*args, **kwargs)
        self.lock = threading.Lock()

    def get_cache(self, key, default=None, duration=300):
        with self.lock:
            self._clean()
            if key in self:
                return self[key].item
            else:
                self[key] = CachedItem(default, duration)
            return self[key].item

    def set_cache(self, key, value, duration=300):
        with self.lock:
            self[key] = CachedItem(value, duration)

    def _clean(self):
        for key in list(self.keys()): # [self.keys()] error, we get dict_keys type
            if self[key].time_stamp + self[key].duration <= time.time():
                self.pop(key)


问:
How to create features_train for Sklearn from two types of data
I have a list of colors:

```<code>initialData = [u'black' u'black' u'white' u'powderblue'
 u'whitesmoke' u'black' u'cornflowerblue' u'powderblue' u'powderblue'
 u'goldenrod']
</code>```

Each color represents a user that chose this color. And I have the labels for each color that means a gender:

```<code>labels_train = [0 0 0 0 0 1 1 1 1 1]
</code>```

0 means that a color is chosen by female, 1 means male. And I need to predict a gender using this knowledge and I did it like this:

```<code>from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(initialData)
features_train = le.transform(initialData)
features_train = features_train.reshape(-1, 1)

from sklearn.naive_bayes import GaussianNB
clf = GaussianNB()
clf.fit(features_train, labels_train)
</code>```

But now I want to add more data to my initialData. What if I should predict a gender not only using color, but using bio as well? How should I change/normalize my features_train for this case? For example, if I have an another one list like this:

```<code>initialData2 = [u'Hello, my name is Bob and I love to cook' u'happy mother' ...]
</code>```

And also labels for each element:

```<code>labels_train2 = [1 0]
</code>```

UPD

Example of my data. It is a CSV and I use columns link_color and description:

```<code>_unit_id,_golden,_unit_state,_trusted_judgments,_last_judgment_at,gender,gender:confidence,profile_yn,profile_yn:confidence,created,description,fav_number,gender_gold,link_color,name,profile_yn_gold,profileimage,retweet_count,sidebar_color,text,tweet_coord,tweet_count,tweet_created,tweet_id,tweet_location,user_timezone
815719226,FALSE,finalized,3,10/26/15 23:24,male,1,yes,1,12/5/13 1:48,i sing my own rhythm.,0,,08C2C2,sheezy0,,pbs.twimg.com/profile_images/414342229096808449/fYvzqXN7_normal.png,0,FFFFFF,Robbie E Responds To Critics After Win Against Eddie Edwards In The #WorldTitleSeries t.co/NSybBmVjKZ,,110964,10/26/15 12:40,6.5873E+17,main; @Kan1shk3,Chennai
815719227,FALSE,finalized,3,10/26/15 23:30,male,1,yes,1,10/1/12 13:51,I'm the author of novels filled with family drama and romance.,68,,0084B4,DavdBurnett,,pbs.twimg.com/profile_images/539604221532700673/WW16tBbU_normal.jpeg,0,C0DEED,���It felt like they were my friends and I was living the story with them�۝ t.co/arngE0YHNO #retired #IAN1 t.co/CIzCANPQFz,,7471,10/26/15 12:40,6.5873E+17,,Eastern Time (US & Canada)
815719228,FALSE,finalized,3,10/26/15 23:33,male,0.6625,yes,1,11/28/14 11:30,louis whining and squealing and all,7696,,ABB8C2,lwtprettylaugh,,pbs.twimg.com/profile_images/657330418249658368/SBLCXdF7_normal.png,1,C0DEED,i absolutely adore when louis starts the songs it hits me hard but it feels good,,5617,10/26/15 12:40,6.5873E+17,clcncl,Belgrade
815719229,FALSE,finalized,3,10/26/15 23:10,male,1,yes,1,6/11/09 22:39,"Mobile guy.  49ers, Shazam, Google, Kleiner Perkins, Yahoo!, Sprint PCS, AirTouch, Air Force.  Stanford GSB, UVa.  Dad, Husband, Brother.  Golfer.",202,,0084B4,douggarland,,pbs.twimg.com/profile_images/259703936/IMG_8444_normal.JPG,0,C0DEED,Hi @JordanSpieth - Looking at the url - do you use @IFTTT?!  Don't typically see an advanced user on the @PGATOUR! t.co/H68ou5PE9L,,1693,10/26/15 12:40,6.5873E+17,"Palo Alto, CA",Pacific Time (US & Canada)
815719230,FALSE,finalized,3,10/27/15 1:15,female,1,yes,1,4/16/14 13:23,Ricky Wilson The Best FRONTMAN/Kaiser Chiefs The Best BAND Xxxx Thank you Kaiser Chiefs for an incredible year of gigs and memories to cherish always :) Xxxxxxx,37318,,3B94D9,WilfordGemma,,pbs.twimg.com/profile_images/564094871032446976/AOfpk-mr_normal.jpeg,0,0,Watching Neighbours on Sky+ catching up with the Neighbs!! Xxx _���_���_���_���_ُ�_�ԍ_ُ� Xxx,,31462,10/26/15 12:40,6.5873E+17,,
</code>```

答:
I'm unable to comment due to low reputation. I want to understand how your dataset is structured a little more in details. Let me try to put it in a table format. Does your table containing the data look something like this maybe?</p>

```<code>labels_train   color             bio

    0         'black'            something
    0         'black'            something
    0         'black'            something
    0         'black'            something
    0         'whitesmoke'       something
    1         'black'            something
    1         'cornflowerblue'   something
    1         'powderblue'       something
    1         'powderblue'       something
    1         'powderblue'       something
    1             -             'Hello, my name is Bob and I love to..
    0             -             'happy mother'
</code>```

Body:
I have a list of colors:

initialData = [u'black' u'black' u'white' u'powderblue'
 u'whitesmoke' u'black' u'cornflowerblue' u'powderblue' u'powderblue'
 u'goldenrod']

Each color represents a user that chose this color. And I have the labels for each color that means a gender:

labels_train = [0 0 0 0 0 1 1 1 1 1]

0 means that a color is chosen by female, 1 means male. And I need to predict a gender using this knowledge and I did it like this:

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(initialData)
features_train = le.transform(initialData)
features_train = features_train.reshape(-1, 1)

from sklearn.naive_bayes import GaussianNB
clf = GaussianNB()
clf.fit(features_train, labels_train)

But now I want to add more data to my initialData. What if I should predict a gender not only using color, but using bio as well? How should I change/normalize my features_train for this case? For example, if I have an another one list like this:

initialData2 = [u'Hello, my name is Bob and I love to cook' u'happy mother' ...]

And also labels for each element:

labels_train2 = [1 0]

UPD

Example of my data. It is a CSV and I use columns link_color and description:

_unit_id,_golden,_unit_state,_trusted_judgments,_last_judgment_at,gender,gender:confidence,profile_yn,profile_yn:confidence,created,description,fav_number,gender_gold,link_color,name,profile_yn_gold,profileimage,retweet_count,sidebar_color,text,tweet_coord,tweet_count,tweet_created,tweet_id,tweet_location,user_timezone
815719226,FALSE,finalized,3,10/26/15 23:24,male,1,yes,1,12/5/13 1:48,i sing my own rhythm.,0,,08C2C2,sheezy0,,pbs.twimg.com/profile_images/414342229096808449/fYvzqXN7_normal.png,0,FFFFFF,Robbie E Responds To Critics After Win Against Eddie Edwards In The #WorldTitleSeries t.co/NSybBmVjKZ,,110964,10/26/15 12:40,6.5873E+17,main; @Kan1shk3,Chennai
815719227,FALSE,finalized,3,10/26/15 23:30,male,1,yes,1,10/1/12 13:51,I'm the author of novels filled with family drama and romance.,68,,0084B4,DavdBurnett,,pbs.twimg.com/profile_images/539604221532700673/WW16tBbU_normal.jpeg,0,C0DEED,���It felt like they were my friends and I was living the story with them�۝ t.co/arngE0YHNO #retired #IAN1 t.co/CIzCANPQFz,,7471,10/26/15 12:40,6.5873E+17,,Eastern Time (US & Canada)
815719228,FALSE,finalized,3,10/26/15 23:33,male,0.6625,yes,1,11/28/14 11:30,louis whining and squealing and all,7696,,ABB8C2,lwtprettylaugh,,pbs.twimg.com/profile_images/657330418249658368/SBLCXdF7_normal.png,1,C0DEED,i absolutely adore when louis starts the songs it hits me hard but it feels good,,5617,10/26/15 12:40,6.5873E+17,clcncl,Belgrade
815719229,FALSE,finalized,3,10/26/15 23:10,male,1,yes,1,6/11/09 22:39,"Mobile guy.  49ers, Shazam, Google, Kleiner Perkins, Yahoo!, Sprint PCS, AirTouch, Air Force.  Stanford GSB, UVa.  Dad, Husband, Brother.  Golfer.",202,,0084B4,douggarland,,pbs.twimg.com/profile_images/259703936/IMG_8444_normal.JPG,0,C0DEED,Hi @JordanSpieth - Looking at the url - do you use @IFTTT?!  Don't typically see an advanced user on the @PGATOUR! t.co/H68ou5PE9L,,1693,10/26/15 12:40,6.5873E+17,"Palo Alto, CA",Pacific Time (US & Canada)
815719230,FALSE,finalized,3,10/27/15 1:15,female,1,yes,1,4/16/14 13:23,Ricky Wilson The Best FRONTMAN/Kaiser Chiefs The Best BAND Xxxx Thank you Kaiser Chiefs for an incredible year of gigs and memories to cherish always :) Xxxxxxx,37318,,3B94D9,WilfordGemma,,pbs.twimg.com/profile_images/564094871032446976/AOfpk-mr_normal.jpeg,0,0,Watching Neighbours on Sky+ catching up with the Neighbs!! Xxx _���_���_���_���_ُ�_�ԍ_ُ� Xxx,,31462,10/26/15 12:40,6.5873E+17,,

Body:
I'm unable to comment due to low reputation. I want to understand how your dataset is structured a little more in details. Let me try to put it in a table format. Does your table containing the data look something like this maybe?

labels_train   color             bio

    0         'black'            something
    0         'black'            something
    0         'black'            something
    0         'black'            something
    0         'whitesmoke'       something
    1         'black'            something
    1         'cornflowerblue'   something
    1         'powderblue'       something
    1         'powderblue'       something
    1         'powderblue'       something
    1             -             'Hello, my name is Bob and I love to..
    0             -             'happy mother'


问:
Best way to mapping dto/domain for transport between microservices
I have DTO and DOMAIN models:

```<code>@Data
public class CarDomain {
    private String name;
    private int year;
    private String color;
}
</code>```

and

```<code>@Data
public class CarDto {
    private String name;
    private int year;
    private String color;
}
</code>```

I have 3 microservices(MS) communicate with each other through RabbitMq.
And I have models module with all DTO classes. Each MS include models module
in maven.

1 MS send carDto 2 MS recive CarDto and convert to Domain. For this I can use Several variants:

use library for example mapstruct:

```<code>@Mapper
public interface CarMapper {
    CarMapper INSTANCE = Mappers.getMapper(CarMapper.class );
    CarDto carToCarDto(CarDomain car);
}
</code>```

and use:

```<code>CarDto carDto = CarMapper.INSTANCE.carToCarDto(carDomain);
</code>```

Create manual mapper:

```<code>class CarMapper {
        public static CarDto toDto(CarDomain car) {
            CarDto carDto = new CarDto();
            carDto.setName(car.getName());
            carDto.setYear(car.getYear());
            carDto.setColor(car.getColor());
        }
    }
</code>```

Now we use 2 variant. Becouse when we build microservice and in models module some field of DTO model change we get error on compile time. For example somebody change name this dto model in models module

```<code>private String name;
</code>```

to

```<code>private String name1;
</code>```

When we build project we get error on this line:

```<code>carDto.setName(car.getName());// getName not found becose now getName1
</code>```

But this way hard. For each dto/domain models we need create mapper and write each field. In 1 variants it easier  but if dto change we get error on runtime.

Tell me the best approach how to match/mapping models dto/domain?

答:
Becouse when we build microservice and in models module some field of DTO model change we get error on compile time.

The problem you are facing is generally recognized as message versioning.

A key idea in microservices is that they can be redeployed independently of each other; you should be able to change them at any time without breaking everything else.  To achieve this, we limit the coupling between microservices to the messages that they have in common.

As a consequence of this; it follows that it is really important to get the message schemas "right".

Right in this circumstance doesn't mean that you figure out the correct messages to send the first time, but rather than you invest upfront design capital in understanding how messages change, and what message structures support those changes.

The best single reference on the topic I know of is Greg Young's book Versioning in an Event Sourced System.

Greg makes a case for using "weak schemas" to support forward and backwards compatibility; the basic ideas are

The meaning of a field never changes

The consumer must ignore and must forward fields it doesn't understand

Most (all?) fields should be optional; the consumer must be prepared for the event that some data element is missing from the message.  That might mean having an acceptable default value prepared, or alternative processing.

With the basics in mind; you can look at the details of Avro, Thrift, Protocol Buffers to get a sense for how the standardized formats tend to evolve.  Martin Kleppmann's discussion of Schema Evolution in Avro, Protocol Buffers, and Thrift might be a good intermediate step.

Message discipline is really important -- the schema is part of the API of the microservice.  Introducing a backwards incompatible change to the API introduces a lot of risk, and should not be undertaken lightly.

I have models module with all DTO classes.

That may be an error; it's hard to say.  It is certainly an error to have a common core that routinely evolves in a way that isn't backwards compatible.  That habit should change.

Body:
I have DTO and DOMAIN models:

@Data
public class CarDomain {
    private String name;
    private int year;
    private String color;
}

and

@Data
public class CarDto {
    private String name;
    private int year;
    private String color;
}

I have 3 microservices(MS) communicate with each other through RabbitMq.
And I have models module with all DTO classes. Each MS include models module
in maven.

1 MS send carDto 2 MS recive CarDto and convert to Domain. For this I can use Several variants:

use library for example mapstruct:

@Mapper
public interface CarMapper {
    CarMapper INSTANCE = Mappers.getMapper(CarMapper.class );
    CarDto carToCarDto(CarDomain car);
}

and use:

CarDto carDto = CarMapper.INSTANCE.carToCarDto(carDomain);

Create manual mapper:

class CarMapper {
        public static CarDto toDto(CarDomain car) {
            CarDto carDto = new CarDto();
            carDto.setName(car.getName());
            carDto.setYear(car.getYear());
            carDto.setColor(car.getColor());
        }
    }

Now we use 2 variant. Becouse when we build microservice and in models module some field of DTO model change we get error on compile time. For example somebody change name this dto model in models module

private String name;

to

private String name1;

When we build project we get error on this line:

carDto.setName(car.getName());// getName not found becose now getName1

But this way hard. For each dto/domain models we need create mapper and write each field. In 1 variants it easier  but if dto change we get error on runtime.

Tell me the best approach how to match/mapping models dto/domain?


问:
Docker compose for Nginx/PHP-FPM/Composer
I am trying to setup Docker for my application relying on an LEMP stack. To this end, I plan to use Docker compose in order to spawn one container for Nginx, one for PHP-FPM and one for MySQL.

This is all working well for the basic illustration use-cases found in the online tutorials, but when I try to apply it to my use-case, I struggle with a design issue.

To give a bit of context, my web application relies on Composer for PHP dependencies and Gulp+Bower for CSS/JS dependencies (and LESS compilation, assets minimization, etc.).

The problem is that I need to build the application (i.e. install all dependencies and run some gulp tasks) and provide the result of this build to both Nginx and PHP-FPM containers.

Here is what I have come to so far:

docker-compose.yml:

```<code>version: "3"

networks:
  database:
  server:

volumes:
  mysql-data:
  source:

services:
  php:
    build: .
    volumes:
      - source:/app:ro
    restart: always
    networks:
      - database
      - server
    depends_on:
      - mysql

  mysql:
    image: mysql:5.7
    volumes:
      - mysql-data:/var/lib/mysql
    restart: always
    networks:
      - database
    environment:
      MYSQL_ROOT_PASSWORD: rootpassword
      MYSQL_USER: test
      MYSQL_PASSWORD: test
      MYSQL_DATABASE: test

  nginx:
    image: nginx
    volumes:
      - source:/app:ro
    restart: always
    networks:
      - server
    depends_on:
      - php
</code>```

Dockerfile:

```<code>FROM php:7.1-fpm
WORKDIR /app

# Install dependencies
RUN curl -sL https://deb.nodesource.com/setup_8.x | bash -
RUN apt-get update && apt-get install -y \
    git \
    nodejs \
    zip
RUN curl -sL https://getcomposer.org/installer | php -- --install-dir /usr/bin --filename composer

# Get application dependencies
COPY composer.json ./
RUN composer install -o

COPY package.json gulpfile.js bower.json ./
RUN npm install
RUN npm run gulp
RUN npm run rev

# Copy application
COPY . ./
</code>```

However, as a Docker beginner, I am not sure it is right to rely on a volume for the build result of the application, or to have the build steps part of one of the containers running the application.

Thanks in advance for any help or advice!

Nicolas

答:
However, as a Docker beginner, I am not sure it is right to rely on a volume for the build result of the application, or to have the build steps part of one of the containers running the application.

Short answer: Named volumes are the correct way to handle this.

In previous versions of compose, you would use the volumes-from option to reference an existing volume in a different container. This is deprecated in v3, being replaced by named volumes which you appear to be implementing correctly. I mention volumes-from because I think it does a good job of showing the intention of volumes - to persist data between containers - where named volumes is a bit less descriptive.

Body:
I am trying to setup Docker for my application relying on an LEMP stack. To this end, I plan to use Docker compose in order to spawn one container for Nginx, one for PHP-FPM and one for MySQL.

This is all working well for the basic illustration use-cases found in the online tutorials, but when I try to apply it to my use-case, I struggle with a design issue.

To give a bit of context, my web application relies on Composer for PHP dependencies and Gulp+Bower for CSS/JS dependencies (and LESS compilation, assets minimization, etc.).

The problem is that I need to build the application (i.e. install all dependencies and run some gulp tasks) and provide the result of this build to both Nginx and PHP-FPM containers.

Here is what I have come to so far:

docker-compose.yml:

version: "3"

networks:
  database:
  server:

volumes:
  mysql-data:
  source:

services:
  php:
    build: .
    volumes:
      - source:/app:ro
    restart: always
    networks:
      - database
      - server
    depends_on:
      - mysql

  mysql:
    image: mysql:5.7
    volumes:
      - mysql-data:/var/lib/mysql
    restart: always
    networks:
      - database
    environment:
      MYSQL_ROOT_PASSWORD: rootpassword
      MYSQL_USER: test
      MYSQL_PASSWORD: test
      MYSQL_DATABASE: test

  nginx:
    image: nginx
    volumes:
      - source:/app:ro
    restart: always
    networks:
      - server
    depends_on:
      - php

Dockerfile:

FROM php:7.1-fpm
WORKDIR /app

# Install dependencies
RUN curl -sL https://deb.nodesource.com/setup_8.x | bash -
RUN apt-get update && apt-get install -y \
    git \
    nodejs \
    zip
RUN curl -sL https://getcomposer.org/installer | php -- --install-dir /usr/bin --filename composer

# Get application dependencies
COPY composer.json ./
RUN composer install -o

COPY package.json gulpfile.js bower.json ./
RUN npm install
RUN npm run gulp
RUN npm run rev

# Copy application
COPY . ./

However, as a Docker beginner, I am not sure it is right to rely on a volume for the build result of the application, or to have the build steps part of one of the containers running the application.

Thanks in advance for any help or advice!

Nicolas