问:
How to calculate form fields values to update hidden field value?
I want to know how to calculate the input values of the following fields

```<code><input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
</code>```

And update the span text and the hidden field value

```<code>TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
</code>```

Thanks in advance

答:
if you're interested in a pure javascript solution:

All inputs have an oninput event attribute that fires when the input is changed.

You can attach an event handler to the event like so:

```<code><input oninput="updateTotal" />
</code>```

where updateTotal is a function declared in your script:

```<code>function updateTotal { /* code that updates the total */ }
</code>```

OR if you select the input in your script then you can attach the event handler like this:

```<code>selectedInput.oninput = function updateTotal () {
  ...
}
</code>```

Here's my implementation that selects all the inputs with the class "auto-sum", assigns the event handler to each of them and updates the code by looping over each input's value attribute:

https://jsfiddle.net/billy_reilly/5dd24v81/2/

Body:
I want to know how to calculate the input values of the following fields

<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">

And update the span text and the hidden field value

TOTAL 0
<input id="total" type="hidden" name="total" value="">

Thanks in advance

Body:
if you're interested in a pure javascript solution:

All inputs have an oninput event attribute that fires when the input is changed.

You can attach an event handler to the event like so:

<input oninput="updateTotal" />

where updateTotal is a function declared in your script:

function updateTotal { /* code that updates the total */ }

OR if you select the input in your script then you can attach the event handler like this:

selectedInput.oninput = function updateTotal () {
  ...
}

Here's my implementation that selects all the inputs with the class "auto-sum", assigns the event handler to each of them and updates the code by looping over each input's value attribute:

https://jsfiddle.net/billy_reilly/5dd24v81/2/


来源: stackexchange

问:
A default document is not configured for the requested URL Web Api 2 / IIS express
I created a empty web api 2 project and created a default controller. When I try to go to my controller I get

```<code>HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.

Most likely causes:
A default document is not configured for the requested URL, and directory browsing is not enabled on the server.

Things you can try:
If you do not want to enable directory browsing, ensure that a default document is configured and that the file exists.
Enable directory browsing.
Go to the IIS Express install directory.
Run appcmd set config /section:system.webServer/directoryBrowse /enabled:true to enable directory browsing at the server level.
Run appcmd set config ["SITE_NAME"] /section:system.webServer/directoryBrowse /enabled:true to enable directory browsing at the site level.
Verify that the configuration/system.webServer/directoryBrowse@enabled attribute is set to true in the site or application configuration file.

Detailed Error Information:
Module     DirectoryListingModule
Notification       ExecuteRequestHandler
Handler    StaticFile
Error Code     0x00000000
Requested URL      http://localhost:49886/api/default/
Physical Path      C:\Users\Source\Repos\ospapi\OSP.Api\OSP.Api\
Logon Method       Anonymous
Logon User     Anonymous
Request Tracing Directory      C:\Users\Documents\IISExpress\TraceLogFiles\OSP.API

More Information:
This error occurs when a document is not specified in the URL, no default document is specified for the Web site or application, and directory listing is not enabled for the Web site or application. This setting may be disabled on purpose to secure the contents of the server.
View more information »
</code>```

My url: http://localhost:49886/api/default/

答: The problem is because your route is not properly set to call api. Make sure you have proper path with every method (eg. api/default/insert). Otherwise if you try to call direct controller it will show this error.</p>

ContentLicense: CC BY-SA 3.0

Body:
I created a empty web api 2 project and created a default controller. When I try to go to my controller I get

HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.

Most likely causes:
A default document is not configured for the requested URL, and directory browsing is not enabled on the server.

Things you can try:
If you do not want to enable directory browsing, ensure that a default document is configured and that the file exists.
Enable directory browsing.
Go to the IIS Express install directory.
Run appcmd set config /section:system.webServer/directoryBrowse /enabled:true to enable directory browsing at the server level.
Run appcmd set config ["SITE_NAME"] /section:system.webServer/directoryBrowse /enabled:true to enable directory browsing at the site level.
Verify that the configuration/system.webServer/directoryBrowse@enabled attribute is set to true in the site or application configuration file.

Detailed Error Information:
Module     DirectoryListingModule
Notification       ExecuteRequestHandler
Handler    StaticFile
Error Code     0x00000000
Requested URL      http://localhost:49886/api/default/
Physical Path      C:\Users\Source\Repos\ospapi\OSP.Api\OSP.Api\
Logon Method       Anonymous
Logon User     Anonymous
Request Tracing Directory      C:\Users\Documents\IISExpress\TraceLogFiles\OSP.API

More Information:
This error occurs when a document is not specified in the URL, no default document is specified for the Web site or application, and directory listing is not enabled for the Web site or application. This setting may be disabled on purpose to secure the contents of the server.
View more information »

My url: http://localhost:49886/api/default/


问:
passing Event Arguments of original handler to Routed Event in wpf
The following code shows a normal event and a routed event. Here I have used the same event name for explaining purposes but in reality I am using just the routed event.

```<code>//Normal Event
public event SelectedHandler Selected;
public delegate void SelectedHandler(Object Sender, RoutedEventArgs e);

//Routed Event
public static readonly RoutedEvent SelectedEvent =
EventManager.RegisterRoutedEvent(
"Selected", RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(MyUserControl));

//add remove handlers
public event RoutedEventHandler Selected
{
    add { AddHandler(SelectedEvent, value); }
    remove { RemoveHandler(SelectedEvent, value); }
}
</code>```

I am raising these events from a couple of event handlers as follows

```<code>private void lstvMyView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //Normal Event Raise
    if (Selected != null)
        Selected(this, e);

    //Routed Event Raise
    RoutedEventArgs args = new RoutedEventArgs(SelectedEvent);
    RaiseEvent(args);
}

private void lstvMyView_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    //Normal Event Raise
    if (Selected != null)
        Selected(this, e);

    //Routed Event Raise
    RoutedEventArgs args = new RoutedEventArgs(SelectedEvent);
    RaiseEvent(args);
}
</code>```

When I am handling the normal Event I am able to send the args of both the handlers to the event but in Routed Event the args will be a new instance. I want to pass the args of both the handlers to the Routed Event. Is it possible to achieve this? If yes then how?

答:
first of all you do not need this (and should remove it):

```<code>//Normal Event
public event SelectedHandler Selected;
public delegate void SelectedHandler(Object Sender, RoutedEventArgs e);
</code>```

i.e. you do not need to define a separate "normal" event, because you have already done it with this declaration:

```<code>public event RoutedEventHandler Selected
{
    add { AddHandler(SelectedEvent, value); }
    remove { RemoveHandler(SelectedEvent, value); }
}
</code>```

with the above code block you are "wrapping" the routed event with a "normal" (clr) one so the users of your class can use it with the "normal" syntax (i.e. instanceOfMyUserControl.Selected += ....)

second, if you want the event arguments of your routed event to be the same as the ones of the SelectionChanged event of the the ListView you are listening to, you should declare your routed event this way:

```<code>public static readonly RoutedEvent SelectedEvent =
EventManager.RegisterRoutedEvent(
"Selected", RoutingStrategy.Bubble,
typeof(SelectionChangedEventHandler),
typeof(MyUserControl));

//add remove handlers
public event SelectionChangedEventHandler Selected
{
    add { AddHandler(SelectedEvent, value); }
    remove { RemoveHandler(SelectedEvent, value); }
}
</code>```

Notice that I have substituted the RoutedEventHandler with SelectionChangedEventHandler, as it is the predefined one that can "carry" SelectionChangedEventArgs.

Now for the rising of the event.
You do not need to rise both the "normal" and the routed one (as the "normal" is a wrapper for the routed), so you should delete this:

```<code>//Normal Event Raise
if (Selected != null)
    Selected(this, e);
</code>```

and rise only the routed version, which can be done this way:

```<code>SelectionChangedEventArgs args =
    new SelectionChangedEventArgs(SelectedEvent, e.RemovedItems, e.AddedItems);

RaiseEvent(args);
</code>```

Notice that I am using the event arguments from the original event to set the AddedItems and RemovedItems of the one custom one.

Body:
The following code shows a normal event and a routed event. Here I have used the same event name for explaining purposes but in reality I am using just the routed event.

//Normal Event
public event SelectedHandler Selected;
public delegate void SelectedHandler(Object Sender, RoutedEventArgs e);

//Routed Event
public static readonly RoutedEvent SelectedEvent =
EventManager.RegisterRoutedEvent(
"Selected", RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(MyUserControl));

//add remove handlers
public event RoutedEventHandler Selected
{
    add { AddHandler(SelectedEvent, value); }
    remove { RemoveHandler(SelectedEvent, value); }
}

I am raising these events from a couple of event handlers as follows

private void lstvMyView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //Normal Event Raise
    if (Selected != null)
        Selected(this, e);

    //Routed Event Raise
    RoutedEventArgs args = new RoutedEventArgs(SelectedEvent);
    RaiseEvent(args);
}

private void lstvMyView_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    //Normal Event Raise
    if (Selected != null)
        Selected(this, e);

    //Routed Event Raise
    RoutedEventArgs args = new RoutedEventArgs(SelectedEvent);
    RaiseEvent(args);
}

When I am handling the normal Event I am able to send the args of both the handlers to the event but in Routed Event the args will be a new instance. I want to pass the args of both the handlers to the Routed Event. Is it possible to achieve this? If yes then how?

Body:
first of all you do not need this (and should remove it):

//Normal Event
public event SelectedHandler Selected;
public delegate void SelectedHandler(Object Sender, RoutedEventArgs e);

i.e. you do not need to define a separate "normal" event, because you have already done it with this declaration:

public event RoutedEventHandler Selected
{
    add { AddHandler(SelectedEvent, value); }
    remove { RemoveHandler(SelectedEvent, value); }
}

with the above code block you are "wrapping" the routed event with a "normal" (clr) one so the users of your class can use it with the "normal" syntax (i.e. instanceOfMyUserControl.Selected += ....)

second, if you want the event arguments of your routed event to be the same as the ones of the SelectionChanged event of the the ListView you are listening to, you should declare your routed event this way:

public static readonly RoutedEvent SelectedEvent =
EventManager.RegisterRoutedEvent(
"Selected", RoutingStrategy.Bubble,
typeof(SelectionChangedEventHandler),
typeof(MyUserControl));

//add remove handlers
public event SelectionChangedEventHandler Selected
{
    add { AddHandler(SelectedEvent, value); }
    remove { RemoveHandler(SelectedEvent, value); }
}

