问:
Jquery for filtering products
I have this jquery plugin that filter products

 (function($) {

  'use strict';

  var $filters = $('.filter [data-filter]'),
    $boxes = $('.boxes [data-cat]');

  $filters.on('click', function(e) {
    e.preventDefault();
    var $this = $(this);

    $filters.removeClass('active');
    $this.addClass('active');

    var $filterColor = $this.attr('data-filter');

    if ($filterColor == 'all') {
      $boxes.removeClass('is-animated')
        .fadeOut().promise().done(function() {
          $boxes.addClass('is-animated').fadeIn();
        });
    } else {
      $boxes.removeClass('is-animated')
        .fadeOut().promise().done(function() {
          $boxes.filter('[data-cat = "' + $filterColor + '"]')
            .addClass('is-animated').fadeIn();
        });
    }
  });

})(jQuery);```
</div>
</div>
</p>

<p>[data-cat] is the category
but some products belong to more than one category and the filter doesn't work with them. It is working if the category is the only one you click the filter button (if the product has 2 categories, for example, airtickets and ferry tickets clicking in airtickets filter button doest show this product at all) and it won't to show the items contain the airtickets in their category, not only the ones that contain only the airtickets</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="cta filter">
  All
  Airtickets
  Ferry
</div></code>```

答:
(function($) {

  'use strict';

  var $filters = $('.filter [data-filter]'),
    $boxes = $('.boxes [data-cat]');

  $filters.on('click', function(e) {
    e.preventDefault();
    var $this = $(this);

    $filters.removeClass('active');
    $this.addClass('active');

    var $filterColor = $this.attr('data-filter');

    $boxes.each(function(index){
      var curCategories = $(this).data("cat").split(",");
      if( curCategories.indexOf( $filterColor ) === -1 ){
        // match not found
        $(this).removeClass("is-animated").fadeOut();
      }else{
        //match found
        $(this).addClass("is-animated").fadeIn();
      }
    });//each()
  });

})(jQuery);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.boxes div
{
  background: orange;
  border-radius: 50%;
  color: #777;
  float: left;
  height: 80px;
  text-align: center;
  width: 80px;
}</code>```

  All
  Airtickets
  Ferry

Airtickets, all

Airtickets, all

Ferry, all

Airtickets, Ferry, all

all

```

Title: Jquery for filtering products

Body:
I have this jquery plugin that filter products

 (function($) {

  'use strict';

  var $filters = $('.filter [data-filter]'),
    $boxes = $('.boxes [data-cat]');

  $filters.on('click', function(e) {
    e.preventDefault();
    var $this = $(this);

    $filters.removeClass('active');
    $this.addClass('active');

    var $filterColor = $this.attr('data-filter');

    if ($filterColor == 'all') {
      $boxes.removeClass('is-animated')
        .fadeOut().promise().done(function() {
          $boxes.addClass('is-animated').fadeIn();
        });
    } else {
      $boxes.removeClass('is-animated')
        .fadeOut().promise().done(function() {
          $boxes.filter('[data-cat = "' + $filterColor + '"]')
            .addClass('is-animated').fadeIn();
        });
    }
  });

})(jQuery);

[data-cat] is the category
but some products belong to more than one category and the filter doesn't work with them. It is working if the category is the only one you click the filter button (if the product has 2 categories, for example, airtickets and ferry tickets clicking in airtickets filter button doest show this product at all) and it won't to show the items contain the airtickets in their category, not only the ones that contain only the airtickets

  All
  Airtickets
  Ferry

Body:
(function($) {

  'use strict';

  var $filters = $('.filter [data-filter]'),
    $boxes = $('.boxes [data-cat]');

  $filters.on('click', function(e) {
    e.preventDefault();
    var $this = $(this);

    $filters.removeClass('active');
    $this.addClass('active');

    var $filterColor = $this.attr('data-filter');

    $boxes.each(function(index){
      var curCategories = $(this).data("cat").split(",");
      if( curCategories.indexOf( $filterColor ) === -1 ){
        // match not found
        $(this).removeClass("is-animated").fadeOut();
      }else{
        //match found
        $(this).addClass("is-animated").fadeIn();
      }
    });//each()
  });

})(jQuery);

.boxes div
{
  background: orange;
  border-radius: 50%;
  color: #777;
  float: left;
  height: 80px;
  text-align: center;
  width: 80px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="cta filter">
  <a class="blue-btn btn" data-filter="all" href="#" >All</a>
  <a class="blue-btn btn" data-filter="Airtickets" href="#" role="button">Airtickets</a>
  <a class="blue-btn btn" data-filter="Ferry" href="#" role="button">Ferry</a>
</div>

<div class="boxes">
 <div data-cat="Airtickets,all">Airtickets, all</div>
 <div data-cat="Airtickets,all">Airtickets, all</div>
 <div data-cat="Ferry,all">Ferry, all</div>
 <div data-cat="Airtickets,Ferry,all">Airtickets, Ferry, all</div>
 <div data-cat="all">all</div>
</div>


来源: stackexchange

问:
Usage of Variable in MySql LIMIT Clause in Version 5.7.18-log
I am new to MySql but have been working MSSQL for quite some time. I need to implement Pagination in one of the Stored Procedures. I am aware of LIMIT Clause (similar to OFFSET in MSSQL), but I am unable to use a variable in the Clause and getting Query Syntax error. I am using MySql Version '5.7.18-log' and I am aware that variable in LIMIT is available from 5.5.6+. I tried many forums and blogposts; I have also tried the 5.7 documentation for help.
I am aware that there is a workaround for this by using dynamic prepared sql statements.
Is there any direct way of using LIMIT with Variable?
Thanks in advance for the help!

Here is the code, @Nigel Ren

```<code>CREATE PROCEDURE `USP_GetResults`(IN PageNumber INT,IN PageCount INT)
BEGIN
SET @pageOffset := (PageNumber - 1) * PageCount;
SELECT * FROM TableName
ORDER BY ColumnName LIMIT @pageOffset,PageCount;
END
</code>```

答:
I found the answer myself, the type of variable I was using was wrong.
Solved it as shown in code snippet below.
Thanks for looking at the question, downvoting and not even answering. ;)
(I personally feel if you feel its very easy kindly help others by answering it)</p>

```<code>CREATE PROCEDURE `USP_GetResults`(IN PageNumber INT,IN PageCount INT)
BEGIN
DECLARE $PageOffset int;
SET $PageOffset = (PageNumber - 1) * PageCount;

SELECT * FROM TableName
ORDER BY ColumnName LIMIT $PageOffset,PageCount;
END
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to MySql but have been working MSSQL for quite some time. I need to implement Pagination in one of the Stored Procedures. I am aware of LIMIT Clause (similar to OFFSET in MSSQL), but I am unable to use a variable in the Clause and getting Query Syntax error. I am using MySql Version '5.7.18-log' and I am aware that variable in LIMIT is available from 5.5.6+. I tried many forums and blogposts; I have also tried the 5.7 documentation for help.
I am aware that there is a workaround for this by using dynamic prepared sql statements.
Is there any direct way of using LIMIT with Variable?
Thanks in advance for the help!

Here is the code, @Nigel Ren

CREATE PROCEDURE `USP_GetResults`(IN PageNumber INT,IN PageCount INT)
BEGIN
SET @pageOffset := (PageNumber - 1) * PageCount;
SELECT * FROM TableName
ORDER BY ColumnName LIMIT @pageOffset,PageCount;
END

Body:
I found the answer myself, the type of variable I was using was wrong.
Solved it as shown in code snippet below.
Thanks for looking at the question, downvoting and not even answering. ;)
(I personally feel if you feel its very easy kindly help others by answering it)

CREATE PROCEDURE `USP_GetResults`(IN PageNumber INT,IN PageCount INT)
BEGIN
DECLARE $PageOffset int;
SET $PageOffset = (PageNumber - 1) * PageCount;

SELECT * FROM TableName
ORDER BY ColumnName LIMIT $PageOffset,PageCount;
END


问:
i want to add checkbox in table view which grows dynamically and perform operations in javafx
Actually i want to add checkbox to this table view which grows dynamically and with the help of a check box i want to delete the data from the database. How to add checkbox in this dynamic table.
Thank you in advance</p>

```<code>public class CheckEngineDetailMain extends Application{

//TABLE VIEW AND DATA
private ObservableList<ObservableList> data;
private TableView tableview;
//MAIN EXECUTOR
public static void main(String[] args) {
    launch(args);

}

//CONNECTION DATABASE
public void buildData(){

    Connection c ;
      data = FXCollections.observableArrayList();
      try{
        c = DBConnect.connect();

        //SQL FOR SELECTING ALL OF CUSTOMER

        String SQL = "SELECT * from Engine_Detail_test;" ;

        //ResultSet
        ResultSet rs = c.createStatement().executeQuery(SQL);

        /**********************************
         * TABLE COLUMN ADDED DYNAMICALLY *
         **********************************/
        for(int i=0 ; i<rs.getMetaData().getColumnCount(); i++){
            //We are using non property style for making dynamic table
            final int j = i;
            TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i+1));
            col.setCellValueFactory(new Callback<CellDataFeatures<ObservableList,String>,ObservableValue<String>>(){
                public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) {
                    return new SimpleStringProperty(param.getValue().get(j).toString());
                }
            });

            tableview.getColumns().addAll(col);

            System.out.println("Column ["+i+"] ");
        }

        while(rs.next()){
            //Iterate Row
            ObservableList<String> row = FXCollections.observableArrayList();

            for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++){
                //Iterate Column
                //row.add(1, new CheckBox());
                row.add(rs.getString(i));
            }
            System.out.println("Row [1] added "+row );
            data.add(row);

        }

        //FINALLY ADDED TO TableView
        tableview.setItems(data);
      }catch(Exception e){
          e.printStackTrace();
          System.out.println("Error on Building Data");
      }
  }

  @Override
  public void start(Stage stage) throws Exception {
    //TableView

    tableview = new TableView();
    buildData();

    //Main Scene
    Scene scene = new Scene(tableview);

    stage.setScene(scene);
    stage.show();
  }

}
</code>```

答:
first of all, it is quite bad idea to mix all things, like the main class with the controller, and not using .fxml file(s) is also a bad practice, but, the solution your problem is that you have to set a cellFactory to your column that you want to be the "mark for delete" or "delete" column.
So for example this way after the for loop:

```<code>TableColumn col = new TableColumn("column header name you want");
col.setCellFactory(factory -> new CheckBoxTableCell());
col.setCellValueFactory(v -> {
        BooleanProperty property = new SimpleBooleanProperty();
        property.addListener((observable, oldValue, newValue) -> {
            if (newValue) {
                tableView.getItems().remove(((TableColumn.CellDataFeatures)v).getValue());
            }
        });
    return property;
});
tableView.getColumns().add(col);
</code>```

Then you have to make the tableView editable this way : tableView.setEditable(true);. This makes the whole table editable, if you want to be editable just the last column you can simply put in your for loop
        col.setEditable(false);

P.S. also a bad practice not using a separate model class for holding the rows' data, and another bad practice not using generics for example at TableView<here you should put the type of your model>

Body:
Actually i want to add checkbox to this table view which grows dynamically and with the help of a check box i want to delete the data from the database. How to add checkbox in this dynamic table.
Thank you in advance

public class CheckEngineDetailMain extends Application{

//TABLE VIEW AND DATA
private ObservableList<ObservableList> data;
private TableView tableview;
//MAIN EXECUTOR
public static void main(String[] args) {
    launch(args);

}

//CONNECTION DATABASE
public void buildData(){

    Connection c ;
      data = FXCollections.observableArrayList();
      try{
        c = DBConnect.connect();

        //SQL FOR SELECTING ALL OF CUSTOMER

        String SQL = "SELECT * from Engine_Detail_test;" ;

        //ResultSet
        ResultSet rs = c.createStatement().executeQuery(SQL);

        /**********************************
         * TABLE COLUMN ADDED DYNAMICALLY *
         **********************************/
        for(int i=0 ; i<rs.getMetaData().getColumnCount(); i++){
            //We are using non property style for making dynamic table
            final int j = i;
            TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i+1));
            col.setCellValueFactory(new Callback<CellDataFeatures<ObservableList,String>,ObservableValue<String>>(){
                public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) {
                    return new SimpleStringProperty(param.getValue().get(j).toString());
                }
            });

            tableview.getColumns().addAll(col);

            System.out.println("Column ["+i+"] ");
        }

        while(rs.next()){
            //Iterate Row
            ObservableList<String> row = FXCollections.observableArrayList();

            for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++){
                //Iterate Column
                //row.add(1, new CheckBox());
                row.add(rs.getString(i));
            }
            System.out.println("Row [1] added "+row );
            data.add(row);

        }

        //FINALLY ADDED TO TableView
        tableview.setItems(data);
      }catch(Exception e){
          e.printStackTrace();
          System.out.println("Error on Building Data");
      }
  }

  @Override
  public void start(Stage stage) throws Exception {
    //TableView

    tableview = new TableView();
    buildData();

    //Main Scene
    Scene scene = new Scene(tableview);

    stage.setScene(scene);
    stage.show();
  }

}

Body:
first of all, it is quite bad idea to mix all things, like the main class with the controller, and not using .fxml file(s) is also a bad practice, but, the solution your problem is that you have to set a cellFactory to your column that you want to be the "mark for delete" or "delete" column.
So for example this way after the for loop:

TableColumn col = new TableColumn("column header name you want");
col.setCellFactory(factory -> new CheckBoxTableCell());
col.setCellValueFactory(v -> {
        BooleanProperty property = new SimpleBooleanProperty();
        property.addListener((observable, oldValue, newValue) -> {
            if (newValue) {
                tableView.getItems().remove(((TableColumn.CellDataFeatures)v).getValue());
            }
        });
    return property;
});
tableView.getColumns().add(col);

Then you have to make the tableView editable this way : tableView.setEditable(true);. This makes the whole table editable, if you want to be editable just the last column you can simply put in your for loop
        col.setEditable(false);

P.S. also a bad practice not using a separate model class for holding the rows' data, and another bad practice not using generics for example at TableView<here you should put the type of your model>


问:
Powershell: Getting users for whom retention policy has been enabled based on content type
Is there a way to get the list of users for which retention policy has been enabled based on the content type i.e: Email, Skype for Business, Onedrive and et al.?  There are these commands to see the policy and rule but I could not find anyway to get the content and the list of users for which retention policy has been enabled.

Get-RetentionComplianceRule

Get-RetentionCompliancePolicy

Basically, I want a way to retrieve the users for Skype for Business in enclosed on red section in the image above.

答:
Try this:
Get-RetentionCompliancePolicy -identity "SfB_Retention" -distributiondetail | Select-Object SkypeLocation


问:
Using Jquery to add comma's on textbox
I'm trying to put a comma on a textbox that should only accept numbers. What I did is instead of using type="numbers", I limited the textbox to only accept number keyCodes.

```<code>    $('#salary').keydown(function (e) {
        var keyCode = e.which;
        if (keyCode != 8 && keyCode != 9 && keyCode != 13 && keyCode != 37 && keyCode != 38 && keyCode != 39 && keyCode != 40 && keyCode != 46 && keyCode != 110 && keyCode != 190) {
            if (keyCode < 48) {
                e.preventDefault();
            } else if (keyCode > 57 && keyCode < 96) {
                e.preventDefault();
            } else if (keyCode > 105) {
                e.preventDefault();
            }
        }
    });
</code>```

What I want is that after the input is edited(out of focus), the textbox automatically shows commas similar to this value:

```<code>1,000,000.00
</code>```

I am clueless on what to do or use to add comma's on the textbox.

Title: Using Jquery to add comma's on textbox

Body:
I'm trying to put a comma on a textbox that should only accept numbers. What I did is instead of using type="numbers", I limited the textbox to only accept number keyCodes.

    $('#salary').keydown(function (e) {
        var keyCode = e.which;
        if (keyCode != 8 && keyCode != 9 && keyCode != 13 && keyCode != 37 && keyCode != 38 && keyCode != 39 && keyCode != 40 && keyCode != 46 && keyCode != 110 && keyCode != 190) {
            if (keyCode < 48) {
                e.preventDefault();
            } else if (keyCode > 57 && keyCode < 96) {
                e.preventDefault();
            } else if (keyCode > 105) {
                e.preventDefault();
            }
        }
    });

What I want is that after the input is edited(out of focus), the textbox automatically shows commas similar to this value:

1,000,000.00

I am clueless on what to do or use to add comma's on the textbox.

Body:
$( "#salary" ).blur(function() {
   $( "#salary" ).val( parseFloat($( "#salary" ).val(), 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());
});


答:
Alexander's solution didn't work. There is a small error. The code should be:</p>

```<code>d = {n: df2.iloc[rows]
 for n, rows in df2.groupby('group_no').groups.items()}
</code>```

Title: Splitting a dataframe based on column values

Body:
I have a dataframe like such

 EndDate
2007-10-31              0
2007-11-30    -0.03384464
2007-12-31     -0.0336299
2008-01-31   -0.009448923
2008-02-29              0
2008-03-31    -0.05744962
2008-04-30     -0.0386942
2008-05-31              0
2008-06-30    -0.03624518
2008-07-31   -0.005286455
2008-08-31              0
2008-09-30     -0.1619864
2008-10-31     -0.2862122
2008-11-30     -0.2942793
2008-12-31     -0.2913253

Now I want to split the dataframe after every occurance of 0.
thus new dataframes should look like:

Dataframe 1:
    2007-11-30    -0.03384464
    2007-12-31     -0.0336299
    2008-01-31   -0.009448923
    2008-02-29              0

Dataframe 2:
    2008-03-31    -0.05744962
    2008-04-30     -0.0386942
    2008-05-31              0

Dataframe 3:
    2008-06-30    -0.03624518
    2008-07-31   -0.005286455
    2008-08-31              0

Dataframe 4:
    2008-09-30     -0.1619864
    2008-10-31     -0.2862122
    2008-11-30     -0.2942793
    2008-12-31     -0.2913253

I am not sure how that can be done.
I can iterate over every row looking for 0 but i think there should be a better way.

Body:
Alexander's solution didn't work. There is a small error. The code should be:

d = {n: df2.iloc[rows]
 for n, rows in df2.groupby('group_no').groups.items()}


问:
jquery dialog save cancel button styling
I am using jquery ui dialogs in my application.
How do I style the "Save" and "Cancel" buttons differently in a jquery dialog?
So "Save" is more appealing than the "Cancel".
I could use a hyper link for "Cancel", but how do I place that in the same button panel?</p>

答:
These solutions are all very well if you only have one dialog in the page at any one time, however if you want to style multiple dialogs at once then try:

```<code>$("#element").dialog({
    buttons: {
        'Save': function() {},
        'Cancel': function() {}
    }
})
.dialog("widget")
.find(".ui-dialog-buttonpane button")
.eq(0).addClass("btnSave").end()
.eq(1).addClass("btnCancel").end();
</code>```

Instead of globally selecting buttons, this gets the widget object and finds it's button pane, then individually styles each button. This saves lot's of pain when you have several dialogs on one page

ContentLicense: CC BY-SA 2.5

Body:
These solutions are all very well if you only have one dialog in the page at any one time, however if you want to style multiple dialogs at once then try:

$("#element").dialog({
    buttons: {
        'Save': function() {},
        'Cancel': function() {}
    }
})
.dialog("widget")
.find(".ui-dialog-buttonpane button")
.eq(0).addClass("btnSave").end()
.eq(1).addClass("btnCancel").end();

Instead of globally selecting buttons, this gets the widget object and finds it's button pane, then individually styles each button. This saves lot's of pain when you have several dialogs on one page


问:
PHP: MYSQLI Change Order By Style

Hi, i want to get data from chat table like this:

```<code>6
7
8
</code>```

My Code show like this:

```<code>8
7
6
</code>```

Code:

```<code>"SELECT * FROM `chat` WHERE
    `chat-code` = 'vm1mxo3dpi9gzuo' AND (`user_1` = '1' OR `user_2` = '1')
     ORDER BY id DESC LIMIT 3"