Notice that I have substituted the RoutedEventHandler with SelectionChangedEventHandler, as it is the predefined one that can "carry" SelectionChangedEventArgs.

Now for the rising of the event.
You do not need to rise both the "normal" and the routed one (as the "normal" is a wrapper for the routed), so you should delete this:

//Normal Event Raise
if (Selected != null)
    Selected(this, e);

and rise only the routed version, which can be done this way:

SelectionChangedEventArgs args =
    new SelectionChangedEventArgs(SelectedEvent, e.RemovedItems, e.AddedItems);

RaiseEvent(args);

Notice that I am using the event arguments from the original event to set the AddedItems and RemovedItems of the one custom one.

ContentLicense: CC BY-SA 2.5


问:
Make sql query simpler shorter ( Laravel )
is there any way to make these queries shorter or simpler? or maybe get the result in 1 query rather than 3.??
any advise appreciated</p>

```<code>        $room_single = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',1)
        ->where('book_room.status','=',1)
        ->count();

    $room_double = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',2)
        ->where('book_room.status','=',1)
        ->count();

    $room_triple = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',3)
        ->where('book_room.status','=',1)
        ->count();
    $total= $room_single+($room_double*2)+($room_triple*3) ;
</code>```

答:
I dont have enough contributions that is why am posting as answer.
try

```<code>GROUP BY roomtype
</code>```

Then you will not need to change your roomtype.

Body:
is there any way to make these queries shorter or simpler? or maybe get the result in 1 query rather than 3.??
any advise appreciated

        $room_single = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',1)
        ->where('book_room.status','=',1)
        ->count();

    $room_double = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',2)
        ->where('book_room.status','=',1)
        ->count();

    $room_triple = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',3)
        ->where('book_room.status','=',1)
        ->count();
    $total= $room_single+($room_double*2)+($room_triple*3) ;

Body:
I dont have enough contributions that is why am posting as answer.
try

GROUP BY roomtype

Then you will not need to change your roomtype.


问:
Testing a random number function in JavaScript with Mocha and Chai
Suppose I have a function that returns a number multiplied by two.

```<code>function double(number){
  return number * 2;
}
</code>```

To test it with Mocha and Chai is easy.

```<code>var expect = require("chai").expect;

describe("#double", function(){
  it("should double a number", function(){
    expect(double(2)).to.equal(4);
    expect(double(4.5)).to.equal(9);
    expect(double(-3)).to.equal(-6);
  });
});
</code>```

But now suppose I have a function that returns a random integer between two specified integers, call them min and max.

```<code>function randBetween(min, max){
  return Math.floor(Math.random() * (max - min + 1) + min);
}
</code>```

I won't be able to predict what the returned value will be equal to. I could write a test that makes sure the returned value is both greater than or equal to min and less than or equal to max, but that doesn't actually test whether the returned value is random. Is there a statistically valid way for me to test whether my randBetween function is working?

P.S. I know the function does not handle invalid arguments, e.g. if max is less than min. Please leave that aside for now.

答:
You can't test it with a single call; you'll need a large number of calls to prove randomness (within a reasonable definition of randomness).

In the large number of calls, you'll want to:

Make sure it doesn't return values out of range