</code>```

答:
use this mat and you can change the between parameters with prepared statements.comment if doesn't work.   </p>

```<code>"SELECT * FROM `chat` WHERE `chat-code` = 'vm1mxo3dpi9gzuo'
AND (`user_1`='1' OR `user_2` = '1')
AND `id` between 6 and 10  //starting and ending offset for query so query doesn't take long time
ORDER BY id ASC LIMIT 3" // LIMIT 3 as you mentioned and ASC order
</code>```

Title: PHP: MYSQLI Change Order By Style

Body:
Hi, i want to get data from chat table like this:

6
7
8

My Code show like this:

8
7
6

Code:

"SELECT * FROM `chat` WHERE
    `chat-code` = 'vm1mxo3dpi9gzuo' AND (`user_1` = '1' OR `user_2` = '1')
     ORDER BY id DESC LIMIT 3"

Body:
use this mat and you can change the between parameters with prepared statements.comment if doesn't work.

"SELECT * FROM `chat` WHERE `chat-code` = 'vm1mxo3dpi9gzuo'
AND (`user_1`='1' OR `user_2` = '1')
AND `id` between 6 and 10  //starting and ending offset for query so query doesn't take long time
ORDER BY id ASC LIMIT 3" // LIMIT 3 as you mentioned and ASC order


问:
Django Media not showing with Debug False
I'm a beginner at Python, my settings.py:

```<code>STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'theme', 'static'),
]
</code>```

If I turn DEBUG to False，the staticfiles and mediafiles don't work, when i run devserver in insecure mode:

```<code>python manage.py runserver --insecure
</code>```

The staticfiles works，but mediafiles(avatars) still doens't work.

my app installed way:

pip install misago

start path:
/home/project/

Can someone help me?
thanks.

答:
Django with debug false, does not manage the statics and media files.

You need to:

Add "statics root" and "media root" to your django settings.py file

Use NGINX to manage statics file (see more info about deployment on django documentation)

use "collect static" command to collect the static/media file

Body:
I'm a beginner at Python, my settings.py:

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'theme', 'static'),
]

If I turn DEBUG to False，the staticfiles and mediafiles don't work, when i run devserver in insecure mode:

python manage.py runserver --insecure

The staticfiles works，but mediafiles(avatars) still doens't work.

my app installed way:

pip install misago

start path:
/home/project/

Can someone help me?
thanks.


问:
Difference between Card lock and Global lock privilege in Global Platform
What is the core difference between card lock and Global lock privilege in Global Platform? If not, then why we need two privileges?

Can an application with Global lock privilege lock card as well?

Any help would be appreciated.

Thank You!

答:
The first difference to understand is the difference between the Card Life Cycle States and Application and Security Domain Life Cycle.

The Card Lock Privilege is used to change the Card life Cycle to Locked state and either the OPEN, or a Security Domain with Card Lock privilege, or an Application with Card Lock
privilege , may initiate the transition from the state SECURED to the state
CARD_LOCKED.

and

A Security Domain or Application with Global Lock privilege is only able to change the life cycle of the SD and Application (independent of its Security Domain association and hierarchy) not the Card Life Cycle from the following states to locked
INSTALLED
SELECTABLE
PERSONALIZED

Regards


问:
Android Share data between two Fragment
I am new developer of Android.How we can share the data between two fragment.
Any idea for this problem.i have make the orderFragment and itemfragment user select the item on item screen and press submit the screen redirct to orders screen user have multiple order.if we redirect the screen the data not send to the orders screen</p>

答:
Its simple to send data between fragments try this

```<code>Bundle bundle = new Bundle();
bundle.putString("YourKeyHere",value);
itemFragment.setArguments(bundle);
</code>```

And then in order Fragment receive as

```<code>@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

          String item = getArguments().getString("YourKeyHere");
    return inflater.inflate(R.layout.fragment, container, false);
    }
</code>```

Title: Android Share data between two Fragment

Body:
Its simple to send data between fragments try this

Bundle bundle = new Bundle();
bundle.putString("YourKeyHere",value);
itemFragment.setArguments(bundle);

And then in order Fragment receive as

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

          String item = getArguments().getString("YourKeyHere");
    return inflater.inflate(R.layout.fragment, container, false);
    }


问:
Can't launch AVD on macOS 10.13
I created some AVDs in Android studio 3.0, but I can't launch them. I used the following command to launch them:

```<code>./emulator @Nexus_5X_API_17
</code>```

logs:

```<code>emulator: WARNING: encryption is off
Hax is enabled
Hax ram_size 0x60000000
Failed to open vm 3
Failed to create HAX VM
No accelerator found.
failed to initialize HAX: Invalid argument
</code>```

And when I reinstalled "Intel x86 Emulator Accelerator(HAXM installer)", the logs:

```<code>HAXM silent installation only supports macOS from 10.8 to 10.12 !
</code>```

I don't know if it is related with this.

After that, I tried to install virtualBox to install genymotion, but I found when I clicks the virturalBox.dmg, the installer crashed.

Could you help me? thanks.

答:
Use the new Hypervisor.Framework support instead of HAXM on macOS, as described in the comments of the issue filed for this:

Try running the emulator on Canary channel 26.1.x (API 25/26
  recommended) with Hypervisor.Framework; put the text "HVF = on" in
  ~/.android/advancedFeatures.ini (create this file if it doesn't exist
  already).

Title: Can't launch AVD on macOS 10.13

Body:
I created some AVDs in Android studio 3.0, but I can't launch them. I used the following command to launch them:

./emulator @Nexus_5X_API_17

logs:

emulator: WARNING: encryption is off
Hax is enabled
Hax ram_size 0x60000000
Failed to open vm 3
Failed to create HAX VM
No accelerator found.
failed to initialize HAX: Invalid argument

And when I reinstalled "Intel x86 Emulator Accelerator(HAXM installer)", the logs:

HAXM silent installation only supports macOS from 10.8 to 10.12 !

I don't know if it is related with this.

After that, I tried to install virtualBox to install genymotion, but I found when I clicks the virturalBox.dmg, the installer crashed.

Could you help me? thanks.


问:
Select values from multiple dictionaries into list of objects with LINQ
I want to select OrderId & Row from multiple dictionaries and create a list of Orders which contains a list of Rows.

The code I'm struggling with this far is:

```<code>var listOfDictionaries = new List<Dictionary<string, string>>();

var dict1 = new Dictionary<string, string>();
dict1.Add("OrderId", "12345");
dict1.Add("Row", "1");
listOfDictionaries.Add(dict1);

var dict2 = new Dictionary<string, string>();
dict2.Add("OrderId", "97845");
dict2.Add("Row", "10");
listOfDictionaries.Add(dict2);

var dict3 = new Dictionary<string, string>();
dict3.Add("OrderId", "12345");
dict3.Add("Row", "2");
listOfDictionaries.Add(dict3);

var grouped = listOfDictionaries.SelectMany(d =>
                 d.Where(kvp =>
                    kvp.Key.ToLower().Contains("orderid") || kvp.Key.ToLower().Contains("row")))
              .GroupBy(a => a.Key).ToList();

public class Order
{
    public Order()
    {
       OrderRows = new List<OrderRow>();
    }

    public string OrderId { get; set; }
    public List<OrderRow> OrderRows { get; set; }
}

public class OrderRow
{
    public string OrderRowId { get; set; }
}
</code>```

Anyone have a good idea how to solve this?

答:
You need to do</p>

```<code>var result = listOfDictionaries.Select(x => new { OrderId = x["OrderId"], Row = x["Row"] })
                   .GroupBy(x => x.OrderId)
                   .Select(x => new { OrderId = x.Key, Values = x.Select(y => y.Row) });
</code>```

Body:
I want to select OrderId & Row from multiple dictionaries and create a list of Orders which contains a list of Rows.

The code I'm struggling with this far is:

var listOfDictionaries = new List<Dictionary<string, string>>();

var dict1 = new Dictionary<string, string>();
dict1.Add("OrderId", "12345");
dict1.Add("Row", "1");
listOfDictionaries.Add(dict1);

var dict2 = new Dictionary<string, string>();
dict2.Add("OrderId", "97845");
dict2.Add("Row", "10");
listOfDictionaries.Add(dict2);

var dict3 = new Dictionary<string, string>();
dict3.Add("OrderId", "12345");
dict3.Add("Row", "2");
listOfDictionaries.Add(dict3);

var grouped = listOfDictionaries.SelectMany(d =>
                 d.Where(kvp =>
                    kvp.Key.ToLower().Contains("orderid") || kvp.Key.ToLower().Contains("row")))
              .GroupBy(a => a.Key).ToList();

public class Order
{
    public Order()
    {
       OrderRows = new List<OrderRow>();
    }

    public string OrderId { get; set; }
    public List<OrderRow> OrderRows { get; set; }
}

public class OrderRow
{
    public string OrderRowId { get; set; }
}

Anyone have a good idea how to solve this?

Body:
You need to do

var result = listOfDictionaries.Select(x => new { OrderId = x["OrderId"], Row = x["Row"] })
                   .GroupBy(x => x.OrderId)
                   .Select(x => new { OrderId = x.Key, Values = x.Select(y => y.Row) });


问:
Docker - ERROR: failed to register layer: symlink
I'm running a docker-compose file we have, I usually run it with command:

```<code>docker-compose up
</code>```

But today I'm getting this error.

```<code>ERROR: failed to register layer: symlink ../bdf441e8145a625c4ab289f13ac2274b37d35475b97680f50b7eccda4328f973/diff /var/lib/docker/overlay2/l/7O5XKRTJV6RMTXBV5DTPDOHYNX: no such file or directory
</code>```

答:
Followed this answer just restarting docker fixed the problem.

https://stackoverflow.com/a/35325477/4031815

Body:
I'm running a docker-compose file we have, I usually run it with command:

docker-compose up

But today I'm getting this error.

ERROR: failed to register layer: symlink ../bdf441e8145a625c4ab289f13ac2274b37d35475b97680f50b7eccda4328f973/diff /var/lib/docker/overlay2/l/7O5XKRTJV6RMTXBV5DTPDOHYNX: no such file or directory


问:
AngularJS: ng-show vs display:none
I had a use case whereby I have to keep an HTML element hidden by default using CSS as follows:

HTML:

```<code><div class="item">
</div>
</code>```

CSS:

```<code>.item {
    display: none;
}
</code>```

But, I need to toggle the element's visibility using ng-show after the page has loaded as follows:

```<code><div class="item" ng-show="show_element">
</div>
</code>```

But, even if $scope.show_element is set to true, the element doesn't become visible, that is, the css property is overriding AngularJS' ng-show. Is there any way to give ng-show more priority?

Also, you may think I can keep $scope.show_element as false initially to hide it. But in that case, I get a very short glimpse of the element when the page is loading which is not good from the UX point of view.

答:
Another simple alternative

```<code>style="{{show_element?'display:block !important':'display:none !important'}}"
</code>```

Title: AngularJS: ng-show vs display:none

Body:
I had a use case whereby I have to keep an HTML element hidden by default using CSS as follows:

HTML:

CSS:

.item {
    display: none;
}

But, I need to toggle the element's visibility using ng-show after the page has loaded as follows:

But, even if $scope.show_element is set to true, the element doesn't become visible, that is, the css property is overriding AngularJS' ng-show. Is there any way to give ng-show more priority?

Also, you may think I can keep $scope.show_element as false initially to hide it. But in that case, I get a very short glimpse of the element when the page is loading which is not good from the UX point of view.

Body:
Another simple alternative

style="{{show_element?'display:block !important':'display:none !important'}}"


问:
Android Java - have button change tab
I recently started coding and have been following tutorials. I'm trying to learn how to use a tab activity right now and followed a tutorial to do it by swiping pages. Here's what I've come up with

```<code>public class MainActivity extends FragmentActivity {

ViewPager pager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn1 = (Button) findViewById(R.id.btn1);
    Button btn2 = (Button) findViewById(R.id.btn2);
    pager = (ViewPager) findViewById(R.id.viewPager);

    pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}

public void onClickBtn1(View v) {
    //when clicked, take to Main2Activity.java
}

public void onClickBtn2(View v) {
    //when clicked, take to Main3Activity.java

}

private class MyPagerAdapter extends FragmentPagerAdapter {

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int pos) {
        switch(pos) {

            case 0: return Main2Activity.newInstance("FirstFragment, Instance 1");
            case 1: return Main3Activity.newInstance("SecondFragment, Instance 1");
            case 2: return Main4Activity.newInstance("ThirdFragment, Instance 1");
            default: return Main4Activity.newInstance("ThirdFragment, Default");
        }
    }

    @Override
    public int getCount() {
        return 3;
    }
}
}
</code>```

Can someone please explain to me what's going on in the MyPageAdapter class please?

Also, is it possible that instead of swiping pages that I use a button? For instance, onClickBtn1 will take me to Main2Activity and onClickBtn2 will take me to Main3Activity. I'd like to continue using the tabs instead of creating a new intent.

Thanks in advance!

答:
Your MyPageAdapter will have as many childs as of your tabs.
For example if you select 1st tab ie position will be 0.
Now in below code new instance of fragment is created for pos 0(First Fragment).

public Fragment getItem(int pos) {
        switch(pos) {

```<code>        case 0: return Main2Activity.newInstance("FirstFragment, Instance 1");
        case 1: return Main3Activity.newInstance("SecondFragment, Instance 1");
        case 2: return Main4Activity.newInstance("ThirdFragment, Instance 1");
        default: return Main4Activity.newInstance("ThirdFragment, Default");
    }
}
</code>```

Switching the tabs on button click is not a cool idea as per user experience.You are using view pager which will help swiping the tabs easily.Execute the code & you will get to know more about the functionality of the code.

Title: Android Java - have button change tab

Body:
I recently started coding and have been following tutorials. I'm trying to learn how to use a tab activity right now and followed a tutorial to do it by swiping pages. Here's what I've come up with

public class MainActivity extends FragmentActivity {

ViewPager pager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn1 = (Button) findViewById(R.id.btn1);
    Button btn2 = (Button) findViewById(R.id.btn2);
    pager = (ViewPager) findViewById(R.id.viewPager);

    pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}

public void onClickBtn1(View v) {
    //when clicked, take to Main2Activity.java
}

public void onClickBtn2(View v) {
    //when clicked, take to Main3Activity.java

}

private class MyPagerAdapter extends FragmentPagerAdapter {

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int pos) {
        switch(pos) {

            case 0: return Main2Activity.newInstance("FirstFragment, Instance 1");
            case 1: return Main3Activity.newInstance("SecondFragment, Instance 1");
            case 2: return Main4Activity.newInstance("ThirdFragment, Instance 1");
            default: return Main4Activity.newInstance("ThirdFragment, Default");
        }
    }

    @Override
    public int getCount() {
        return 3;
    }
}
}

Can someone please explain to me what's going on in the MyPageAdapter class please?

Also, is it possible that instead of swiping pages that I use a button? For instance, onClickBtn1 will take me to Main2Activity and onClickBtn2 will take me to Main3Activity. I'd like to continue using the tabs instead of creating a new intent.

Thanks in advance!

Body:
Your MyPageAdapter will have as many childs as of your tabs.
For example if you select 1st tab ie position will be 0.
Now in below code new instance of fragment is created for pos 0(First Fragment).

public Fragment getItem(int pos) {
        switch(pos) {

        case 0: return Main2Activity.newInstance("FirstFragment, Instance 1");
        case 1: return Main3Activity.newInstance("SecondFragment, Instance 1");
        case 2: return Main4Activity.newInstance("ThirdFragment, Instance 1");
        default: return Main4Activity.newInstance("ThirdFragment, Default");
    }
}

Switching the tabs on button click is not a cool idea as per user experience.You are using view pager which will help swiping the tabs easily.Execute the code & you will get to know more about the functionality of the code.


问:
ERROR ITMS-90685: "CFBundleIdentifier Collision. There is more than one bundle"
When I am try to submit my app to app store, I am getting the error:

ERROR ITMS-90685: "CFBundleIdentifier Collision. There is more than
  one bundle with the CFBundleIdentifier value
  com.companyname.projectName under the application ProjectName.app"

Can any one help me?

答:
Steps without script:

Open the (Your App).xcodeproj file (this is the first file on the project navigator pane).

Switch to the target for your app extension (on the top left of the middle pane).

Go to the Build Phases tab

Click the X after "Embed Pod Frameworks"


问:
QML TextArea baseline
how can i remove the line which appears under a text area in qml? is it even possible? because groove music has such a thing without a line! what is that?
if not what other component should i use instead?

thanks in advance

```<code>TextArea{
            id:search
            placeholderText: qsTr("Search")
            x:7
            width: parent.width - 25
            onFocusChanged: border.color= "gray"

        }
</code>```

(as in groove music search box or telegram which has no line and only a place holder text)

Screenshot:

答:
That looks like the Material style. You can disable the line by setting the background to null:

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480

    TextArea {
        placeholderText: qsTr("Search")
        focus: true
        background: null
        anchors.centerIn: parent
    }
}
</code>```

Title: QML TextArea baseline

Body:
how can i remove the line which appears under a text area in qml? is it even possible? because groove music has such a thing without a line! what is that?
if not what other component should i use instead?

thanks in advance

TextArea{
            id:search
            placeholderText: qsTr("Search")
            x:7
            width: parent.width - 25
            onFocusChanged: border.color= "gray"

        }

(as in groove music search box or telegram which has no line and only a place holder text)

Screenshot:

Body:
That looks like the Material style. You can disable the line by setting the background to null:

import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480

    TextArea {
        placeholderText: qsTr("Search")
        focus: true
        background: null
        anchors.centerIn: parent
    }
}


问:
missing Builds in iTunesConnect
I have uploaded two new versions as I always do. But the areas with the versions are empty.

Can anybody help?

missing Builds

答:
1st id confirm the browser your on, I seem to get on better with Chrome on iTC.

Processing time can cause them to not appear either, some times it takes a little while to populate.

Let me know how you get on

Title: missing Builds in iTunesConnect


问:
in one class run many class, PHP OOP
i have class "User_registration" and in this class i need use many class: "Location", "Links", "Mail", "Module".

i create include all class in file:
include 'class/location.php';
include 'class/links.php';
include 'class/mail.php';
include 'class/modules.php';

Now create "User_registration" class.

```<code><?php
class User_registration{

    public function insert_to_db($name, $country_code, $home_page)
    {
        //work with data

        return id;
    }

    public function show_info($id)
    {
        //work with data
    }

}

$reg_u = new User_registration;
$res = $reg_u->insert_to_db($name, $country_code, $home_page);

if($res){
    $reg_u->show_info($res);
}
?>
</code>```

I need in method "insert_to_db" run class: "Location", "Links", "Mail" methods
and in "show_info" run some methods of "Location", "Links", "Module" class.

How? How in one class run another class (no't one)

Thanks for help ;)

答:
There are a few ways to do this.  If you have only a couple objects that another class needs to utilize, use dependency injection; Pass each object as an argument into a class's constructor and store those objects as a class property.

If only a single method needs the object, pass the object as an argument of the method. I discourage this approach though, because I feel it hinders expandability/code-cleanliness in the long run.

If you have many objects that are needed in several classes, I recommend a registry that you inject into a class's constructor.  The registry is a singleton (it holds a single instance of each object you need to share). In the class that needs to utilize a shared object, you might call $this->registry->get('Some_Shared_Object')->doSomething().

Dependency Injection (at the constructor)

```<code>class Foo {
    protected $dependency1;
    protected $dependency2;
    protected $dependency3;

    public function __construct($dependency1, $dependency2, $dependency3) {
        $this->dependency1 = $dependency1;
        $this->dependency2 = $dependency2;
        $this->dependency3 = $dependency3;
    }

    public function foo() {
        $this->dependency1->doSomething();
    }
}

$foo = new Foo($dependency1, $dependency2, $dependency3);
$foo->foo();</code>```

Dependency Injection (at the method, not recommended)

```<code>class Foo {
    public function foo($dependency1) {
        $dependency1->doSomething();
    }
}

$foo = new Foo();
$foo->foo($dependency1);</code>```

Dependency Injection using a Registry

```<code>class Registry {
    var $data = array();

    function __get($key) {
        return $this->get($key);
    }

    function __set($key, $value) {
        $this->set($key, $value);
    }

    /**
    * Retrieve a resource from the registry.
    *
    * @param string
    * @return mixed|null
    */
    function get($key) {
        return isset($this->data[$key]) ? $this->data[$key] : NULL;
    }

    /**
    * Store a resource in the registry.
    *
    * @param string
    * @param mixed
    */
    function set($key, &$value) {
        $this->data[$key] = $value;
    }

    /**
    * Check if a resource exists in the registry.
    *
    * @param string
    * @return boolean
    */
    function has($key) {
        return isset($this->data[$key]);
    }
}

class Foo {
    protected $registry;

    public function __construct($registry) {
        $this->registry = $registry;
    }

    public function foo() {
        $this->registry->dependency1->doSomething();
    }
}

$dependency1 = new Dependency1();
$registry = new Registry();
$registry->set('dependency1', $dependency1);

$foo = new Foo($registry);
$foo->foo();</code>```

Title: in one class run many class, PHP OOP

Body:
i have class "User_registration" and in this class i need use many class: "Location", "Links", "Mail", "Module".

i create include all class in file:
include 'class/location.php';
include 'class/links.php';
include 'class/mail.php';
include 'class/modules.php';

Now create "User_registration" class.

<?php
class User_registration{

    public function insert_to_db($name, $country_code, $home_page)
    {
        //work with data

        return id;
    }

    public function show_info($id)
    {
        //work with data
    }

}

$reg_u = new User_registration;
$res = $reg_u->insert_to_db($name, $country_code, $home_page);

if($res){
    $reg_u->show_info($res);
}
?>

I need in method "insert_to_db" run class: "Location", "Links", "Mail" methods
and in "show_info" run some methods of "Location", "Links", "Module" class.

How? How in one class run another class (no't one)

Thanks for help ;)

Body:
There are a few ways to do this.  If you have only a couple objects that another class needs to utilize, use dependency injection; Pass each object as an argument into a class's constructor and store those objects as a class property.

If only a single method needs the object, pass the object as an argument of the method. I discourage this approach though, because I feel it hinders expandability/code-cleanliness in the long run.

If you have many objects that are needed in several classes, I recommend a registry that you inject into a class's constructor.  The registry is a singleton (it holds a single instance of each object you need to share). In the class that needs to utilize a shared object, you might call $this->registry->get('Some_Shared_Object')->doSomething().

Dependency Injection (at the constructor)

class Foo {
    protected $dependency1;
    protected $dependency2;
    protected $dependency3;