Make sure it does provide random values within a reasonable definition of randomness (given it's a deterministic PRNG)

This question and its answers go into how to do the latter, although sadly the links in the accepted answer are mostly dead now.

The National Institute of Standards and Technology has a whole section dedicated to PRNGs, including this page describing several tests you could use to ensure the randomness of what you get back.

Of course, provided your function is implemented correctly (and it appears to be, if it's meant to return min <= value < max as is usually the case), ultimately you're testing the randomness of the underlying Math.random implementation.

Body:
Suppose I have a function that returns a number multiplied by two.

function double(number){
  return number * 2;
}

To test it with Mocha and Chai is easy.

var expect = require("chai").expect;

describe("#double", function(){
  it("should double a number", function(){
    expect(double(2)).to.equal(4);
    expect(double(4.5)).to.equal(9);
    expect(double(-3)).to.equal(-6);
  });
});

But now suppose I have a function that returns a random integer between two specified integers, call them min and max.

function randBetween(min, max){
  return Math.floor(Math.random() * (max - min + 1) + min);
}

I won't be able to predict what the returned value will be equal to. I could write a test that makes sure the returned value is both greater than or equal to min and less than or equal to max, but that doesn't actually test whether the returned value is random. Is there a statistically valid way for me to test whether my randBetween function is working?

P.S. I know the function does not handle invalid arguments, e.g. if max is less than min. Please leave that aside for now.


问:
Trying to add backslash in C# as escape for MySql insert statement
I am importing and Excel spreadsheet in order to insert into a MySql database. Here's one record in the spreadsheet:

```<code>Loc     Item                 Description
FAB12   0121G00667PDG   PNL  DUCT 27.5"
</code>```

I'm using OleDbDataReader to get a DataTable and that is working. The problem I'm having is when trying to replace the " with \" so that MySql will accept the double quote. I am trying to get C# to change 27.5" to 27.5\"

Thanks for any help you can provide.

Here's the result I'm getting now:

```<code>INSERT INTO test_table2 (Loc, Item, Description) VALUES ("FAB12
 ","0121G00667PDG","PNL  DUCT 27.5"")
</code>```

Here's the code:

```<code>           for (int i = 0; i < dtSheet.Rows.Count; i++)
        {
            DataRow dr = dtSheet.Rows[i];
            for (int j = 0; j < dtSheet.Columns.Count; j++)
            {
                DataColumn dc = dtSheet.Columns[j];
                if (dr[j].ToString().Contains("\""))
                {
                    Console.WriteLine(dr[j].ToString());
                    dr[j].ToString().Replace("\"", "\\\"");
                  //need the backslash for mysql to escape "
                  //so trying to get "PNL  DUCT 27.5\""
                    Console.WriteLine(dr[j].ToString());
                }
</code>```

Here's the fix as per Majid. Using prepared statement allowed the double quotes to be inserted into MySql
     try
            {
                conn.Open();
                cmd.Connection = conn;

```<code>            cmd.CommandText = "INSERT INTO test_table2 (Loc, Item, Description) VALUES( @Loc, @Item, @Desc )";
            cmd.Prepare();

            cmd.Parameters.AddWithValue("@Loc", "Loc");
            cmd.Parameters.AddWithValue("@Item", "Item");
            cmd.Parameters.AddWithValue("@Desc", "Desc");

            foreach (DataRow row in dtSheet.Rows)
            {
                cmd.Parameters["@Loc"].Value = row[0];
                cmd.Parameters["@Item"].Value = row[1];
                cmd.Parameters["@Desc"].Value = row[2];
                Console.WriteLine(cmd.ToString());

                cmd.ExecuteNonQuery();
            }
        }
</code>```

答:
Try using:</p>

```<code>dr[j].ToString().Replace("\"", @"\");
</code>```

Body:
I am importing and Excel spreadsheet in order to insert into a MySql database. Here's one record in the spreadsheet:

Loc     Item                 Description
FAB12   0121G00667PDG   PNL  DUCT 27.5"

I'm using OleDbDataReader to get a DataTable and that is working. The problem I'm having is when trying to replace the " with \" so that MySql will accept the double quote. I am trying to get C# to change 27.5" to 27.5\"

Thanks for any help you can provide.

Here's the result I'm getting now:

INSERT INTO test_table2 (Loc, Item, Description) VALUES ("FAB12
 ","0121G00667PDG","PNL  DUCT 27.5"")

Here's the code:

           for (int i = 0; i < dtSheet.Rows.Count; i++)
        {
            DataRow dr = dtSheet.Rows[i];
            for (int j = 0; j < dtSheet.Columns.Count; j++)
            {
                DataColumn dc = dtSheet.Columns[j];
                if (dr[j].ToString().Contains("\""))
                {
                    Console.WriteLine(dr[j].ToString());
                    dr[j].ToString().Replace("\"", "\\\"");
                  //need the backslash for mysql to escape "
                  //so trying to get "PNL  DUCT 27.5\""
                    Console.WriteLine(dr[j].ToString());
                }

Here's the fix as per Majid. Using prepared statement allowed the double quotes to be inserted into MySql
     try
            {
                conn.Open();
                cmd.Connection = conn;

            cmd.CommandText = "INSERT INTO test_table2 (Loc, Item, Description) VALUES( @Loc, @Item, @Desc )";
            cmd.Prepare();

            cmd.Parameters.AddWithValue("@Loc", "Loc");
            cmd.Parameters.AddWithValue("@Item", "Item");
            cmd.Parameters.AddWithValue("@Desc", "Desc");

            foreach (DataRow row in dtSheet.Rows)
            {
                cmd.Parameters["@Loc"].Value = row[0];
                cmd.Parameters["@Item"].Value = row[1];
                cmd.Parameters["@Desc"].Value = row[2];
                Console.WriteLine(cmd.ToString());

                cmd.ExecuteNonQuery();
            }
        }

Body:
Try using:

dr[j].ToString().Replace("\"", @"\");


问:
How can I replace date in oracle systimestamp
I can only use specific basedate value(YYYYMMDD) at my query.

I'd like to insert data with timestamp but just replaced with that date

```<code>INSERT INTO table (field1, field2, regTs)
 VALUES (:field1, :field2, systimestamp);
</code>```

from this query, how can I apply :basedate + systimestamp's hour, minute, second, microsecond

答:
First convert date to string using To_Char and concatenate time string with date string, now you can use To_Date function to convert the datetime string into timestamp.

Ex:

```<code>to_date(to_char(BASEDATE, 'YYYY/MM/DD') || ' ' ||TO_CHAR(sysdate,'HH24:MI:SS.FF'), 'YYYY/MM/DD HH24:MI:SS.FF')
</code>```

Hope this helps.

Body:
I can only use specific basedate value(YYYYMMDD) at my query.

I'd like to insert data with timestamp but just replaced with that date

INSERT INTO table (field1, field2, regTs)
 VALUES (:field1, :field2, systimestamp);

from this query, how can I apply :basedate + systimestamp's hour, minute, second, microsecond

Body:
First convert date to string using To_Char and concatenate time string with date string, now you can use To_Date function to convert the datetime string into timestamp.

Ex:

to_date(to_char(BASEDATE, 'YYYY/MM/DD') || ' ' ||TO_CHAR(sysdate,'HH24:MI:SS.FF'), 'YYYY/MM/DD HH24:MI:SS.FF')

Hope this helps.


问:
ValueError: could not convert string to float: Numpy array
This is my code snippet where data2 is a dataframe.
Why isn't the string object converted to float?
Same code works for converting string to int64.</p>

```<code>dt = np.dtype(object)  # Python object
df4 = data2['What was your +2 percentage?']
x=np.array(df4,dtype=dt)
y = x.astype(float)
</code>```

答:
Assuming df is your data frame, you can use pd.to_numeric to coerce your data into floats:

```<code>In [86]: pd.to_numeric(df['data'], errors='coerce')
Out[86]:
0    1.0
1    2.0
2   -3.0
3    5.5
Name: data, dtype: float64

In [91]: pd.to_numeric(df['data'], errors='coerce').tolist()
Out[91]: [1.0, 2.0, -3.0, 5.5]
</code>```

What you get is a list of floats, you can then convert it to a np.array().

Body:
This is my code snippet where data2 is a dataframe.
Why isn't the string object converted to float?
Same code works for converting string to int64.

dt = np.dtype(object)  # Python object
df4 = data2['What was your +2 percentage?']
x=np.array(df4,dtype=dt)
y = x.astype(float)

Body:
Assuming df is your data frame, you can use pd.to_numeric to coerce your data into floats:

In [86]: pd.to_numeric(df['data'], errors='coerce')
Out[86]:
0    1.0
1    2.0
2   -3.0
3    5.5
Name: data, dtype: float64

In [91]: pd.to_numeric(df['data'], errors='coerce').tolist()
Out[91]: [1.0, 2.0, -3.0, 5.5]

What you get is a list of floats, you can then convert it to a np.array().


问:
js check many variables not equal to empty
Maybe this is a duplicate question. But I didn't find any good answer at all.
I want to check multiple variables if not equal to empty('') as below;

```<code>var list1 = '';
var list2 = 'something';
var list3 = '';
var list4 = 'hello world';
</code>```

Now I want to check only one variable not equal empty returns true. If more than one variables are not empty returns false

As I tried

```<code>if(list1 != '' && list2 != '' && list3 != '' && list4 != ''){
   alert("ALL are filled");
   return false;
}
</code>```

I have no idea how to do it with javascript logical operations

答:
You can create an array and use filter + length to get the number of empty items:

var list1 = '';
var list2 = 'something';
var list3 = '';
var list4 = 'hello world';

var list = [list1, list2, list3, list4];

var numberEmptyItens = list.filter((item) => item === '').length;
console.log(numberEmptyItens);```

Body:
Maybe this is a duplicate question. But I didn't find any good answer at all.
I want to check multiple variables if not equal to empty('') as below;

var list1 = '';
var list2 = 'something';
var list3 = '';
var list4 = 'hello world';

Now I want to check only one variable not equal empty returns true. If more than one variables are not empty returns false

As I tried

if(list1 != '' && list2 != '' && list3 != '' && list4 != ''){
   alert("ALL are filled");
   return false;
}

I have no idea how to do it with javascript logical operations


问:
Check all radios with the same xpath - robotframework
I have 3 radio buttons in a form which have to checked by robotframework. Below is part of the html code:

```<code>  <div>
    <div>
    <label for="doc-22-Confirm">
    Confirm
    <input id="doc-22-Confirm" class="radiocheckbox" type="radio" checked="checked" value="Confirm" name="data[doc-22]"/>
    </label>
    <label for="doc-22-Reject">
    Reject
    <input id="doc-22-Reject" class="radiocheckbox" type="radio" value="Reject" name="data[doc-22]"/>
    </label>
    </div>
    <div>
    <label for="doc-23-Confirm">
    Confirm
    <input id="doc-23-Confirm" class="radiocheckbox" type="radio" checked="checked" value="Confirm" name="data[doc-22]"/>
    </label>
    <label for="doc-23-Reject">
    Reject
    <input id="doc-23-Reject" class="radiocheckbox" type="radio" value="Reject" name="data[doc-22]"/>
    </label>
    </div>
 </div>
</code>```

Ids are dynamic. So I'm trying to check all radios with this code but it just select one of them:

```<code>click element  xpath=//input[contains(@id,'Confirm')]
</code>```

I even tried this:

```<code>click element  xpath=//input[contains(@id,'Confirm')][1]
click element  xpath=//input[contains(@id,'Confirm')][2]
click element  xpath=//input[contains(@id,'Confirm')][3]
</code>```

But still it doesn't work.

答:
Try the following:

```<code>Click element  xpath=(//input[contains(@id,'Confirm')])[1]
</code>```

I added the '( )' , it should solve the issue.

Body:
I have 3 radio buttons in a form which have to checked by robotframework. Below is part of the html code:

    Confirm
    <input id="doc-22-Confirm" class="radiocheckbox" type="radio" checked="checked" value="Confirm" name="data[doc-22]"/>

    Reject
    <input id="doc-22-Reject" class="radiocheckbox" type="radio" value="Reject" name="data[doc-22]"/>

    Confirm
    <input id="doc-23-Confirm" class="radiocheckbox" type="radio" checked="checked" value="Confirm" name="data[doc-22]"/>

    Reject
    <input id="doc-23-Reject" class="radiocheckbox" type="radio" value="Reject" name="data[doc-22]"/>

Ids are dynamic. So I'm trying to check all radios with this code but it just select one of them:

click element  xpath=//input[contains(@id,'Confirm')]

I even tried this:

click element  xpath=//input[contains(@id,'Confirm')][1]
click element  xpath=//input[contains(@id,'Confirm')][2]
click element  xpath=//input[contains(@id,'Confirm')][3]

But still it doesn't work.

Body:
Try the following:

Click element  xpath=(//input[contains(@id,'Confirm')])[1]

I added the '( )' , it should solve the issue.


问:
Why color balls are not visible while mouse click?
This is the Code I'm testing =>

I followed everything but cant make result as preview, everything is working fine but color balls are not visible i think
pls help me out where i am missing the actual code? i am hitting my head again and again and tryng but no use!
p.s. i tried in local and js fiddle too, not working either -> https://jsfiddle.net/mhLjps6q/
here is

var d = document, $d = $(d),
    w = window, $w = $(w),
    wWidth = $w.width(), wHeight = $w.height(),
    credit = $('.credit > a'),
    particles = $('.particles'),
    particleCount = 0,
    sizes = [
      15, 20, 25, 35, 45
    ],
    colors = [
      '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
      '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50',
      '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800',
      '#FF5722', '#795548', '#9E9E9E', '#607D8B', '#777777'
    ],

    mouseX = $w.width() / 2, mouseY = $w.height() / 2;

function updateParticleCount () {
  $('.particle-count > .number').text(particleCount);
};

$w
.on( 'resize' , function () {
  wWidth = $w.width();
  wHeight = $w.height();
});

$d
.on( 'mousemove touchmove' , function ( event ) {
  event.preventDefault();
  event.stopPropagation();
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
})
.on( 'mousedown touchstart' , function( event ) {
  if( event.target === credit.get(0) ){
    return;
  }
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
  var timer = setInterval(function () {
    $d
    .one('mouseup mouseleave touchend touchcancel touchleave', function () {
      clearInterval( timer );
    })
    createParticle( event );
  }, 1000 / 60)

});

function createParticle ( event ) {
  var particle = $('
'),
      size = sizes[Math.floor(Math.random() * sizes.length)],
      color = colors[Math.floor(Math.random() * colors.length)],
      negative = size/2,
      speedHorz = Math.random() * 10,
      speedUp = Math.random() * 25,
      spinVal = 360 * Math.random(),
      spinSpeed = ((36 * Math.random())) * (Math.random() <=.5 ? -1 : 1),
      otime,
      time = otime = (1 + (.5 * Math.random())) * 1000,
      top = (mouseY - negative),
      left = (mouseX - negative),
      direction = Math.random() <=.5 ? -1 : 1 ,
      life = 10;

  particle
  .css({
    height: size + 'px',
    width: size + 'px',
    top: top + 'px',
    left: left + 'px',
    background: color,
    transform: 'rotate(' + spinVal + 'deg)',
    webkitTransform: 'rotate(' + spinVal + 'deg)'
  })
  .appendTo( particles );
  particleCount++;
  updateParticleCount();

  var particleTimer = setInterval(function () {
    time = time - life;
    left = left - (speedHorz * direction);
    top = top - speedUp;
    speedUp = Math.min(size, speedUp - 1);
    spinVal = spinVal + spinSpeed;

    particle
    .css({
      height: size + 'px',
      width: size + 'px',
      top: top + 'px',
      left: left + 'px',
      opacity: ((time / otime)/2) + .25,
     transform: 'rotate(' + spinVal + 'deg)',
     webkitTransform: 'rotate(' + spinVal + 'deg)'
    });

    if( time <= 0 || left <= -size || left >= wWidth + size || top >= wHeight + size ) {
      particle.remove();
    particleCount--;
      updateParticleCount();
      clearInterval(particleTimer);
    }
  }, 1000 / 50);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
  background: #fff;
  width: 100%;
  height: 100%;
  overflow: hidden;
  cursor: default;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
  font-family: 'PT Sans', sans-serif;
}

.title {
  font-size: 10vw;
  font-weight: 700;
  text-align: center;
  margin-top: 15%;
  color: #444;
}

.subtitle {
  font-size: 4vw;
  color: #777;
  font-weight: normal;
  text-align: center;
  margin-top: 0;
}

.credit {
  position: absolute;
  bottom: 5px;
  width: 100%;
  display: block;
  text-align: center;
  color: #777;
}
.credit > a {
  color: #777;
}

.particle-count {
  display: block;
  text-align: center;
  margin: 25px 0;
}

.particles > .particle {
  border-radius: 100%;
  background: transparent;
  position: absolute;
  background-size: 100% 100%;
  background-repeat: no-repeat;
}
.particles > .particle.smaller {
  width: 5px;
  height: 5px;
}
.particles > .particle.small {
  width: 10px;
  height: 10px;
}
.particles > .particle.normal {
  width: 15px;
  height: 15px;
}
.particles > .particle.big {
  width: 20px;
  height: 20px;
}
.particles > .particle.bigger {
  width: 25px;
  height: 25px;
}</code>```

PARTICLES!

Click / Touch Anywhere

  0
  Particles

  Created by
  Shawn G.

```

`

答:
Found the error why it is not working on your localhost and JSFiddle .

You Should start your JS code with $(document).ready(function()

Use my code and try to run it on your localhost and JSFiddle, it will work.

```<code><html>
<head>
<title>PARTICLES</title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var d = document, $d = $(d),
    w = window, $w = $(w),
    wWidth = $w.width(), wHeight = $w.height(),
    credit = $('.credit > a'),
    particles = $('.particles'),
    particleCount = 0,
    sizes = [
      15, 20, 25, 35, 45
    ],
    colors = [
      '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
      '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50',
      '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800',
      '#FF5722', '#795548', '#9E9E9E', '#607D8B', '#777777'
    ],

    mouseX = $w.width() / 2, mouseY = $w.height() / 2;

function updateParticleCount () {
  $('.particle-count > .number').text(particleCount);
};

$w
.on( 'resize' , function () {
  wWidth = $w.width();
  wHeight = $w.height();
});

$d
.on( 'mousemove touchmove' , function ( event ) {
  event.preventDefault();
  event.stopPropagation();
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
})
.on( 'mousedown touchstart' , function( event ) {
  if( event.target === credit.get(0) ){
    return;
  }
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
  var timer = setInterval(function () {
    $d
    .one('mouseup mouseleave touchend touchcancel touchleave', function () {
      clearInterval( timer );
    })
    createParticle( event );
  }, 1000 / 60)

});

function createParticle ( event ) {
  var particle = $('<div class="particle"/>'),
      size = sizes[Math.floor(Math.random() * sizes.length)],
      color = colors[Math.floor(Math.random() * colors.length)],
      negative = size/2,
      speedHorz = Math.random() * 10,
      speedUp = Math.random() * 25,
      spinVal = 360 * Math.random(),
      spinSpeed = ((36 * Math.random())) * (Math.random() <=.5 ? -1 : 1),
      otime,
      time = otime = (1 + (.5 * Math.random())) * 1000,
      top = (mouseY - negative),
      left = (mouseX - negative),
      direction = Math.random() <=.5 ? -1 : 1 ,
      life = 10;

  particle
  .css({
    height: size + 'px',
    width: size + 'px',
    top: top + 'px',
    left: left + 'px',
    background: color,
    transform: 'rotate(' + spinVal + 'deg)',
    webkitTransform: 'rotate(' + spinVal + 'deg)'
  })
  .appendTo( particles );
  particleCount++;
  updateParticleCount();

  var particleTimer = setInterval(function () {
    time = time - life;
    left = left - (speedHorz * direction);
    top = top - speedUp;
    speedUp = Math.min(size, speedUp - 1);
    spinVal = spinVal + spinSpeed;

    particle
    .css({
      height: size + 'px',
      width: size + 'px',
      top: top + 'px',
      left: left + 'px',
      opacity: ((time / otime)/2) + .25,
        transform: 'rotate(' + spinVal + 'deg)',
        webkitTransform: 'rotate(' + spinVal + 'deg)'
    });

    if( time <= 0 || left <= -size || left >= wWidth + size || top >= wHeight + size ) {
      particle.remove();
        particleCount--;
      updateParticleCount();
      clearInterval(particleTimer);
    }
  }, 1000 / 50);
}

});
</script>
<style>
html, body {
  background: #fff;
  width: 100%;
  height: 100%;
  overflow: hidden;
  cursor: default;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
  font-family: 'PT Sans', sans-serif;
}

.title {
  font-size: 10vw;
  font-weight: 700;
  text-align: center;
  margin-top: 15%;
  color: #444;
}

.subtitle {
  font-size: 4vw;
  color: #777;
  font-weight: normal;
  text-align: center;
  margin-top: 0;
}

.credit {
  position: absolute;
  bottom: 5px;
  width: 100%;
  display: block;
  text-align: center;
  color: #777;
}
.credit > a {
  color: #777;
}

.particle-count {
  display: block;
  text-align: center;
  margin: 25px 0;
}

.particles > .particle {
  border-radius: 100%;
  background: transparent;
  position: absolute;
  background-size: 100% 100%;
  background-repeat: no-repeat;
}
.particles > .particle.smaller {
  width: 5px;
  height: 5px;
}
.particles > .particle.small {
  width: 10px;
  height: 10px;
}
.particles > .particle.normal {
  width: 15px;
  height: 15px;
}
.particles > .particle.big {
  width: 20px;
  height: 20px;
}
.particles > .particle.bigger {
  width: 25px;
  height: 25px;
}
</style>
</head>
<body>

<h1 class='title'>PARTICLES!</h1>
<h4 class='subtitle'>Click / Touch Anywhere</h4>
<div class='particle-count'>
  <span class='number'>0</span>
  Particles
</div>
<span class='credit'>
  Created by
  <a href='https://twitter.com/Shawn_Sauce' target='_blank'>Shawn G.</a>
</span>
<div class='particles'></div>

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

Body:
This is the Code I'm testing =>

I followed everything but cant make result as preview, everything is working fine but color balls are not visible i think
pls help me out where i am missing the actual code? i am hitting my head again and again and tryng but no use!
p.s. i tried in local and js fiddle too, not working either -> https://jsfiddle.net/mhLjps6q/
here is

var d = document, $d = $(d),
    w = window, $w = $(w),
    wWidth = $w.width(), wHeight = $w.height(),
    credit = $('.credit > a'),
    particles = $('.particles'),
    particleCount = 0,
    sizes = [
      15, 20, 25, 35, 45
    ],
    colors = [
      '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
      '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50',
      '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800',
      '#FF5722', '#795548', '#9E9E9E', '#607D8B', '#777777'
    ],

    mouseX = $w.width() / 2, mouseY = $w.height() / 2;

function updateParticleCount () {
  $('.particle-count > .number').text(particleCount);
};

$w
.on( 'resize' , function () {
  wWidth = $w.width();
  wHeight = $w.height();
});

$d
.on( 'mousemove touchmove' , function ( event ) {
  event.preventDefault();
  event.stopPropagation();
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
})
.on( 'mousedown touchstart' , function( event ) {
  if( event.target === credit.get(0) ){
    return;
  }
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
  var timer = setInterval(function () {
    $d
    .one('mouseup mouseleave touchend touchcancel touchleave', function () {
      clearInterval( timer );
    })
    createParticle( event );
  }, 1000 / 60)

});

function createParticle ( event ) {
  var particle = $('
'),
      size = sizes[Math.floor(Math.random() * sizes.length)],
      color = colors[Math.floor(Math.random() * colors.length)],
      negative = size/2,
      speedHorz = Math.random() * 10,
      speedUp = Math.random() * 25,
      spinVal = 360 * Math.random(),
      spinSpeed = ((36 * Math.random())) * (Math.random() <=.5 ? -1 : 1),
      otime,
      time = otime = (1 + (.5 * Math.random())) * 1000,
      top = (mouseY - negative),
      left = (mouseX - negative),
      direction = Math.random() <=.5 ? -1 : 1 ,
      life = 10;

  particle
  .css({
    height: size + 'px',
    width: size + 'px',
    top: top + 'px',
    left: left + 'px',
    background: color,
    transform: 'rotate(' + spinVal + 'deg)',
    webkitTransform: 'rotate(' + spinVal + 'deg)'
  })
  .appendTo( particles );
  particleCount++;
  updateParticleCount();

  var particleTimer = setInterval(function () {
    time = time - life;
    left = left - (speedHorz * direction);
    top = top - speedUp;
    speedUp = Math.min(size, speedUp - 1);
    spinVal = spinVal + spinSpeed;

    particle
    .css({
      height: size + 'px',
      width: size + 'px',
      top: top + 'px',
      left: left + 'px',
      opacity: ((time / otime)/2) + .25,
     transform: 'rotate(' + spinVal + 'deg)',
     webkitTransform: 'rotate(' + spinVal + 'deg)'
    });

    if( time <= 0 || left <= -size || left >= wWidth + size || top >= wHeight + size ) {
      particle.remove();
    particleCount--;
      updateParticleCount();
      clearInterval(particleTimer);
    }
  }, 1000 / 50);
}

html, body {
  background: #fff;
  width: 100%;
  height: 100%;
  overflow: hidden;
  cursor: default;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
  font-family: 'PT Sans', sans-serif;
}

.title {
  font-size: 10vw;
  font-weight: 700;
  text-align: center;
  margin-top: 15%;
  color: #444;
}

.subtitle {
  font-size: 4vw;
  color: #777;
  font-weight: normal;
  text-align: center;
  margin-top: 0;
}

.credit {
  position: absolute;
  bottom: 5px;
  width: 100%;
  display: block;
  text-align: center;
  color: #777;
}
.credit > a {
  color: #777;
}

.particle-count {
  display: block;
  text-align: center;
  margin: 25px 0;
}

.particles > .particle {
  border-radius: 100%;
  background: transparent;
  position: absolute;
  background-size: 100% 100%;
  background-repeat: no-repeat;
}
.particles > .particle.smaller {
  width: 5px;
  height: 5px;
}
.particles > .particle.small {
  width: 10px;
  height: 10px;
}
.particles > .particle.normal {
  width: 15px;
  height: 15px;
}
.particles > .particle.big {
  width: 20px;
  height: 20px;
}
.particles > .particle.bigger {
  width: 25px;
  height: 25px;
}

PARTICLES!

Click / Touch Anywhere

  0
  Particles

  Created by
  Shawn G.

`

Body:
Found the error why it is not working on your localhost and JSFiddle .

You Should start your JS code with $(document).ready(function()

Use my code and try to run it on your localhost and JSFiddle, it will work.

<html>
<head>
<title>PARTICLES</title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var d = document, $d = $(d),
    w = window, $w = $(w),
    wWidth = $w.width(), wHeight = $w.height(),
    credit = $('.credit > a'),
    particles = $('.particles'),
    particleCount = 0,
    sizes = [
      15, 20, 25, 35, 45
    ],
    colors = [
      '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5',
      '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50',
      '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800',
      '#FF5722', '#795548', '#9E9E9E', '#607D8B', '#777777'
    ],

    mouseX = $w.width() / 2, mouseY = $w.height() / 2;

function updateParticleCount () {
  $('.particle-count > .number').text(particleCount);
};

$w
.on( 'resize' , function () {
  wWidth = $w.width();
  wHeight = $w.height();
});

$d
.on( 'mousemove touchmove' , function ( event ) {
  event.preventDefault();
  event.stopPropagation();
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
})
.on( 'mousedown touchstart' , function( event ) {
  if( event.target === credit.get(0) ){
    return;
  }
  mouseX = event.clientX;
  mouseY = event.clientY;
  if( !!event.originalEvent.touches ) {
    mouseX = event.originalEvent.touches[0].clientX;
    mouseY = event.originalEvent.touches[0].clientY;
  }
  var timer = setInterval(function () {
    $d
    .one('mouseup mouseleave touchend touchcancel touchleave', function () {
      clearInterval( timer );
    })
    createParticle( event );
  }, 1000 / 60)

});

function createParticle ( event ) {
  var particle = $('<div class="particle"/>'),
      size = sizes[Math.floor(Math.random() * sizes.length)],
      color = colors[Math.floor(Math.random() * colors.length)],
      negative = size/2,
      speedHorz = Math.random() * 10,
      speedUp = Math.random() * 25,
      spinVal = 360 * Math.random(),
      spinSpeed = ((36 * Math.random())) * (Math.random() <=.5 ? -1 : 1),
      otime,
      time = otime = (1 + (.5 * Math.random())) * 1000,
      top = (mouseY - negative),
      left = (mouseX - negative),
      direction = Math.random() <=.5 ? -1 : 1 ,
      life = 10;

  particle
  .css({
    height: size + 'px',
    width: size + 'px',
    top: top + 'px',
    left: left + 'px',
    background: color,
    transform: 'rotate(' + spinVal + 'deg)',
    webkitTransform: 'rotate(' + spinVal + 'deg)'
  })
  .appendTo( particles );
  particleCount++;
  updateParticleCount();

  var particleTimer = setInterval(function () {
    time = time - life;
    left = left - (speedHorz * direction);
    top = top - speedUp;
    speedUp = Math.min(size, speedUp - 1);
    spinVal = spinVal + spinSpeed;

    particle
    .css({
      height: size + 'px',
      width: size + 'px',
      top: top + 'px',
      left: left + 'px',
      opacity: ((time / otime)/2) + .25,
        transform: 'rotate(' + spinVal + 'deg)',
        webkitTransform: 'rotate(' + spinVal + 'deg)'
    });

    if( time <= 0 || left <= -size || left >= wWidth + size || top >= wHeight + size ) {
      particle.remove();
        particleCount--;
      updateParticleCount();
      clearInterval(particleTimer);
    }
  }, 1000 / 50);
}

});
</script>
<style>
html, body {
  background: #fff;
  width: 100%;
  height: 100%;
  overflow: hidden;
  cursor: default;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
  font-family: 'PT Sans', sans-serif;
}

.title {
  font-size: 10vw;
  font-weight: 700;
  text-align: center;
  margin-top: 15%;
  color: #444;
}

.subtitle {
  font-size: 4vw;
  color: #777;
  font-weight: normal;
  text-align: center;
  margin-top: 0;
}

.credit {
  position: absolute;
  bottom: 5px;
  width: 100%;
  display: block;
  text-align: center;
  color: #777;
}
.credit > a {
  color: #777;
}

.particle-count {
  display: block;
  text-align: center;
  margin: 25px 0;
}

.particles > .particle {
  border-radius: 100%;
  background: transparent;
  position: absolute;
  background-size: 100% 100%;
  background-repeat: no-repeat;
}
.particles > .particle.smaller {
  width: 5px;
  height: 5px;
}
.particles > .particle.small {
  width: 10px;
  height: 10px;
}
.particles > .particle.normal {
  width: 15px;
  height: 15px;
}
.particles > .particle.big {
  width: 20px;
  height: 20px;
}
.particles > .particle.bigger {
  width: 25px;
  height: 25px;
}
</style>
</head>
<body>

<h1 class='title'>PARTICLES!</h1>
<h4 class='subtitle'>Click / Touch Anywhere</h4>
<div class='particle-count'>
  <span class='number'>0</span>
  Particles
</div>
<span class='credit'>
  Created by
  <a href='https://twitter.com/Shawn_Sauce' target='_blank'>Shawn G.</a>
</span>
<div class='particles'></div>

</body>
</html>


问:
Update react state after a certain interval
```<code>constructor(){
    super();
    this.state={
        data : [1,2,3,4,1,2,3,4,1,3,1,4,12,2,3,2]
    };

}
componentDidMount(){setInterval(this.updateCanvas(),5000);}

updateCanvas() {
    console.log(this.props.newData);
    let data = this.state.data.slice();
    let length = data.length;
    console.log(length);
    data.push(20);
    this.setState({data:data},()=>{console.log(this.state.data);});
}
</code>```

I am trying to push a new value to the state every 5s, but the state changes immediately. How can I achieve the effect I want?

答:
Why doesn't it work?

There are actually two problems:

You need to pass a function to setInterval. The setInterval method excepts a function as it's 1st parameter. When you usesetInterval(this.updateCanvas(),5000);, you pass the returned value of the invoked method this.updateCanvas(). Since the method returns nothing (undefined), what you actually get is window.setInterval(undefined, 5000);.

You have to bind that function to the component instance's this. Since the updateCanvas method uses this, for example this.setState(),

Binding updateCanvas to this and invoking in setInterval:

Pass setInveral an arrow function, and invoke updateCanvas inside:

```<code>componentDidMount(){
    setInterval(() => this.updateCanvas(),5000);
}
</code>```

Or

Bind the method to the component instance this:

```<code>constructor(){
    super();
    this.state={
        data : [1,2,3,4,1,2,3,4,1,3,1,4,12,2,3,2]
    };

    this.updateCanvas = this.updateCanvas.bind(this); // bind the method to this
}

componentDidMount(){
    setInterval(this.updateCanvas,5000);
}
</code>```

Body:
constructor(){
    super();
    this.state={
        data : [1,2,3,4,1,2,3,4,1,3,1,4,12,2,3,2]
    };

}
componentDidMount(){setInterval(this.updateCanvas(),5000);}

updateCanvas() {
    console.log(this.props.newData);
    let data = this.state.data.slice();
    let length = data.length;
    console.log(length);
    data.push(20);
    this.setState({data:data},()=>{console.log(this.state.data);});
}

I am trying to push a new value to the state every 5s, but the state changes immediately. How can I achieve the effect I want?

Body:
Why doesn't it work?

There are actually two problems:

You need to pass a function to setInterval. The setInterval method excepts a function as it's 1st parameter. When you usesetInterval(this.updateCanvas(),5000);, you pass the returned value of the invoked method this.updateCanvas(). Since the method returns nothing (undefined), what you actually get is window.setInterval(undefined, 5000);.

You have to bind that function to the component instance's this. Since the updateCanvas method uses this, for example this.setState(),

Binding updateCanvas to this and invoking in setInterval:

Pass setInveral an arrow function, and invoke updateCanvas inside:

componentDidMount(){
    setInterval(() => this.updateCanvas(),5000);
}

Or

Bind the method to the component instance this:

constructor(){
    super();
    this.state={
        data : [1,2,3,4,1,2,3,4,1,3,1,4,12,2,3,2]
    };

    this.updateCanvas = this.updateCanvas.bind(this); // bind the method to this
}

componentDidMount(){
    setInterval(this.updateCanvas,5000);
}


问:
Misaligned DetailsView controls
I'm using a DetailsView in an applicaoon I am developing, and have a minor issue. My detailsview has multiple control types - checkboxs, textboxs, drop down lists etc. They are all slightly misaligned from each other vertically -I.e. Text boss are pushed slightly right for some reason.

I can easily fix it by changing the margins of the controls so they line up, but that's rather 'hacky' and probably won't work well in all browsers. Is there a simpler way?

答: You can change the align of detailsview so every item will be have the same align.</p>

Title: Misaligned DetailsView controls


问:
Left right button for slider like Bootstrap carousel
I Want to slide my images right and left on click. I use jquery for that. but problem is that when I continue to click on right the div goes right and blank space display. I tried but it not fixes. I'm a newbie in jquery.</p>

```<code>    <!DOCTYPE html><html class=''>
<head>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<style class="cp-pen-styles">
.row_outer {
  *overflow-x: auto;
  width: 100%;
}
.row__inner {
  -webkit-transition: 450ms -webkit-transform;
  transition: 450ms -webkit-transform;
  transition: 450ms transform;
  transition: 450ms transform, 450ms -webkit-transform;
  font-size: 0;
  white-space: nowrap;
  margin: 70.3125px 0;
  padding-bottom: 10px;
}
.tile {
  position: relative;
  display: inline-block;
  width: 326px;
  height: 192px;
  margin-right: 10px;
  font-size: 20px;
  cursor: pointer;
  -webkit-transition: 450ms all;
  transition: 450ms all;
  -webkit-transform-origin: center left;
          transform-origin: center left;
}
.tile__img {
  width: 326px;
  height: 192px;
  -o-object-fit: cover;
     object-fit: cover;
}
.tile__details {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  top: 0;
  font-size: 10px;
  opacity: 0;
  background: -webkit-linear-gradient(bottom, rgba(0,0,0,0.9) 0%, rgba(0,0,0,0) 100%);
  background: linear-gradient(to top, rgba(0,0,0,0.9) 0%, rgba(0,0,0,0) 100%);
  -webkit-transition: 450ms opacity;
  transition: 450ms opacity;
}
.tile__details:after,
.tile__details:before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  display: #000;
}
.tile__details:after {
  margin-top: -25px;
  margin-left: -25px;
  width: 50px;
  height: 50px;
  border: 3px solid #ecf0f1;
  line-height: 50px;
  text-align: center;
  border-radius: 100%;
  background: rgba(0,0,0,0.5);
  z-index: 1;
}
.tile__details:before {
  content: '▶';
  left: 0;
  width: 100%;
  font-size: 30px;
  margin-left: 7px;
  margin-top: -18px;
  text-align: center;
  z-index: 2;
  color: #fff;
}
.tile:hover .tile__details {
  opacity: 1;
}
.tile__title {
  position: absolute;
  bottom: 0;
  padding: 10px;
  color: #fff;
}
.row__inner:hover {
  -webkit-transform: translate3d(-72.5px, 0, 0);
          transform: translate3d(-72.5px, 0, 0);
}
.row__inner:hover .tile {
  opacity: 0.3;
}
.row__inner:hover .tile:hover {
  -webkit-transform: scale(1.5);
          transform: scale(1.5);
  opacity: 1;
}
.tile:hover ~ .tile {
  -webkit-transform: translate3d(215px, 0, 0);
          transform: translate3d(215px, 0, 0);
}

    .buttons{
        position: absolute;
        width: 100%;
        margin-right: 10px;
        font-size: 20px;
        margin-top: -190px;
    }

    .buttons button{
        height: 100%;
        padding: 7px 20px;
        color: #fa8f33;
        border: 1px solid
    }

    .left{
    float: left;
    }

    .right{
        float: right;
    }

/* Sweep To Right */
.hvr-sweep-to-right {
  display: inline-block;
  vertical-align: middle;
  -webkit-transform: perspective(1px) translateZ(0);
  transform: perspective(1px) translateZ(0);
  box-shadow: 0 0 1px transparent;
  position: relative;
  -webkit-transition-property: color;
  transition-property: color;
  -webkit-transition-duration: 0.3s;
  transition-duration: 0.3s;
}
.hvr-sweep-to-right:before {
  content: "";
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fa8f33;
  -webkit-transform: scaleX(0);
  transform: scaleX(0);
  -webkit-transform-origin: 0 50%;
  transform-origin: 0 50%;
  -webkit-transition-property: transform;
  transition-property: transform;
  -webkit-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -webkit-transition-timing-function: ease-out;
  transition-timing-function: ease-out;
}
.hvr-sweep-to-right:hover, .hvr-sweep-to-right:focus, .hvr-sweep-to-right:active {
  color: white;
}
.hvr-sweep-to-right:hover:before, .hvr-sweep-to-right:focus:before, .hvr-sweep-to-right:active:before {
  -webkit-transform: scaleX(1);
  transform: scaleX(1);
}

/* Sweep To Left */
.hvr-sweep-to-left {
  display: inline-block;
  vertical-align: middle;
  -webkit-transform: perspective(1px) translateZ(0);
  transform: perspective(1px) translateZ(0);
  box-shadow: 0 0 1px transparent;
  position: relative;
  -webkit-transition-property: color;
  transition-property: color;
  -webkit-transition-duration: 0.3s;
  transition-duration: 0.3s;
}
.hvr-sweep-to-left:before {
  content: "";
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fa8f33;
  -webkit-transform: scaleX(0);
  transform: scaleX(0);
  -webkit-transform-origin: 100% 50%;
  transform-origin: 100% 50%;
  -webkit-transition-property: transform;
  transition-property: transform;
  -webkit-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -webkit-transition-timing-function: ease-out;
  transition-timing-function: ease-out;
}
.hvr-sweep-to-left:hover, .hvr-sweep-to-left:focus, .hvr-sweep-to-left:active {
  color: white;
}
.hvr-sweep-to-left:hover:before, .hvr-sweep-to-left:focus:before, .hvr-sweep-to-left:active:before {
  -webkit-transform: scaleX(1);
  transform: scaleX(1);
}

</style></head><body>
<div class="contain">

  <div class="row_outer">
    <div class="row__inner">

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-1.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img " src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-2.jpg" alt="" />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img " src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-3.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-4.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-5.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-6.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-7.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-8.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-9.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-10.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-11.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-12.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-13.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-14.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-15.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-16.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-17.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-18.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>

      <div class="tile">
        <div class="tile__media">
          <img class="tile__img" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/70390/show-19.jpg" alt=""  />
        </div>
        <div class="tile__details">
          <div class="tile__title">
            Top Gear
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="buttons">
         <button class="left hvr-sweep-to-left " id="left"><span><i class="fa fa-angle-double-left" aria-hidden="true"></i>
</span></button>
         <button href="" class="right hvr-sweep-to-right " id="right"><span><i class="fa fa-angle-double-right" aria-hidden="true"></i>
</span></button>
     </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>

    $( "#right" ).click(function() {
      $( ".tile" ).animate({ "left": "+=365px" }, "1000" );
    });

    $( "#left" ).click(function(){
      $( ".tile" ).animate({ "left": "-=365px" }, "1000" );
    });
    </script>

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

答:
You can check this out jsfiddle link</p>

```<code>    var slideIndex = 1;
var length = $(".tile").length;

$( "#right" ).click(function() {
    if(slideIndex != 1){
  $( ".tile" ).animate({ "left": "+=365px" }, "1000" );
  slideIndex--;
  }
});

$( "#left" ).click(function() {
    if(slideIndex >= length-1 ){

  }else{
  $( ".tile" ).animate({ "left": "-=365px" }, "1000" );
  slideIndex++;
  }

});
</code>```

Body:
I Want to slide my images right and left on click. I use jquery for that. but problem is that when I continue to click on right the div goes right and blank space display. I tried but it not fixes. I'm a newbie in jquery.

    <!DOCTYPE html>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

            Top Gear

         <button class="left hvr-sweep-to-left " id="left">
</button>
         <button href="" class="right hvr-sweep-to-right " id="right">
</button>

Body:
You can check this out jsfiddle link

    var slideIndex = 1;
var length = $(".tile").length;

$( "#right" ).click(function() {
    if(slideIndex != 1){
  $( ".tile" ).animate({ "left": "+=365px" }, "1000" );
  slideIndex--;
  }
});

$( "#left" ).click(function() {
    if(slideIndex >= length-1 ){

  }else{
  $( ".tile" ).animate({ "left": "-=365px" }, "1000" );
  slideIndex++;
  }

});


问:
Setting up Qt Creator for linking and compiling assembly code
I've been studying C++ and x64 Assembly the last weeks and would like to get into GUI programming with the Qt IDE. The problem is that I can't find a way to link and compile a file containing assembly code. I've been browsing the internet and this site without finding anything helpful.

Here is what I have tried so far:
.pro

```<code>QMAKE_CXXFLAGS += -save-temps
QT       += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = test---
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS

QMAKE_EXTRA_COMPILERS += nasm

SOURCES += main.cpp\
    mainwindow.cpp\
    asm.s

HEADERS  += mainwindow.h
FORMS    += mainwindow.ui
</code>```

mainwindow.cpp

```<code>//code
extern "C" __int64 assembly();

//code

void MainWindow::on_pushButton_clicked()
{
    int zahl = assembly(); // place what the assembly function return into "zahl"
}
</code>```

asm.s

```<code>.code
.global
assembly proc

mov rax, 1
ret

xor rax, rax

assembly endp
end
</code>```

Build setup img

Attempting to compile the project leads to following error message:

```<code>mainwindow.obj:-1: Fehler: LNK2019: unresolved external symbol assembly referenced in function "private: void __cdecl MainWindow::on_pushButton_clicked(void)" (?on_pushButton_clicked@MainWindow@@AEAAXXZ)
</code>```

I have also found a setup guide on this for console applications. But it doesn't seem to be suitable for GUI applications: http ://dvisagie.blogspot.de/2011/09/setting-up-qt-creator-for-assemblylinux.html

Here's how I've been compiling assembly files in Visual Studio:
.cpp:

```<code>#include "stdafx.h"
#include<iostream>

using namespace std;

extern "C" __int64 _stdcall assembly();

int main()
{
    cout << assembly() << endl;

    system("pause");
    return 0;
}
</code>```

.asm:
    .code
    assembly proc

```<code>mov rax, 1234
ret
xor rax, rax

assembly endp
end
</code>```

EDIT: appended build

答:
The code should look like this (in your pro file). The first compiler (nasm) generates the lst file from the asm file. The second compiler (nasm_ld) then runs ld to generate an object file.

For the nasm compiler, ASM_FILES is the input variable that it reads from, and writes the name of the generated lst to LST_FILES, which is the processed by nasm_ld and the objects added to OBJECTS, which should make the available for the linker.

```<code>nasm.name = nasm ${QMAKE_FILE_IN}
nasm.input = ASM_FILES
nasm.variable_out = OBJECTS
nasm.commands = nasm -f win64 ${QMAKE_FILE_IN} -o ${QMAKE_FILE_OUT}
nasm.output = ${QMAKE_VAR_OBJECTS_DIR}${QMAKE_FILE_IN_BASE}$${first(QMAKE_EXT_OBJ)}
nasm.CONFIG += target_predeps

QMAKE_EXTRA_COMPILERS  += nasm

ASM_FILES += asm.s
</code>```

Edit: I have updated the code based on the comments. Try if this works. It should compile the asm file and add the object file to the linker. Please remove your custom build step first.

Body:
I've been studying C++ and x64 Assembly the last weeks and would like to get into GUI programming with the Qt IDE. The problem is that I can't find a way to link and compile a file containing assembly code. I've been browsing the internet and this site without finding anything helpful.

Here is what I have tried so far:
.pro

QMAKE_CXXFLAGS += -save-temps
QT       += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = test---
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS

QMAKE_EXTRA_COMPILERS += nasm

SOURCES += main.cpp\
    mainwindow.cpp\
    asm.s

HEADERS  += mainwindow.h
FORMS    += mainwindow.ui

mainwindow.cpp

//code
extern "C" __int64 assembly();

//code

void MainWindow::on_pushButton_clicked()
{
    int zahl = assembly(); // place what the assembly function return into "zahl"
}

asm.s

.code
.global
assembly proc

mov rax, 1
ret

xor rax, rax

assembly endp
end

Build setup img

Attempting to compile the project leads to following error message:

mainwindow.obj:-1: Fehler: LNK2019: unresolved external symbol assembly referenced in function "private: void __cdecl MainWindow::on_pushButton_clicked(void)" (?on_pushButton_clicked@MainWindow@@AEAAXXZ)

I have also found a setup guide on this for console applications. But it doesn't seem to be suitable for GUI applications: http ://dvisagie.blogspot.de/2011/09/setting-up-qt-creator-for-assemblylinux.html

Here's how I've been compiling assembly files in Visual Studio:
.cpp:

#include "stdafx.h"
#include<iostream>

using namespace std;

extern "C" __int64 _stdcall assembly();

int main()
{
    cout << assembly() << endl;

    system("pause");
    return 0;
}

.asm:
    .code
    assembly proc

mov rax, 1234
ret
xor rax, rax

assembly endp
end

EDIT: appended build

Body:
The code should look like this (in your pro file). The first compiler (nasm) generates the lst file from the asm file. The second compiler (nasm_ld) then runs ld to generate an object file.

For the nasm compiler, ASM_FILES is the input variable that it reads from, and writes the name of the generated lst to LST_FILES, which is the processed by nasm_ld and the objects added to OBJECTS, which should make the available for the linker.

nasm.name = nasm ${QMAKE_FILE_IN}
nasm.input = ASM_FILES
nasm.variable_out = OBJECTS
nasm.commands = nasm -f win64 ${QMAKE_FILE_IN} -o ${QMAKE_FILE_OUT}
nasm.output = ${QMAKE_VAR_OBJECTS_DIR}${QMAKE_FILE_IN_BASE}$${first(QMAKE_EXT_OBJ)}
nasm.CONFIG += target_predeps

QMAKE_EXTRA_COMPILERS  += nasm

ASM_FILES += asm.s

Edit: I have updated the code based on the comments. Try if this works. It should compile the asm file and add the object file to the linker. Please remove your custom build step first.


问:
Creating a Column for Price in Laravel Schema
I want to create a column for price in a laravel schema.

```<code>public function up()
{
    Schema::create('cameras', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('condition');
        $table->string('price');
        $table->string('type');
        $table->timestamps();
    });
}
</code>```

Or is there an alternative data type I can use?  As I don't see anything for monetary value in the documentation.  Any help would be appreciated.

答:
There is 'float' type for your purpose it seems fine unless you don't want to save currency too:

$table->float('amount')
```

Available types are listed in documentation.
https://laravel.com/docs/5.4/migrations#creating-columns

If you do want to save currency with price you will have to use string , or create a new column for currency-type can be another work around.

ContentLicense: CC BY-SA 4.0

Body:
I want to create a column for price in a laravel schema.

public function up()
{
    Schema::create('cameras', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('condition');
        $table->string('price');
        $table->string('type');
        $table->timestamps();
    });
}

Or is there an alternative data type I can use?  As I don't see anything for monetary value in the documentation.  Any help would be appreciated.

Body:
There is 'float' type for your purpose it seems fine unless you don't want to save currency too:

$table->float('amount')

Available types are listed in documentation.
https://laravel.com/docs/5.4/migrations#creating-columns

If you do want to save currency with price you will have to use string , or create a new column for currency-type can be another work around.


问:
`DesignMode` in subcontrols is not set correctly?
I have a compound control contains nested controls. The problem i am facing is that control read properties from a global setting class which is static and intern read from setting file. To stop individual control from accessing configuration in design mode i added check in each control.

```<code>If(!DesignMode){
    ...
    //Initialize properties e.g. prop = AppConfig.GetProperty("prop1");
}
</code>```

The problem is that individual control work fine when open in VS. But when i open top control containing nested control i get error by VS designer. The error is that in a nested control DesignMode=false for some reason.

I also created a test app and created a simple control within another control to test if there is a problem with VS but it seem to work correctly for any depth of controls.

I dont even know how to debug this. For now i comment out the property initializing code and build it and then open designer and there uncomment it and build it again to run it.

Did anyone came across this problem or is there any way to fix it.

答:
The problem you're facing is that the DesignMode is not set while in Constructor (at any level).

Move your initialization methods to Load event, to avoid this problem.

Also, you could add additional comparison with:

```<code> protected bool IsInDesignMode
 {
    get
    {
        return DesignMode || LicenseManager.UsageMode == LicenseUsageMode.Designtime;
    }
 }
</code>```

This would definitely provide an acurate way to determine the design mode because sometimes VisualStudio
returns DesignMode = false while you're placing user controls on the form, or refreshing the form display itself in design.

Body:
I have a compound control contains nested controls. The problem i am facing is that control read properties from a global setting class which is static and intern read from setting file. To stop individual control from accessing configuration in design mode i added check in each control.

If(!DesignMode){
    ...
    //Initialize properties e.g. prop = AppConfig.GetProperty("prop1");
}

The problem is that individual control work fine when open in VS. But when i open top control containing nested control i get error by VS designer. The error is that in a nested control DesignMode=false for some reason.

I also created a test app and created a simple control within another control to test if there is a problem with VS but it seem to work correctly for any depth of controls.

I dont even know how to debug this. For now i comment out the property initializing code and build it and then open designer and there uncomment it and build it again to run it.

Did anyone came across this problem or is there any way to fix it.

Body:
The problem you're facing is that the DesignMode is not set while in Constructor (at any level).

Move your initialization methods to Load event, to avoid this problem.

Also, you could add additional comparison with:

 protected bool IsInDesignMode
 {
    get
    {
        return DesignMode || LicenseManager.UsageMode == LicenseUsageMode.Designtime;
    }
 }

This would definitely provide an acurate way to determine the design mode because sometimes VisualStudio
returns DesignMode = false while you're placing user controls on the form, or refreshing the form display itself in design.


问:
SQL: how to randomly sample a number of values for each row
Suppose I have a table A (id string), what I need is to create a table B (id1 string, id2 string) such that, B.id2 is randomly sampled from A.id. B.id1 is the same as A.id. For example:

table A:

```<code>id
1
2
3
4
</code>```

table B:

```<code>id1   id2
 1     2
 1     3
 2     4
 2     3
 3     1
 3     2
 4     1
 4     4
</code>```

That is, for each id in A, randomly sample 2 id in A as a new column id2. How can I do this with SQL? I would prefer a sample without replacement. But it is ok if id2 equals id1. Thank you for helping me!

答:
Try this (done in SQL Server):

```<code>SELECT ID FROM TableA ORDER By ID

OPEN CURA

FETCH NEXT FROM CURA
INTO @id1

WHILE @@FETCH_STATUS = 0
BEGIN

--fetch 2 rows casually from same table, different from the first column
DECLARE CURB CURSOR FOR
SELECT ID FROM TableA WHERE ID <> @id1 ORDER BY NEWID()

OPEN CURB

FETCH NEXT FROM CURB INTO @id2
INSERT INTO @TempTable(ID1, ID2) VALUES (@id1, @id2)
FETCH NEXT FROM CURB INTO @id2
INSERT INTO @TempTable(ID1, ID2) VALUES (@id1, @id2)

CLOSE CURB
DEALLOCATE CURB

FETCH NEXT FROM CURA
INTO @id1

END

CLOSE CURA
DEALLOCATE CURA

SELECT * from @TempTable ORDER BY ID1, ID2
</code>```

If you want a different number of rows for each group, simply substitute the two FETCH NEXT FROM CURB with a counted loop

Body:
Suppose I have a table A (id string), what I need is to create a table B (id1 string, id2 string) such that, B.id2 is randomly sampled from A.id. B.id1 is the same as A.id. For example:

table A:

id
1
2
3
4

table B:

id1   id2
 1     2
 1     3
 2     4
 2     3
 3     1
 3     2
 4     1
 4     4

That is, for each id in A, randomly sample 2 id in A as a new column id2. How can I do this with SQL? I would prefer a sample without replacement. But it is ok if id2 equals id1. Thank you for helping me!

Body:
Try this (done in SQL Server):

SELECT ID FROM TableA ORDER By ID

OPEN CURA

FETCH NEXT FROM CURA
INTO @id1

WHILE @@FETCH_STATUS = 0
BEGIN

--fetch 2 rows casually from same table, different from the first column
DECLARE CURB CURSOR FOR
SELECT ID FROM TableA WHERE ID <> @id1 ORDER BY NEWID()

OPEN CURB

FETCH NEXT FROM CURB INTO @id2
INSERT INTO @TempTable(ID1, ID2) VALUES (@id1, @id2)
FETCH NEXT FROM CURB INTO @id2
INSERT INTO @TempTable(ID1, ID2) VALUES (@id1, @id2)

CLOSE CURB
DEALLOCATE CURB

FETCH NEXT FROM CURA
INTO @id1

END

CLOSE CURA
DEALLOCATE CURA

SELECT * from @TempTable ORDER BY ID1, ID2

If you want a different number of rows for each group, simply substitute the two FETCH NEXT FROM CURB with a counted loop


问:
Is it possible to set a property on UIView via Swift 4 KeyPaths in an extension?
I'm trying to create a set method on UIView via an extension that will allow me to set a color via the new Swift 4 KeyPaths. If I do the following I get the error Cannot assign to immutable expression of type 'UIColor?'

```<code>extension UIView {
    func set(color: UIColor, forKeyPath path: KeyPath<UIView, UIColor?>) {
        self[keyPath: path] = color //  Error: Cannot assign to immutable expression of type 'UIColor?'
    }
}
view.set(color: .white, forKeyPath: \.backgroundColor)
</code>```

If I use this outside of an extension it works fine:

```<code>let view = UIView()
let path = \UIView.backgroundColor
view[keyPath: path] = .white // Works fine
</code>```

Also using the old style of KeyPath works fine:

```<code>extension UIView {
    func set(color: UIColor, forKeyPath path: String) {
        self.setValue(color, forKey: path)
    }
}
view.set(color: .white, forKeyPath: #keyPath(UIView.backgroundColor))
</code>```

Thanks for any help.

答:
In your standalone example, if you option-click on path you will see that its declaration is:

```<code>let path: ReferenceWritableKeyPath<UIView, UIColor?>
</code>```

So it isn't just a KeyPath but a ReferenceWritableKeyPath.  Clicking on ReferenceWritableKeyPath reveals that it is:

A key path that supports reading from and writing to the resulting
  value with reference semantics.

So the KeyPath type that you are using in your extension is too restrictive as it doesn't allow writing.

Changing KeyPath to ReferenceWritableKeyPath passes along the correct type makes it work:

```<code>extension UIView {
    func set(color: UIColor, forKeyPath path: ReferenceWritableKeyPath<UIView, UIColor?>) {
        self[keyPath: path] = color
    }
}

view.set(color: .white, forKeyPath: \.backgroundColor)  // success!
</code>```

Body:
I'm trying to create a set method on UIView via an extension that will allow me to set a color via the new Swift 4 KeyPaths. If I do the following I get the error Cannot assign to immutable expression of type 'UIColor?'

extension UIView {
    func set(color: UIColor, forKeyPath path: KeyPath<UIView, UIColor?>) {
        self[keyPath: path] = color //  Error: Cannot assign to immutable expression of type 'UIColor?'
    }
}
view.set(color: .white, forKeyPath: \.backgroundColor)

If I use this outside of an extension it works fine:

let view = UIView()
let path = \UIView.backgroundColor
view[keyPath: path] = .white // Works fine

Also using the old style of KeyPath works fine:

extension UIView {
    func set(color: UIColor, forKeyPath path: String) {
        self.setValue(color, forKey: path)
    }
}
view.set(color: .white, forKeyPath: #keyPath(UIView.backgroundColor))

Thanks for any help.

Body:
In your standalone example, if you option-click on path you will see that its declaration is:

let path: ReferenceWritableKeyPath<UIView, UIColor?>

So it isn't just a KeyPath but a ReferenceWritableKeyPath.  Clicking on ReferenceWritableKeyPath reveals that it is:

A key path that supports reading from and writing to the resulting
  value with reference semantics.

So the KeyPath type that you are using in your extension is too restrictive as it doesn't allow writing.

Changing KeyPath to ReferenceWritableKeyPath passes along the correct type makes it work:

extension UIView {
    func set(color: UIColor, forKeyPath path: ReferenceWritableKeyPath<UIView, UIColor?>) {
        self[keyPath: path] = color
    }
}

view.set(color: .white, forKeyPath: \.backgroundColor)  // success!


问:
Date after another date in symfony form
I have a form that contain 2 dates: start date(datedebut) and end date(datefin).
 I want the end date to be always after the start date. How can i do that?

My form type:

```<code>class ReservationType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('datedebut',DateType::class,array(
                'widget' => 'choice',
                'years' => range(date('Y'), date('Y')+20),
            ))
            ->add('datefin',DateType::class,array(
                'widget' => 'choice',
                'years' => range(date('Y'), date('Y')+20),
            ))
            ->add('nbplaces')
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Bridge\TravelBundle\Entity\Reservation'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'Bridge_TravelBundle_Reservation';
    }
}
</code>```

答:
Usually these kind of tasks are solved by adding validation constraints to check if value of one field is greater then the other. Implement callback validation constraint as stated in the documentation: http://symfony.com/doc/current/reference/constraints/Callback.html You can also create your custom class constraint validator and place validation logic there: http://symfony.com/doc/current/validation/custom_constraint.html

This way whenever a user tries to submit value of datefin which is less than selected value of datedebut he will see a validation error and the form will not be processed.

After that you can always add some javascript code that will filter available dates in  datefin field after value in datedebut field is changed.

Also you can use dynamic form modification to render the second date field (and filter its available dates on server side) only if value of the first one is submitted. Check this out: http://symfony.com/doc/current/form/dynamic_form_modification.html

Title: Date after another date in symfony form

Body:
I have a form that contain 2 dates: start date(datedebut) and end date(datefin).
 I want the end date to be always after the start date. How can i do that?

My form type:

class ReservationType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('datedebut',DateType::class,array(
                'widget' => 'choice',
                'years' => range(date('Y'), date('Y')+20),
            ))
            ->add('datefin',DateType::class,array(
                'widget' => 'choice',
                'years' => range(date('Y'), date('Y')+20),
            ))
            ->add('nbplaces')
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Bridge\TravelBundle\Entity\Reservation'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'Bridge_TravelBundle_Reservation';
    }
}


问:
How to run a single deploy when Travis builds succeeds?
I am running Travis CI using matrix of Python versions but I do want to execute the release actions only after all of these are passed, obviously.

How can I do this? It seems that the "deploy" actions are executed for each sub-build.

答:
It is possible by using bash and Travis built-in variables. For a JavaScript / Node repo that would be:

```<code>dist: trusty
language: node_js
node_js:
  - '8'
  - '7'
install: ...
script: ...
after_success:
  - 'if [ "${TRAVIS_NODE_VERSION}" = "8" ]; then cat ./coverage/lcov.info | coveralls ; fi'
  - 'if [ "${TRAVIS_NODE_VERSION}" = "8" ]; then firebase deploy --token $FIREBASE_TOKEN --non-interactive ; fi'
</code>```

Other built-in variables:

TRAVIS_DART_VERSION

TRAVIS_GO_VERSION

TRAVIS_HAXE_VERSION

TRAVIS_JDK_VERSION

TRAVIS_JULIA_VERSION

TRAVIS_NODE_VERSION

TRAVIS_OTP_RELEASE

TRAVIS_PERL_VERSION

TRAVIS_PHP_VERSION

TRAVIS_PYTHON_VERSION

TRAVIS_R_VERSION

TRAVIS_RUBY_VERSION

TRAVIS_RUST_VERSION

TRAVIS_SCALA_VERSION

See https://docs.travis-ci.com/user/environment-variables/

Credits to @airbnb/enzyme which is where I took the idea from.

Body:
It is possible by using bash and Travis built-in variables. For a JavaScript / Node repo that would be:

dist: trusty
language: node_js
node_js:
  - '8'
  - '7'
install: ...
script: ...
after_success:
  - 'if [ "${TRAVIS_NODE_VERSION}" = "8" ]; then cat ./coverage/lcov.info | coveralls ; fi'
  - 'if [ "${TRAVIS_NODE_VERSION}" = "8" ]; then firebase deploy --token $FIREBASE_TOKEN --non-interactive ; fi'

Other built-in variables:

TRAVIS_DART_VERSION

TRAVIS_GO_VERSION

TRAVIS_HAXE_VERSION

TRAVIS_JDK_VERSION

TRAVIS_JULIA_VERSION

TRAVIS_NODE_VERSION

TRAVIS_OTP_RELEASE

TRAVIS_PERL_VERSION

TRAVIS_PHP_VERSION

TRAVIS_PYTHON_VERSION

TRAVIS_R_VERSION

TRAVIS_RUBY_VERSION

TRAVIS_RUST_VERSION

TRAVIS_SCALA_VERSION

See https://docs.travis-ci.com/user/environment-variables/

Credits to @airbnb/enzyme which is where I took the idea from.


问:
Php artisan migrate fails Laravel
I have the following error. Someone is understanding why?

php artisan migrate

```<code> SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key
was too long; max key length is 767 bytes (SQL: alter table `users`
add unique `users_email_unique`(`email`))
</code>```

create_users_table.php

```<code>Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name',255);
    $table->string('email',255)->unique();
    $table->string('password',255);
    $table->rememberToken();
    $table->timestamps();
});
</code>```

答:
Thanks all message

Resolved with next code:

```<code> in config/database.php in mysql section

'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
 and replace them with with

'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
</code>```

Title: Php artisan migrate fails Laravel

Body:
I have the following error. Someone is understanding why?

php artisan migrate

 SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key
was too long; max key length is 767 bytes (SQL: alter table `users`
add unique `users_email_unique`(`email`))

create_users_table.php

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name',255);
    $table->string('email',255)->unique();
    $table->string('password',255);
    $table->rememberToken();
    $table->timestamps();
});

Body:
Thanks all message

Resolved with next code:

 in config/database.php in mysql section

'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
 and replace them with with

'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',


问:
How to include a folder in your exe file using Inno Setup Compiler
I'm currently using Inno Setup Compiler to create an installer for Windows and everything is working fine except when I try to include a folder to the exe. In other words what I want is to be able to include a folder with two files in it,  I want this folder to appear right where the .exe file is (C:\Program Files x86\appFolder) when the program is installed.

Inno has an option to add folders but for some reason when I select the folder with the two files I want, it compiles fine but when I actually install the program it actually adds the two files but not the folder.

I found the following line of code online and I used it but it actually included some folders that I didn't want. The problem I have with this line of code is that I don't fully understand it, I don't know where the folder path should be? What is Exlude: "Setup.iss,generated_images\"

```<code>Source: "*.*"; Excludes: "Setup.iss,generated_images\*"; DestDir: "{app}"; Flags:replacesameversion recursesubdirs
</code>```

Can someone be so kind an explain this line of code?

Thanks

答: while making the setup file Inno SETUP....Click on new folder,click on the url,then click on edit and name the subfolder which you want to include in installation folder.</p>

Body:
I'm currently using Inno Setup Compiler to create an installer for Windows and everything is working fine except when I try to include a folder to the exe. In other words what I want is to be able to include a folder with two files in it,  I want this folder to appear right where the .exe file is (C:\Program Files x86\appFolder) when the program is installed.

Inno has an option to add folders but for some reason when I select the folder with the two files I want, it compiles fine but when I actually install the program it actually adds the two files but not the folder.

I found the following line of code online and I used it but it actually included some folders that I didn't want. The problem I have with this line of code is that I don't fully understand it, I don't know where the folder path should be? What is Exlude: "Setup.iss,generated_images\"

Source: "*.*"; Excludes: "Setup.iss,generated_images\*"; DestDir: "{app}"; Flags:replacesameversion recursesubdirs

Can someone be so kind an explain this line of code?

Thanks


问:
How to confirm if a popover is displayed on mouse over a element and how to get the inside text of the displayed popover using protractor
My protractor code

```<code>var meover = element(by.xpath('/html/body/div[2]/div[1]/div[2]/span[1]/code'));

meover.getText().then(console.log);

browser.actions().mouseMove(meover).perform();

browser.sleep(2000);
</code>```

How to get popover text?? see the images for better understanding

Images

答:
Why do you want to do that with protractor ? You can just create a Directive [popover] or a component to do that
example :

.ts file :

```<code>import {Component, Input} from "@angular/core";

@Component({
    selector: "popover",
    templateUrl: "popover.component.html"
})
export class PopoverComponent {
    @Input() title: string;
    @Input() content: string;
}
</code>```

.html file :

```<code> <ng-content></ng-content>
<div class="popover">
    <div class='header'>{{ title }}</div>
    <div class='content'>{{ content }}</div>
</div>
</code>```

example of css :

```<code>popover {
    position: relative;
    display: inline-block;
}

.popover {
    display: none;
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(50%) translateY(100%);
    width: 300px;
}

popover:hover > .popover {
    display: block;
}
</code>```

I didn't tested it, but it should looks like my example.

To use it, you will write this on a HTML file :

```<code>Hint : place the mouse over <popover [title]="my title" [content]="text displayed on hover">me</popover> !
</code>```

Body:
My protractor code

var meover = element(by.xpath('/html/body/div[2]/div[1]/div[2]/span[1]/code'));

meover.getText().then(console.log);

browser.actions().mouseMove(meover).perform();

browser.sleep(2000);

How to get popover text?? see the images for better understanding

Images

Body:
Why do you want to do that with protractor ? You can just create a Directive [popover] or a component to do that
example :

.ts file :

import {Component, Input} from "@angular/core";

@Component({
    selector: "popover",
    templateUrl: "popover.component.html"
})
export class PopoverComponent {
    @Input() title: string;
    @Input() content: string;
}

.html file :

 <ng-content></ng-content>
<div class="popover">
    <div class='header'>{{ title }}</div>
    <div class='content'>{{ content }}</div>
</div>

example of css :

popover {
    position: relative;
    display: inline-block;
}

.popover {
    display: none;
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(50%) translateY(100%);
    width: 300px;
}

popover:hover > .popover {
    display: block;
}

I didn't tested it, but it should looks like my example.

To use it, you will write this on a HTML file :

Hint : place the mouse over <popover [title]="my title" [content]="text displayed on hover">me</popover> !