    public function __construct($dependency1, $dependency2, $dependency3) {
        $this->dependency1 = $dependency1;
        $this->dependency2 = $dependency2;
        $this->dependency3 = $dependency3;
    }

    public function foo() {
        $this->dependency1->doSomething();
    }
}

$foo = new Foo($dependency1, $dependency2, $dependency3);
$foo->foo();

Dependency Injection (at the method, not recommended)

class Foo {
    public function foo($dependency1) {
        $dependency1->doSomething();
    }
}

$foo = new Foo();
$foo->foo($dependency1);

Dependency Injection using a Registry

class Registry {
    var $data = array();

    function __get($key) {
        return $this->get($key);
    }

    function __set($key, $value) {
        $this->set($key, $value);
    }

    /**
    * Retrieve a resource from the registry.
    *
    * @param string
    * @return mixed|null
    */
    function get($key) {
        return isset($this->data[$key]) ? $this->data[$key] : NULL;
    }

    /**
    * Store a resource in the registry.
    *
    * @param string
    * @param mixed
    */
    function set($key, &$value) {
        $this->data[$key] = $value;
    }

    /**
    * Check if a resource exists in the registry.
    *
    * @param string
    * @return boolean
    */
    function has($key) {
        return isset($this->data[$key]);
    }
}

class Foo {
    protected $registry;

    public function __construct($registry) {
        $this->registry = $registry;
    }

    public function foo() {
        $this->registry->dependency1->doSomething();
    }
}

$dependency1 = new Dependency1();
$registry = new Registry();
$registry->set('dependency1', $dependency1);

$foo = new Foo($registry);
$foo->foo();


问:
What is Asset, and key-value pair in Asset in Hyperledger fabric?
What is asset and how and where the value of asset is defined, what is key-value pair in Asset ?</p>

答:
You can find the asset definition here : Readthedocs Assets

Fabric Composer let you define asset easily : Hyperledger Composer Modeling Language


问:
compilation fails for nested boost::variant of fusion pairs
Following code fails to compile on gcc 4.9.2 with boost 1.64:

```<code>#include <boost/fusion/support/pair.hpp>
#include <boost/mpl/int.hpp>
#include <boost/variant.hpp>

#include <string>

namespace bf = boost::fusion;
namespace bm = boost::mpl;

int
main(int argc, char** argv)
{
    using L2_t = boost::variant<bf::pair<bm::int_<1>,char>>;
    using L1_t = boost::variant<bf::pair<bm::int_<1>,L2_t>>;
    L1_t result;
}
</code>```

while I think, it's legal.

Error message starts with:

```<code>/home/vagrant/.conan/data/boost/1.64.0/conaned/master/package/b06f2a498643ee1d889c6aea8e0e21d3cac9f57c/include/boost/fusion/support/pair.hpp: In instantiation of ‘constexpr boost::fusion::pai
r<First, Second>::pair(const boost::fusion::pair<First, Second2>&) [with Second2 = boost::variant<boost::fusion::pair<mpl_::int_<1>, char> >; First = mpl_::int_<1>; Second = char]’:          /home/vagrant/.conan/data/boost/1.64.0/conaned/master/package/b06f2a498643ee1d889c6aea8e0e21d3cac9f57c/include/boost/type_traits/is_constructible.hpp:33:45:   required by substitution of ‘tem
plate<class T, class Arg, class> static boost::type_traits::yes_type boost::detail::is_constructible_imp::test1(int) [with T = boost::fusion::pair<mpl_::int_<1>, char>; Arg = const boost::fus
ion::pair<mpl_::int_<1>, boost::variant<boost::fusion::pair<mpl_::int_<1>, char> > >&; <template-parameter-1-3> = <missing>]’
</code>```

Compilation succeeds when I change one of pair's key value to make them different.

How to solve this problem? I use those pair key values to serialize/deserialize, so having them same values on different levels is important for me.

答: As xaxxon said, this works starting with gcc 5.2.</p>

Body:
Following code fails to compile on gcc 4.9.2 with boost 1.64:

#include <boost/fusion/support/pair.hpp>
#include <boost/mpl/int.hpp>
#include <boost/variant.hpp>

#include <string>

namespace bf = boost::fusion;
namespace bm = boost::mpl;

int
main(int argc, char** argv)
{
    using L2_t = boost::variant<bf::pair<bm::int_<1>,char>>;
    using L1_t = boost::variant<bf::pair<bm::int_<1>,L2_t>>;
    L1_t result;
}

while I think, it's legal.

Error message starts with:

/home/vagrant/.conan/data/boost/1.64.0/conaned/master/package/b06f2a498643ee1d889c6aea8e0e21d3cac9f57c/include/boost/fusion/support/pair.hpp: In instantiation of ‘constexpr boost::fusion::pai
r<First, Second>::pair(const boost::fusion::pair<First, Second2>&) [with Second2 = boost::variant<boost::fusion::pair<mpl_::int_<1>, char> >; First = mpl_::int_<1>; Second = char]’:          /home/vagrant/.conan/data/boost/1.64.0/conaned/master/package/b06f2a498643ee1d889c6aea8e0e21d3cac9f57c/include/boost/type_traits/is_constructible.hpp:33:45:   required by substitution of ‘tem
plate<class T, class Arg, class> static boost::type_traits::yes_type boost::detail::is_constructible_imp::test1(int) [with T = boost::fusion::pair<mpl_::int_<1>, char>; Arg = const boost::fus
ion::pair<mpl_::int_<1>, boost::variant<boost::fusion::pair<mpl_::int_<1>, char> > >&; <template-parameter-1-3> = <missing>]’

Compilation succeeds when I change one of pair's key value to make them different.

How to solve this problem? I use those pair key values to serialize/deserialize, so having them same values on different levels is important for me.


问:
Android: Scroll in a NestedScrollView to align a View to visible screen top
I have expandable views in my layout like this.

Suppose I click on education, I need my NestedScrollView to move such that Education CardView  should align to visible top of layout/screen.

I tried scrollView.smoothScrollTo(view.getTop());
It's as if the function is not even getting called.

Code where I am calling smoothScrollTo()

```<code>@OnClick(R.id.ip_expand_experience)
void expandExperiences(){
    if(!experiencesExpanded){
        AnimationUtils.expand(experiencesCard,context,CARD_HEIGHT_COLLAPSED);
        experiencesExpanded=true;
        focusOnView(experiencesCard);
    }else{
        AnimationUtils.collapse(experiencesCard,context,CARD_HEIGHT_COLLAPSED);
        experiencesExpanded=false;
    }

}

private void focusOnView(final View view){
    scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.smoothScrollTo(0, view.getTop());
        }
    });
}
</code>```

答:
try this</p>

```<code> your_scrollview.post(new Runnable() {
        @Override
        public void run() {
            your_scrollview.scrollTo(0, yourview.getBottom());
        }
    });
</code>```

Body:
I have expandable views in my layout like this.

Suppose I click on education, I need my NestedScrollView to move such that Education CardView  should align to visible top of layout/screen.

I tried scrollView.smoothScrollTo(view.getTop());
It's as if the function is not even getting called.

Code where I am calling smoothScrollTo()

@OnClick(R.id.ip_expand_experience)
void expandExperiences(){
    if(!experiencesExpanded){
        AnimationUtils.expand(experiencesCard,context,CARD_HEIGHT_COLLAPSED);
        experiencesExpanded=true;
        focusOnView(experiencesCard);
    }else{
        AnimationUtils.collapse(experiencesCard,context,CARD_HEIGHT_COLLAPSED);
        experiencesExpanded=false;
    }

}

private void focusOnView(final View view){
    scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.smoothScrollTo(0, view.getTop());
        }
    });
}

Body:
try this

 your_scrollview.post(new Runnable() {
        @Override
        public void run() {
            your_scrollview.scrollTo(0, yourview.getBottom());
        }
    });


问:
Java-based workflow solutions
We currently use a sequential workflow to process documents. We have a total of 10 distinct workflow steps. We have re-analyzed the workflow and realized that we could restructure the workflow to process in parallel a number of the workflow steps. Basically we are able to process steps 1,2,3,4 in parallel, wait until steps 1-4 are completed and then process step 5, then process steps 6,7,8,9 in parallel wait until steps 6-9 are completed and then finally process step 10. If we were able to implement this new workflow we could boost our processing throughput dramatically.

My question is: What java-based open-source workflow projects would you recommend? Do they typically support what I outlined above?

Thanks for all the replies. After taking a quick look at the the websites you all have listed I think I have more than enough to chew on for a while.

答: You could have a look at YAWL.</p>

Title: Java-based workflow solutions

Body: You could have a look at YAWL.


问:
Does jquery post ever timeout?
Official documentation at jQuery does not mention it.

Possible confusion: I know I can use ajax to gain control over timeout, but my question is different.

Scenario:

I am using post to grab data from a backend which I know will take a long (sometimes very very long) time to load.

Question:

Will my javascript request ever timeout or will it always wait until backend is loaded, even if it takes a few minutes?

答:
HTTP Request timeout is a server side configuration not a client side configuration. Requests submitted via Jquery code is no different.
You might want to have a test against the return code from the last request and add exception handling to your code (like resubmit the request)

Always check the response code and a common strategy is to rety. https://www.lifewire.com/g00/troubleshooting-network-error-messages-4102727

Title: Does jquery post ever timeout?


答:
The timeout of a request is, by default, controlled by the browser and the receiving server, whichever cancels the request first. I believe most browsers have a 60 second timeout by default. The server can be any arbitrary value.

Will my javascript request ever timeout or will it always wait until backend is loaded, even if it takes a few minutes?

The answer to this is therefore, yes, your request will timeout at an arbitrary point. If you want to control the amount of time you force your users to wait for a request then you can specifically set this time by using the timeout property of the $.ajax call. This overrides any timeout set in the browser or on the server.

15 seconds should be more than enough. If a request is taking longer than that I'd suggest you change the pattern you're using to generate the response.

Title: Does jquery post ever timeout?

Body:
Official documentation at jQuery does not mention it.

Possible confusion: I know I can use ajax to gain control over timeout, but my question is different.

Scenario:

I am using post to grab data from a backend which I know will take a long (sometimes very very long) time to load.

Question:

Will my javascript request ever timeout or will it always wait until backend is loaded, even if it takes a few minutes?


问:
Overriding a hooked in function in WooCommerce
What is the procedure of overriding functions that are hooked into WordPress?

The following function in wc-template-functions.php is one of the functions I'm looking to override:

```<code>function woocommerce_template_loop_product_link_close() {
    echo '</a>';
}
</code>```

It is hooked in at wc-template-hooks.php:

```<code>add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );
</code>```

If I write the following code, the function is then unhooked:

```<code>function remove_default_wc_behaviour() {
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );
}

add_action( 'init', 'remove_default_wc_behaviour' );
</code>```

But what if I want to override the function, ie. implement my own functionality instead of the default functionality from WooCommerce?

Would I call a remove_action() first, and then hook in my function with add_action(), or is there a procedure which can simply override the function that is hooked in my WooCommerce?

Thanks in advance

答:
The first option is the right one: In your main function hooked in init action hook, you can add your replacement hooked function:

```<code>add_action( 'init', 'replace_default_wc_behaviour' );
function remove_default_wc_behaviour() {
    // remove the default behavior
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );

    // Replace by your custom behavior
    add_action( 'woocommerce_after_shop_loop_item', 'custom_WC_loop_product_link_close', 5 );
    function custom_WC_loop_product_link_close() {
        // Do your custumizations

        // add the close tag
        echo '</a>';
    }
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Body:
What is the procedure of overriding functions that are hooked into WordPress?

The following function in wc-template-functions.php is one of the functions I'm looking to override:

function woocommerce_template_loop_product_link_close() {
    echo '';
}

It is hooked in at wc-template-hooks.php:

add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );

If I write the following code, the function is then unhooked:

function remove_default_wc_behaviour() {
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );
}

add_action( 'init', 'remove_default_wc_behaviour' );

But what if I want to override the function, ie. implement my own functionality instead of the default functionality from WooCommerce?

Would I call a remove_action() first, and then hook in my function with add_action(), or is there a procedure which can simply override the function that is hooked in my WooCommerce?

Thanks in advance

Body:
The first option is the right one: In your main function hooked in init action hook, you can add your replacement hooked function:

add_action( 'init', 'replace_default_wc_behaviour' );
function remove_default_wc_behaviour() {
    // remove the default behavior
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );

    // Replace by your custom behavior
    add_action( 'woocommerce_after_shop_loop_item', 'custom_WC_loop_product_link_close', 5 );
    function custom_WC_loop_product_link_close() {
        // Do your custumizations

        // add the close tag
        echo '</a>';
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.


问:
how to get all mysql tuple result and convert to json
I was able to get a single data from a table. but when i'm trying to get all the data on my table, i got only a single row. </p>

```<code>cnn.execute(sql)
        rows = cnn.fetchall()
        column = [t[0] for t in cnn.description]
        for row in rows:
            myjson = {column[0]: row[0], column[1]: row[1], column[2]: row[2], column[3]: row[3], column[4]: row[4], column[5]: row[5], column[6]: row[6], column[7]: row[7], column[8]: row[8], column[9]: row[9], column[10]: row[10], column[11]: row[11], column[12]: row[12], column[13]: row[13], column[14]: row[14], column[15]: row[15], column[16]: row[16], column[17]: row[17], column[18]: row[18], column[19]: row[19], column[20]: row[20]}
            myresult = json.dumps(myjson, indent=3)
            return myresult
</code>```

答:
```<code>#imports
import collections
import MySQLdb
import json

#connect to database
conn = MySQLdb.connect(host= "localhost", user="root", passwd="abc",  db="mydatabase")

#Fetch rows
sql  = "SELECT * from userstable"
cursor = conn.cursor()
cursor.execute(sql)
data = cursor.fetchall()

#Converting data into json
user_list = []
for row in data :
    d = collections.OrderedDict()
    d['firstName']  = row[1] #name
    d['lastName']   = row[2] #lname
    d['email']      = row[3] #email
    user_list.append(d)

return json.dumps(user_list)

##Result
[{"firstName":"jame","lastName":"king","email":"test@gmail.com"}]
</code>```

Body:
I was able to get a single data from a table. but when i'm trying to get all the data on my table, i got only a single row.

cnn.execute(sql)
        rows = cnn.fetchall()
        column = [t[0] for t in cnn.description]
        for row in rows:
            myjson = {column[0]: row[0], column[1]: row[1], column[2]: row[2], column[3]: row[3], column[4]: row[4], column[5]: row[5], column[6]: row[6], column[7]: row[7], column[8]: row[8], column[9]: row[9], column[10]: row[10], column[11]: row[11], column[12]: row[12], column[13]: row[13], column[14]: row[14], column[15]: row[15], column[16]: row[16], column[17]: row[17], column[18]: row[18], column[19]: row[19], column[20]: row[20]}
            myresult = json.dumps(myjson, indent=3)
            return myresult


问:
Javascript - returning concatenates instead of sum of variables from input
I am trying to get values from input field using .each() and adding them to show the sum in another input value. But unfortunately in spite of using parseInt() I am unable to get sum.

HTML

```<code><input type=text name=value[] id=value class="value">
<input type=text name=value[] id=value class="value">
<input type=text name=totalvalue id=totalvalue>
</code>```

JavaScript

```<code>var totalvalue = parseInt(0);
$(document).on("focusout",".value",function() {
    $(".value").each(function() {
        totalvalue = parseInt(totalvalue + $(this).val());
    });
    $("#totalvalue").val(totalvalue);
});
</code>```

JSFiddle Demo

答:
You should declare totalvalue inside focusout function  ,because it will always show the total of two input text and pass the input value empty state when sum !!!

```<code>$(document).on("focusout",".value",function() {
    var totalvalue = 0;
    $(".value").each(function() {
        if($(this).val() == "") return;
        totalvalue +=  parseInt($(this).val());
    });
    $("#totalvalue").val(totalvalue);
});
</code>```

Body:
I am trying to get values from input field using .each() and adding them to show the sum in another input value. But unfortunately in spite of using parseInt() I am unable to get sum.

HTML

<input type=text name=value[] id=value class="value">
<input type=text name=value[] id=value class="value">
<input type=text name=totalvalue id=totalvalue>

JavaScript

var totalvalue = parseInt(0);
$(document).on("focusout",".value",function() {
    $(".value").each(function() {
        totalvalue = parseInt(totalvalue + $(this).val());
    });
    $("#totalvalue").val(totalvalue);
});

JSFiddle Demo

Body:
You should declare totalvalue inside focusout function  ,because it will always show the total of two input text and pass the input value empty state when sum !!!

$(document).on("focusout",".value",function() {
    var totalvalue = 0;
    $(".value").each(function() {
        if($(this).val() == "") return;
        totalvalue +=  parseInt($(this).val());
    });
    $("#totalvalue").val(totalvalue);
});


问:
How to make servo reach the desired angle slowly?
I found a solution that make a servo reach a desired angle step by step , But it depends on the current angle of servo .
this is the code :

```<code>    if servo_current angle > servo_desired_angle :
        while(x=true) :
             servo_current_angle -=1
             duty_cycle = (((12.5-2.5)/(180-0) * servo_current_angle) +2.5
             p.ChangeDutyCycle (duty_cycle)
             time.sleep(0.01)
             if servo_current angle = servo_desired_angle :
                 x = false
    elif servo_current_angle < servo_desired_angle :
         while(x=true) :
             servo_current_angle +=1
             duty_cycle = (((12.5-2.5)/(180-0) * servo_current_angle) +2.5
             p.ChangeDutyCycle (duty_cycle)
             time.sleep(0.01)
             if servo_current angle = servo_desired_angle :
                 x = false
</code>```

the problem is How to know servo_current_angle ?

答:
What about tracking the current servo position during runtime and
  update it along the way?

You can use the PWM module in
  RPi.GPIO and in the beginning move
  the servo into its initial position to start from.

The position of the servo motor is set by the length of a pulse. The servo expects to receive a pulse at least every 20 milliseconds. If that pulse is high for 1 millisecond, the servo angle will be zero; if it is 1.5 milliseconds, it will be at its center position; and if it is 2 milliseconds, it will be at 180 degrees.

The example program sets the PWM frequency to 100 Hz, which will send a pulse to the servo every 10 milliseconds. The angle is converted into a duty cycle between 0 and 100. This actually produces pulses shorter than the 1 millisecond expected minimum value and longer than 2 milliseconds maximum.

Source here

Body:
I found a solution that make a servo reach a desired angle step by step , But it depends on the current angle of servo .
this is the code :

    if servo_current angle > servo_desired_angle :
        while(x=true) :
             servo_current_angle -=1
             duty_cycle = (((12.5-2.5)/(180-0) * servo_current_angle) +2.5
             p.ChangeDutyCycle (duty_cycle)
             time.sleep(0.01)
             if servo_current angle = servo_desired_angle :
                 x = false
    elif servo_current_angle < servo_desired_angle :
         while(x=true) :
             servo_current_angle +=1
             duty_cycle = (((12.5-2.5)/(180-0) * servo_current_angle) +2.5
             p.ChangeDutyCycle (duty_cycle)
             time.sleep(0.01)
             if servo_current angle = servo_desired_angle :
                 x = false

the problem is How to know servo_current_angle ?


问:
UICollctionView didSelectItemAt problems
I am trying to change an UIImage in the collectionviewcell with the help of on didSelectItemAt. It is working when I select cell on the beginning but when I scroll down and scroll back up the images are back to what they were and changed images shift to different cells.

First cell selected Image

Scrolled down then came up Image

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collection_cell", for: indexPath) as! RateCardCollectionViewCell
        let tempString = "\(NSLocalizedString("base_url", comment: ""))\(itemImageLink[indexPath.row])"
        let urlnew:String = tempString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
        let url = URL(string: urlnew)
        cell.rateCardImage.kf.setImage(with: url,placeholder: UIImage(named: "Junkart_Bin.png"))
        cell.label.text = itemName[indexPath.row]
        cell.itemRate.text = itemRate[indexPath.row]
        cell.layer.cornerRadius = 3
        cell.card.backgroundColor = UIColor.white
        cell.card.layer.masksToBounds = false
        cell.card.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
        cell.card.layer.shadowOffset = CGSize(width: 0, height: 0)
        cell.card.layer.shadowOpacity = 1   //0.8
        return cell
    }

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! RateCardCollectionViewCell
        if self.selectedRate == nil {
            cell.changeImagetoSelected()
            self.selectedRate = [Int]()
            self.selectedRate.append(indexPath.row)
        }
        else {

        }
    }
</code>```

Following is the UICollectionViewCell Class

```<code>class RateCardCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var rateCardImage: UIImageView!
    @IBOutlet weak var card: UIView!
    @IBOutlet weak var itemRate: UILabel!
    @IBOutlet weak var selected_rate_image: UIImageView!
    func changeImagetounSelected() {
        selected_rate_image.image = UIImage(named: "unselected_rate")
    }
    func changeImagetoSelected() {
        selected_rate_image.image = UIImage(named: "selected_rate")
    }
}
</code>```

Please Help!!

答:
Check the cell creation index added on the selectedRate at the time of cell creation cellForItemAt.

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collection_cell", for: indexPath) as! RateCardCollectionViewCell
        // Your remaining codes are here.

        if selectedRate.contains(IndexPath.row) {
           cell.changeImageToSelected()
        } else {
           cell.changeImageTounselected()
        }
        return cell
    }
</code>```

Body:
I am trying to change an UIImage in the collectionviewcell with the help of on didSelectItemAt. It is working when I select cell on the beginning but when I scroll down and scroll back up the images are back to what they were and changed images shift to different cells.

First cell selected Image

Scrolled down then came up Image

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collection_cell", for: indexPath) as! RateCardCollectionViewCell
        let tempString = "\(NSLocalizedString("base_url", comment: ""))\(itemImageLink[indexPath.row])"
        let urlnew:String = tempString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
        let url = URL(string: urlnew)
        cell.rateCardImage.kf.setImage(with: url,placeholder: UIImage(named: "Junkart_Bin.png"))
        cell.label.text = itemName[indexPath.row]
        cell.itemRate.text = itemRate[indexPath.row]
        cell.layer.cornerRadius = 3
        cell.card.backgroundColor = UIColor.white
        cell.card.layer.masksToBounds = false
        cell.card.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
        cell.card.layer.shadowOffset = CGSize(width: 0, height: 0)
        cell.card.layer.shadowOpacity = 1   //0.8
        return cell
    }

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! RateCardCollectionViewCell
        if self.selectedRate == nil {
            cell.changeImagetoSelected()
            self.selectedRate = [Int]()
            self.selectedRate.append(indexPath.row)
        }
        else {

        }
    }

Following is the UICollectionViewCell Class

class RateCardCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var rateCardImage: UIImageView!
    @IBOutlet weak var card: UIView!
    @IBOutlet weak var itemRate: UILabel!
    @IBOutlet weak var selected_rate_image: UIImageView!
    func changeImagetounSelected() {
        selected_rate_image.image = UIImage(named: "unselected_rate")
    }
    func changeImagetoSelected() {
        selected_rate_image.image = UIImage(named: "selected_rate")
    }
}

Please Help!!

Body:
Check the cell creation index added on the selectedRate at the time of cell creation cellForItemAt.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collection_cell", for: indexPath) as! RateCardCollectionViewCell
        // Your remaining codes are here.

        if selectedRate.contains(IndexPath.row) {
           cell.changeImageToSelected()
        } else {
           cell.changeImageTounselected()
        }
        return cell
    }


问:
Can someone explain to me what the code below is doing?
I am working on a Rails tutorial and I have no idea what

```<code>@comment.article_id = params[:article_id]
</code>```

is doing in the code:

```<code> def create
    @comment = Comment.new(comment_params)
    @comment.article_id = params[:arcticle_id]
    @comment.save
    redirect_to article_path(@comment.article)
 end
</code>```

Also, does the params[:article_id] get transferred into the instance variable on the left ?

答:
You need to read about Rails "Active Record Associations"

```<code>class Article < ApplicationRecord
  has_many :comments, dependent: :destroy
end

class Comments < ApplicationRecord
  belongs_to :article
end
</code>```

When you create has_many and belongs_to relation between two tables you need to store article.id in comments table then comments related to that particular article.

In your code:

```<code>def create
    @comment = Comment.new(comment_params)
    @comment.article_id = params[:arcticle_id]

    @comment.save

    redirect_to article_path(@comment.article)
end
</code>```

You are creating comment for an article so when you do

@comment.article_id = params[:arcticle_id]

it will store the article.id in this comment so this comment related to that particular article.

Read Active Record Associations

Body:
I am working on a Rails tutorial and I have no idea what

@comment.article_id = params[:article_id]

is doing in the code:

 def create
    @comment = Comment.new(comment_params)
    @comment.article_id = params[:arcticle_id]
    @comment.save
    redirect_to article_path(@comment.article)
 end

Also, does the params[:article_id] get transferred into the instance variable on the left ?

Body:
You need to read about Rails "Active Record Associations"

class Article < ApplicationRecord
  has_many :comments, dependent: :destroy
end

class Comments < ApplicationRecord
  belongs_to :article
end

When you create has_many and belongs_to relation between two tables you need to store article.id in comments table then comments related to that particular article.

In your code:

def create
    @comment = Comment.new(comment_params)
    @comment.article_id = params[:arcticle_id]

    @comment.save

    redirect_to article_path(@comment.article)
end

You are creating comment for an article so when you do

@comment.article_id = params[:arcticle_id]

it will store the article.id in this comment so this comment related to that particular article.

Read Active Record Associations


问:
How to change audio output device using VLC.Net
I am able to create media player like app using VLC.Net library. I am now trying to add a feature to be able to select the output device to play the media through. So far no luck.
Has anyone ever done it?</p>

答:
From reading the source code I would try the following. I assume you have a VlcMediaPlayer at hand and created somewhere:</p>

```<code>void DoAudio(VlcMediaPlayer player)
{
    IAudioManagement audioMgt = player.Audio;

    foreach(AudioOutputDescriptions descriptions in audioMgt.Outputs.All){

        foreach(AudioOutputDevice device in description.Devices){
            //enumerate them for display
            string audioName = device.LongName;

            // Or set it as output
            device.SetAsCurrent();
        }
}
</code>```

Body:
From reading the source code I would try the following. I assume you have a VlcMediaPlayer at hand and created somewhere:

void DoAudio(VlcMediaPlayer player)
{
    IAudioManagement audioMgt = player.Audio;

    foreach(AudioOutputDescriptions descriptions in audioMgt.Outputs.All){

        foreach(AudioOutputDevice device in description.Devices){
            //enumerate them for display
            string audioName = device.LongName;

            // Or set it as output
            device.SetAsCurrent();
        }
}


问:
Does throwing an Exception have to cause the program to terminate
Does throwing an Exception have to cause the program to terminate?

I think its no, I just want to make sure

答:
It depends on the thread where the exception is thrown, and on the other threads running on the same time in the application.

An uncaught exception terminates the thread where it was thrown. If the rest of the threads are only daemon threads, then yes, the application will be terminated.

According to Thread.setDaemon(boolean) documentation:

The Java Virtual Machine exits when the only threads running are all daemon threads.


问:
Generate date range in between 2 dates
for the last couple of hours I have been breaking my head over this.

I want to create a result set which contains a series of dates like this:

```<code>2011-07-05
2011-07-04
2011-07-03
2011-07-02
2011-07-01
2011-06-30
2011-06-29
2011-06-28
...
</code>```

Ideally between 2 dates given. But If I can say the last 30 days or the last 100 days from now that would be fine also.

Normally I would this with a CTE like this

```<code>;WITH Dates AS
(
    SELECT CONVERT(DATE, GETDATE()) [Date]
    UNION ALL
    SELECT DATEADD(DAY,-1, [Date])
    FROM Dates
    WHERE [Date] > DATEADD(DAY, -30, CONVERT(DATE, GETDATE()))
)
SELECT [Date]
</code>```

But I am not allowed to use any statements that can't be executed in a subquery. The program I am using executes queries like this:

```<code>Select *
From (
    TheQuery
) as t1
</code>```

This means I can't use declares, no stored procedures, no CTEs..

Is there any way I can obtain the dataset I need with these limitations?

I am using azure SQL

答:
If you dont't want create a calendar table or a number table, nor use existing table to generate numbers/ date (see for example https://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1)
you could use something like this:</p>

```<code>SELECT DATEADD(DAY, -B.N1+1, CONVERT(DATE, GETDATE())) AS D1
FROM
(SELECT 1 AS N1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7  UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10) A
CROSS JOIN (SELECT 1 AS N1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7  UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10) B
</code>```

Title: Generate date range in between 2 dates

Body:
for the last couple of hours I have been breaking my head over this.

I want to create a result set which contains a series of dates like this:

2011-07-05
2011-07-04
2011-07-03
2011-07-02
2011-07-01
2011-06-30
2011-06-29
2011-06-28
...

Ideally between 2 dates given. But If I can say the last 30 days or the last 100 days from now that would be fine also.

Normally I would this with a CTE like this

;WITH Dates AS
(
    SELECT CONVERT(DATE, GETDATE()) [Date]
    UNION ALL
    SELECT DATEADD(DAY,-1, [Date])
    FROM Dates
    WHERE [Date] > DATEADD(DAY, -30, CONVERT(DATE, GETDATE()))
)
SELECT [Date]

But I am not allowed to use any statements that can't be executed in a subquery. The program I am using executes queries like this:

Select *
From (
    TheQuery
) as t1

This means I can't use declares, no stored procedures, no CTEs..

Is there any way I can obtain the dataset I need with these limitations?

I am using azure SQL

Body:
If you dont't want create a calendar table or a number table, nor use existing table to generate numbers/ date (see for example https://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1)
you could use something like this:

SELECT DATEADD(DAY, -B.N1+1, CONVERT(DATE, GETDATE())) AS D1
FROM
(SELECT 1 AS N1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7  UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10) A
CROSS JOIN (SELECT 1 AS N1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7  UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10) B


答:
Jquery uses the native XMLHttpRequest module to make requests.

The XMLHttpRequest.timeout property is an unsigned long representing the number of milliseconds a request can take before automatically being terminated. The default value is 0, which means there is no timeout.

Reading the source code of the jquery library, the ajax method does not set a timeout in and way, hence it is save to say that the request does not timeout.

But you can explicitly set a timeout in both jquery and the native module.

this does not mean that your request will not timeout, since the server usually does impose a bail timeout strategy, usually long responses timeout from the server side. you could consider chunking or streaming as a safe and convenient solution.

github jquery ajax source:

https://github.com/jquery/jquery/tree/2d4f53416e5f74fa98e0c1d66b6f3c285a12f0ce/src/ajax

Title: Does jquery post ever timeout?


问:
How to get String output as in single quote in javascript
Advance thanks, Question looks like simple but i could not able to find the solution.

```<code>function sumStrings(a, b)
{
return  +a + +b;
}
sumStrings('1','2') //=>3
</code>```

Expected output

```<code>sumStrings('1','2') // => '3'
</code>```

答:
After addition, add ' to beginning and end.

function sumStrings(a, b){

  return  "'" + (Number(a) + Number(b)) + "'";
}
console.log(sumStrings('1','2'));```

Body:
Advance thanks, Question looks like simple but i could not able to find the solution.

function sumStrings(a, b)
{
return  +a + +b;
}
sumStrings('1','2') //=>3

Expected output

sumStrings('1','2') // => '3'


答:
since you are using a relational database the 'artical_id' is used to create a relation between the comment and the article that it belongs to.

So the code:

```<code>@comment.artical_id = params[:artical_id]
</code>```

is used to give the comment it's article id so it can be referred back to later.

Hope this help

Title: Can someone explain to me what the code below is doing?

Body:
since you are using a relational database the 'artical_id' is used to create a relation between the comment and the article that it belongs to.

So the code:

@comment.artical_id = params[:artical_id]

is used to give the comment it's article id so it can be referred back to later.

Hope this help


问:
Uploading latest version of Excel data like 2013 into SQL Server table without installing Access database engine
I get this error

The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

I get this error when I try to upload Excel 2013 data into a SQL Server table using .NET. I need to solve this error without installing the Access database engine.

答:
Here is one option - https://www.simple-talk.com/sql/ssis/moving-data-from-excel-to-sql-server-10-steps-to-follow/

Another option would be to use OleDbConnection to read data from the excel file and then insert that data to the sql server -Accessing Excel 2013 File in ASP.NET


问:
How to label x-axis if a sequence is used?
I've this R script:

```<code>plot(
  seq(2011, 2015),
  main = 'Anzahl vor dem 20 Lebensjahr verstorbener Personen',
  xlab = 'Jahre',
  ylab = 'Tode',
  ylim = c(100, 400)
)

points(
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'Jahr'],
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'value'],
  col = 'blue'
)

points(
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'Jahr'],
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'value'],
  col = 'red'
)
</code>```

Which produces this plot:

My quick question is: How can I achieve, that the x-axis is labeled with the sequence? (2011, 2012, 2013, 2014, 2015)

Tl;dr

My data looks like this:

```<code>> deaths.data
   Geschlecht Demographisches.Merkmal Jahr value
1        Mann         Unter 20 Jahren 2011   301
2        Frau         Unter 20 Jahren 2011   214
3        Mann         Unter 20 Jahren 2012   285
4        Frau         Unter 20 Jahren 2012   203
5        Mann         Unter 20 Jahren 2013   312
6        Frau         Unter 20 Jahren 2013   212
7        Mann         Unter 20 Jahren 2014   305
8        Frau         Unter 20 Jahren 2014   209
9        Mann         Unter 20 Jahren 2015   323
10       Frau         Unter 20 Jahren 2015   225
</code>```

答:
plot(seq(2011, 2015)) does not do what you seem to be expecting it to do. If you feed plot a vector, it will plot the values of the vector on the y-axis against their indices on the x-axis.

So this plot would range from 1 to 5 on the x-axis, and would range from 2011-2015 on the y-axis, if you didn't specify ylim = c(100, 400). The points you plot initially, fall outside of this range, so are not shown. You then place the points with your actual data. I suspect that the years in your dataframe also have values of 1 to 5, instead of the actual years. Thats's how these points are plotted on x=1 tot x=5.

To change this, we only have to adjust the value in deaths.data$years.

```<code>plot(
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'Jahr'] + 2010,
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'value'],
  col = 'blue',
  main = 'Anzahl vor dem 20 Lebensjahr verstorbener Personen',
  xlab = 'Jahre',
  ylab = 'Tode',
  ylim = c(100, 400),
  type = 'p'
)
points(
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'Jahr'] + 2010,
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'value'],
  col = 'red'
)
</code>```

In the code above, I added 2010 to the years value. This should make the years take 2011-2015 instead of 1-5. I can't verify, because you didn't show your data in your post.

After OP edit:

I tried to reproduce a part of your dataset:

```<code>deaths.data <- data.frame(Geschlecht = rep("Mann", 5), Jahr = 2011:2015, value = c(301, 285, 312, 305, 323))
</code>```

Using this, my provided code worked (aside from the fact I was missing some commas.

However, when I changed it to this:

```<code>deaths.data <- data.frame(Geschlecht = rep("Mann", 5), Jahr = as.character(2011:2015), value = c(301, 285, 312, 305, 323))
</code>```

It provided similar output to what you showed in your question.

I assume that the years you have in your dataset are stored as characters instead of numerics. Changing that with as.numeric should fix your problem.

Body:
I've this R script:

plot(
  seq(2011, 2015),
  main = 'Anzahl vor dem 20 Lebensjahr verstorbener Personen',
  xlab = 'Jahre',
  ylab = 'Tode',
  ylim = c(100, 400)
)

points(
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'Jahr'],
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'value'],
  col = 'blue'
)

points(
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'Jahr'],
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'value'],
  col = 'red'
)

Which produces this plot:

My quick question is: How can I achieve, that the x-axis is labeled with the sequence? (2011, 2012, 2013, 2014, 2015)

Tl;dr

My data looks like this:

> deaths.data
   Geschlecht Demographisches.Merkmal Jahr value
1        Mann         Unter 20 Jahren 2011   301
2        Frau         Unter 20 Jahren 2011   214
3        Mann         Unter 20 Jahren 2012   285
4        Frau         Unter 20 Jahren 2012   203
5        Mann         Unter 20 Jahren 2013   312
6        Frau         Unter 20 Jahren 2013   212
7        Mann         Unter 20 Jahren 2014   305
8        Frau         Unter 20 Jahren 2014   209
9        Mann         Unter 20 Jahren 2015   323
10       Frau         Unter 20 Jahren 2015   225

Body:
plot(seq(2011, 2015)) does not do what you seem to be expecting it to do. If you feed plot a vector, it will plot the values of the vector on the y-axis against their indices on the x-axis.

So this plot would range from 1 to 5 on the x-axis, and would range from 2011-2015 on the y-axis, if you didn't specify ylim = c(100, 400). The points you plot initially, fall outside of this range, so are not shown. You then place the points with your actual data. I suspect that the years in your dataframe also have values of 1 to 5, instead of the actual years. Thats's how these points are plotted on x=1 tot x=5.

To change this, we only have to adjust the value in deaths.data$years.

plot(
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'Jahr'] + 2010,
  deaths.data[deaths.data['Geschlecht'] == 'Mann', 'value'],
  col = 'blue',
  main = 'Anzahl vor dem 20 Lebensjahr verstorbener Personen',
  xlab = 'Jahre',
  ylab = 'Tode',
  ylim = c(100, 400),
  type = 'p'
)
points(
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'Jahr'] + 2010,
  deaths.data[deaths.data['Geschlecht'] == 'Frau', 'value'],
  col = 'red'
)

In the code above, I added 2010 to the years value. This should make the years take 2011-2015 instead of 1-5. I can't verify, because you didn't show your data in your post.

After OP edit:

I tried to reproduce a part of your dataset:

deaths.data <- data.frame(Geschlecht = rep("Mann", 5), Jahr = 2011:2015, value = c(301, 285, 312, 305, 323))

Using this, my provided code worked (aside from the fact I was missing some commas.

However, when I changed it to this:

deaths.data <- data.frame(Geschlecht = rep("Mann", 5), Jahr = as.character(2011:2015), value = c(301, 285, 312, 305, 323))

It provided similar output to what you showed in your question.

I assume that the years you have in your dataset are stored as characters instead of numerics. Changing that with as.numeric should fix your problem.


问:
How to use the same name classes but in separate styles
see the example to understand:

```<code>    <!--Standard Bootstrap -->
    <link href="/build/css/site/bootstrap.min.css" rel="stylesheet">

    <!-- Material Design Bootstrap -->
    <link href="/build/css/site/mdb.min.css" rel="stylesheet">
</code>```

so i want a thing like it:

```<code>    <div class="btn btn-danger" >Standard Bootstrap Button</div>
    <div class="btn btn-danger" >Material Design Bootstrap Button</div>
</code>```

The name of the classes are the same. But they are in two separate styles.
How can I use the two styles as I said?

Forgive me for the bad English.

答:
Using the

This paragraph is blue.

  <style scoped>
    p {color: red;}
  </style>

This paragraph is red.

```

<p>Using this, we can replace the CSS selector with an <code>@import</code> to import the Bootstrap CSS in one section and the Material Design Bootstrap in another.</p>

<p><strong>Note:</strong> the example below will ONLY work in Firefox as of 07/06/2017.  </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>

  <div class="btn btn-danger">Standard Bootstrap Button</div>
</div>

<div>

  <div class="btn btn-danger">Material Design Bootstrap Button</div>
</div></code>```

Here's the result in Firefox

Another downside to this is you'll need to re-@import each stylesheet for each section.

There are several polyfills available to add support for scoped to browsers which currently don't support it. There's also a jQuery script if you're already using jQuery.

ContentLicense: CC BY-SA 4.0

Body:
see the example to understand:

    <link href="/build/css/site/bootstrap.min.css" rel="stylesheet">

    <link href="/build/css/site/mdb.min.css" rel="stylesheet">

so i want a thing like it:

Standard Bootstrap Button

Material Design Bootstrap Button

The name of the classes are the same. But they are in two separate styles.
How can I use the two styles as I said?

Forgive me for the bad English.

Body:
Using the <style> scoped attribute this is possible, but comes with several caveats.

It currently works only in Firefox

Every other browser will require a polyfill to add support for the scoped attribute - here's one and there are several others available

And even with a polyfill it may not work - I did a few quick experiments with different polyfills and @import but had no luck

The scoped attribute allows CSS within a <style> tag to be scoped to the parent element where the <style> tag is contained. Here's a quick example:

<div>
  <style scoped>
    p {color: blue;}
  </style>

  <p>This paragraph is blue.</p>
</div>

<div>
  <style scoped>
    p {color: red;}
  </style>

  <p>This paragraph is red.</p>
</div>

Using this, we can replace the CSS selector with an @import to import the Bootstrap CSS in one section and the Material Design Bootstrap in another.

Note: the example below will ONLY work in Firefox as of 07/06/2017.

<div>
  <style scoped>
    @import url(https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css)
  </style>

  <div class="btn btn-danger">Standard Bootstrap Button</div>
</div>

<div>
  <style scoped>
    @import url(https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/4.0.2/bootstrap-material-design.min.css)
  </style>

  <div class="btn btn-danger">Material Design Bootstrap Button</div>
</div>

Here's the result in Firefox

Another downside to this is you'll need to re-@import each stylesheet for each section.

There are several polyfills available to add support for scoped to browsers which currently don't support it. There's also a jQuery script if you're already using jQuery.


问:
How to convert NSstring to Nsdate
I am getting response from service that

```<code>"created_at" = "Thu Jul 06 07:26:23 +0000 2017";
</code>```

i want to convert the string  into Nsdate  format
i do not know how to do it

答:
Try this:</p>

```<code>NSString *dateString = @"Thu Jul 06 07:26:23 +0000 2017";

NSDate *date =[[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"EEE MMM dd hh:mm:ss Z yyyy";
date = [ dateFormatter dateFromString:dateString];
</code>```

Title: How to convert NSstring to Nsdate

Body:
I am getting response from service that

"created_at" = "Thu Jul 06 07:26:23 +0000 2017";

i want to convert the string  into Nsdate  format
i do not know how to do it

Body:
Try this:

NSString *dateString = @"Thu Jul 06 07:26:23 +0000 2017";

NSDate *date =[[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"EEE MMM dd hh:mm:ss Z yyyy";
date = [ dateFormatter dateFromString:dateString];