问:
SymmetricDS:Creating 2 server nodes referencing same DB
So i have a scenario here. I have a Central Database, say DB0. I also have two smaller databases,  say DB1 and DB2 which are accessed by my applications, say App1 and App2 respectively. I want to replicate contents of DB0 to DB1 and DB2. For this I'm using Symmetricds.

Now this is where i'm having a doubt. I understand that I can create a CentralNode-00 pointing to DB0 and 2 ClientNodes, ClientNodes-01 and ClientNodes-02 pointing to DB1 and DB2 respectively and easily do the replication.

But I'm trying to use SymmetricDS in embedded mode with my Java. So this is how I'd like to do this:

From App1, I'd like to start a Symmetric-Server Central-00 pointing to DB0 and a Symmetric-Client Client-01 pointing to DB1. Similarly from App2, I'd like to start another instance of Symmetric-Server Central-00 pointing to DB0 and a Symmetric-Client Client-02 pointing to DB2. Obviously, App1 and App2 will be started in its own JVM.

So my question is this, Can I start two instances of the same Symmetric-Server Central-00 on two different VMs. Simply put, can i start two symmetricds server nodes that are accessing the same DB(also the same SYM tables generated within this DB.)?

This is the cofiguration that I inserted in the Central DB.

```<code>insert into sym_channel
(channel_id, processing_order, max_batch_size, enabled, description)
values('item', 1, 100000, 1, 'Item and pricing data');

insert into sym_node_group (node_group_id) values ('corp');
insert into sym_node_group (node_group_id) values ('store');
insert into sym_node_group (node_group_id) values ('store02');

insert into sym_node_group_link (source_node_group_id, target_node_group_id, data_event_action) values ('corp', 'store', 'W');
insert into sym_node_group_link (source_node_group_id, target_node_group_id, data_event_action) values ('corp', 'store02', 'W');
insert into sym_node_group_link (source_node_group_id, target_node_group_id, data_event_action) values ('store', 'corp', 'P');
insert into sym_node_group_link (source_node_group_id, target_node_group_id, data_event_action) values ('store02', 'corp', 'P');

insert into sym_trigger
(trigger_id,source_table_name,channel_id,last_update_time,create_time)
values('item','item','item',current_timestamp,current_timestamp);

insert into sym_router
(router_id,source_node_group_id,target_node_group_id,router_type,create_time,last_update_time)
values('corp_2_store', 'corp', 'store', 'default',current_timestamp, current_timestamp);

insert into sym_router
(router_id,source_node_group_id,target_node_group_id,router_type,create_time,last_update_time)
values('corp_2_store02', 'corp', 'store02', 'default',current_timestamp, current_timestamp);

insert into sym_trigger_router
(trigger_id,router_id,initial_load_order,last_update_time,create_time)
values('item','corp_2_store', 100, current_timestamp, current_timestamp);

insert into sym_trigger_router
(trigger_id,router_id,initial_load_order,last_update_time,create_time)
values('item','corp_2_store02', 100, current_timestamp, current_timestamp);
</code>```

But when i start the instances it throws a Primary Key Violation Exception.

So could someone tell me whether this is possible or not? if so could you point out my mistakes?

答: No!  Only one instance, only one symmetricds engine should be pointing to one db. Why don't you use multiengine mode and start all three engineers from one JVM client?</p>

Body:
So i have a scenario here. I have a Central Database, say DB0. I also have two smaller databases,  say DB1 and DB2 which are accessed by my applications, say App1 and App2 respectively. I want to replicate contents of DB0 to DB1 and DB2. For this I'm using Symmetricds.

Now this is where i'm having a doubt. I understand that I can create a CentralNode-00 pointing to DB0 and 2 ClientNodes, ClientNodes-01 and ClientNodes-02 pointing to DB1 and DB2 respectively and easily do the replication.

But I'm trying to use SymmetricDS in embedded mode with my Java. So this is how I'd like to do this:

From App1, I'd like to start a Symmetric-Server Central-00 pointing to DB0 and a Symmetric-Client Client-01 pointing to DB1. Similarly from App2, I'd like to start another instance of Symmetric-Server Central-00 pointing to DB0 and a Symmetric-Client Client-02 pointing to DB2. Obviously, App1 and App2 will be started in its own JVM.

So my question is this, Can I start two instances of the same Symmetric-Server Central-00 on two different VMs. Simply put, can i start two symmetricds server nodes that are accessing the same DB(also the same SYM tables generated within this DB.)?

This is the cofiguration that I inserted in the Central DB.

insert into sym_channel
(channel_id, processing_order, max_batch_size, enabled, description)
values('item', 1, 100000, 1, 'Item and pricing data');

insert into sym_node_group (node_group_id) values ('corp');
insert into sym_node_group (node_group_id) values ('store');
insert into sym_node_group (node_group_id) values ('store02');

insert into sym_node_group_link (source_node_group_id, target_node_group_id, data_event_action) values ('corp', 'store', 'W');
insert into sym_node_group_link (source_node_group_id, target_node_group_id, data_event_action) values ('corp', 'store02', 'W');
insert into sym_node_group_link (source_node_group_id, target_node_group_id, data_event_action) values ('store', 'corp', 'P');
insert into sym_node_group_link (source_node_group_id, target_node_group_id, data_event_action) values ('store02', 'corp', 'P');

insert into sym_trigger
(trigger_id,source_table_name,channel_id,last_update_time,create_time)
values('item','item','item',current_timestamp,current_timestamp);

insert into sym_router
(router_id,source_node_group_id,target_node_group_id,router_type,create_time,last_update_time)
values('corp_2_store', 'corp', 'store', 'default',current_timestamp, current_timestamp);

insert into sym_router
(router_id,source_node_group_id,target_node_group_id,router_type,create_time,last_update_time)
values('corp_2_store02', 'corp', 'store02', 'default',current_timestamp, current_timestamp);

insert into sym_trigger_router
(trigger_id,router_id,initial_load_order,last_update_time,create_time)
values('item','corp_2_store', 100, current_timestamp, current_timestamp);

insert into sym_trigger_router
(trigger_id,router_id,initial_load_order,last_update_time,create_time)
values('item','corp_2_store02', 100, current_timestamp, current_timestamp);

But when i start the instances it throws a Primary Key Violation Exception.

So could someone tell me whether this is possible or not? if so could you point out my mistakes?


来源: stackexchange

问:
How to make two buttons on the same row in eclipse programmatically?
```<code>LinearLayout table = (LinearLayout)findViewById(R.id.linearlayout);

btnControl = new Button(this);
    btnControl.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    btnControl.setPadding(0,40,0,40);//x,y,w,h
    btnControl.setBackgroundColor(Color.parseColor("#1C344E"));
    btnControl.setTextColor(Color.WHITE);
    setMargins(btnControl, 50, 50, 50, 50);

btnLogs = new Button(this);
        btnLogs.setLayoutParams(new LayoutParams(380, LayoutParams.WRAP_CONTENT));
        btnLogs.setPadding(0,40,0,40);//x,y,w,h
        btnLogs.setBackgroundColor(Color.parseColor("#1C344E"));
        btnLogs.setTextColor(Color.WHITE);
        setMargins(btnLogs, 50, 50, 50, 50);
        btnLogs.setId(5);
        btnLogs.setOnClickListener(this);

        btnTermLogs = new Button(this);
        btnTermLogs.setLayoutParams(new LayoutParams(380, LayoutParams.WRAP_CONTENT));
        btnTermLogs.setPadding(0,40,0,40);//x,y,w,h
        btnTermLogs.setBackgroundColor(Color.parseColor("#CC6675"));
        btnTermLogs.setTextColor(Color.WHITE);
        setMargins(btnLogs, 50, 50, 50, 50);
        btnTermLogs.setId(6);
        btnTermLogs.setOnClickListener(this);

btnLogout = new Button(this);
    btnLogout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    btnLogout.setPadding(0,40,0,40);//x,y,w,h
    btnLogout.setBackgroundColor(Color.parseColor("#CC6675"));
    btnLogout.setTextColor(Color.WHITE);

    table.addView(btnLogs);
        table.addView(btnTermLogs);
</code>```

I want the two buttons to be aligned together horizontally. However it just align themselves vertically which i dont want.

My buttons look like this:

what i want is to look like this:

答:
Horizontal linear layout supports left to right widgets approach, When
  app developer selects horizontal orientation in linear layout then it
  will automatically start adding components and widgets to left to
  right side after adding them. So here is the complete step by step
  tutorial for Creating horizontal linearlayout programmatically
  android.

Write this code

```<code>     //Creating LinearLayout.
     LinearLayout Horizontallinearlayout = new LinearLayout(this);

     //Setting up LinearLayout Orientation
     Horizontallinearlayout.setOrientation(LinearLayout.HORIZONTAL);

     LayoutParams Horizontallinearlayoutlayoutparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

     setContentView(Horizontallinearlayout, Horizontallinearlayoutlayoutparams);

     LayoutParams LayoutParamsview = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

     //Creating textview .
     Button button1 = new Button(this);
     Button button2 = new Button(this);

     //Adding text to TextView.
     button1.setText("First Button");
     button2.setText("Second Button");

     button1.setLayoutParams(LayoutParamsview);
     button2.setLayoutParams(LayoutParamsview);

     //Adding textview to linear layout using Add View function.
     Horizontallinearlayout.addView(button1);
     Horizontallinearlayout.addView(button2);
</code>```

Hope this helps you

ContentLicense: CC BY-SA 3.0

Body:
LinearLayout table = (LinearLayout)findViewById(R.id.linearlayout);

btnControl = new Button(this);
    btnControl.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    btnControl.setPadding(0,40,0,40);//x,y,w,h
    btnControl.setBackgroundColor(Color.parseColor("#1C344E"));
    btnControl.setTextColor(Color.WHITE);
    setMargins(btnControl, 50, 50, 50, 50);

btnLogs = new Button(this);
        btnLogs.setLayoutParams(new LayoutParams(380, LayoutParams.WRAP_CONTENT));
        btnLogs.setPadding(0,40,0,40);//x,y,w,h
        btnLogs.setBackgroundColor(Color.parseColor("#1C344E"));
        btnLogs.setTextColor(Color.WHITE);
        setMargins(btnLogs, 50, 50, 50, 50);
        btnLogs.setId(5);
        btnLogs.setOnClickListener(this);

        btnTermLogs = new Button(this);
        btnTermLogs.setLayoutParams(new LayoutParams(380, LayoutParams.WRAP_CONTENT));
        btnTermLogs.setPadding(0,40,0,40);//x,y,w,h
        btnTermLogs.setBackgroundColor(Color.parseColor("#CC6675"));
        btnTermLogs.setTextColor(Color.WHITE);
        setMargins(btnLogs, 50, 50, 50, 50);
        btnTermLogs.setId(6);
        btnTermLogs.setOnClickListener(this);

btnLogout = new Button(this);
    btnLogout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    btnLogout.setPadding(0,40,0,40);//x,y,w,h
    btnLogout.setBackgroundColor(Color.parseColor("#CC6675"));
    btnLogout.setTextColor(Color.WHITE);

    table.addView(btnLogs);
        table.addView(btnTermLogs);

I want the two buttons to be aligned together horizontally. However it just align themselves vertically which i dont want.

My buttons look like this:

what i want is to look like this:

Body:
Horizontal linear layout supports left to right widgets approach, When
  app developer selects horizontal orientation in linear layout then it
  will automatically start adding components and widgets to left to
  right side after adding them. So here is the complete step by step
  tutorial for Creating horizontal linearlayout programmatically
  android.

Write this code

     //Creating LinearLayout.
     LinearLayout Horizontallinearlayout = new LinearLayout(this);

     //Setting up LinearLayout Orientation
     Horizontallinearlayout.setOrientation(LinearLayout.HORIZONTAL);

     LayoutParams Horizontallinearlayoutlayoutparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

     setContentView(Horizontallinearlayout, Horizontallinearlayoutlayoutparams);

     LayoutParams LayoutParamsview = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

     //Creating textview .
     Button button1 = new Button(this);
     Button button2 = new Button(this);

     //Adding text to TextView.
     button1.setText("First Button");
     button2.setText("Second Button");

     button1.setLayoutParams(LayoutParamsview);
     button2.setLayoutParams(LayoutParamsview);

     //Adding textview to linear layout using Add View function.
     Horizontallinearlayout.addView(button1);
     Horizontallinearlayout.addView(button2);

Hope this helps you


问:
Mapping some HashMap Key/Values to a POJO
I have a HashMap of about 300 Key/String Value pairs and a POJO with about 12 string attributes where the names match the key names.

I would like to know how to get the HashMap values into the POJO?

I made this start which uses relfection and a loop but wasn't sure how to dynamically construct  the setter method name, and apparently reflection is a bad idea anyway...but FWIW:

```<code>    public void writeToFile(Map<String, String> currentSale) throws IOException {

    SaleExport saleExport = new SaleExport();

    Field[] fields = saleExport.getClass().getDeclaredFields();

       for (Field field : fields ) {
        System.out.println(field.getName());
        saleExport.set +field(saleExport.get(field));
</code>```

I have used map struct once before but it does not appear to support HashMaps.

UPDATE

This answer looks similar to what I want to do but gave a stack error on fields that didn't map:

```<code>Exception in thread "Thread-2" java.lang.IllegalArgumentException: Unrecognized field "Physical" (class com.SaleExport), not marked as ignorable (6 known properties: "date", "city", "surname", "streetName", "salesNo", "salesSurname"])
 at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.SalesExport["Physical"])
    at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:3738)
    at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:3656)
    at com.CSVExport.writeToFile(CSVExport.java:20)
    at com.JFrameTest.writefiletoDB(JFrameTest.java:135)
    at com.JFrameTest$FileWorkerThread.run(JFrameTest.java:947)
</code>```

To ignore the errors I tried :

```<code>mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
</code>```

But then nothing got mapped.

答:
I think you had the right idea in your code.  I understand your POJO to contain only a subset of the fields represented in the HashMap, so you just iterate through the fields, populating them from the HashMap as you find them.</p>

```<code>public SaleExport toSaleExport(Map<String,String> currentSale) {
    SaleExport saleExport=new SaleExport();
    Field[] fields=SaleExport.class.getDeclaredFields();
    for (Field field : fields) {
        String name=field.getName();
        if (currentSale.containsKey(name)) {
            field.set(saleExport, currentSale.get(name));
        }
    }
    return saleExport;
}
</code>```

Body:
I have a HashMap of about 300 Key/String Value pairs and a POJO with about 12 string attributes where the names match the key names.

I would like to know how to get the HashMap values into the POJO?

I made this start which uses relfection and a loop but wasn't sure how to dynamically construct  the setter method name, and apparently reflection is a bad idea anyway...but FWIW:

    public void writeToFile(Map<String, String> currentSale) throws IOException {

    SaleExport saleExport = new SaleExport();

    Field[] fields = saleExport.getClass().getDeclaredFields();

       for (Field field : fields ) {
        System.out.println(field.getName());
        saleExport.set +field(saleExport.get(field));

I have used map struct once before but it does not appear to support HashMaps.

UPDATE

This answer looks similar to what I want to do but gave a stack error on fields that didn't map:

Exception in thread "Thread-2" java.lang.IllegalArgumentException: Unrecognized field "Physical" (class com.SaleExport), not marked as ignorable (6 known properties: "date", "city", "surname", "streetName", "salesNo", "salesSurname"])
 at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.SalesExport["Physical"])
    at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:3738)
    at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:3656)
    at com.CSVExport.writeToFile(CSVExport.java:20)
    at com.JFrameTest.writefiletoDB(JFrameTest.java:135)
    at com.JFrameTest$FileWorkerThread.run(JFrameTest.java:947)

To ignore the errors I tried :

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

But then nothing got mapped.

Body:
I think you had the right idea in your code.  I understand your POJO to contain only a subset of the fields represented in the HashMap, so you just iterate through the fields, populating them from the HashMap as you find them.

public SaleExport toSaleExport(Map<String,String> currentSale) {
    SaleExport saleExport=new SaleExport();
    Field[] fields=SaleExport.class.getDeclaredFields();
    for (Field field : fields) {
        String name=field.getName();
        if (currentSale.containsKey(name)) {
            field.set(saleExport, currentSale.get(name));
        }
    }
    return saleExport;
}


问:
How to get output like this in Javascript/ES6
Let's say you have an array like this:

//Input
[1,2,3,4,5,6,7]

How to write the function which will get us the output of

//Output

```<code> Array1 = [1]
 Array2 = [1,2]
 Array3 = [1,2,3]
 Array4 = [1,2,3,4]
 Array5 = [1,2,3,4,5]
</code>```

And

//Output
1. [1,1,2,1,2,3,1,2,3,4...]

// tried this

```<code>for (i = 0; i < arr.length; i++) {
    arr = new Array(arr[i]);
}
</code>```

答:
Use forEach and for loop

var arr = [1, 2, 3, 4, 5, 6, 7];
var arrys = [];
//lopping over the array, and creating the new array and putting values
// equal to number of index
arr.forEach(function(item, index) {
  var tempArray = [];
  for (var m = 0; m <= index; m++) {
    tempArray.push(arr[m])
  }
  arrys.push(tempArray)
})
console.log(arrys)
// flat the previously created array
var flatten = [];
arrys.forEach(function(item) {
  item.forEach(function(item2) {
    flatten.push(item2)
  })
})
console.log(flatten)```

Body:
Let's say you have an array like this:

//Input
[1,2,3,4,5,6,7]

How to write the function which will get us the output of

//Output

 Array1 = [1]
 Array2 = [1,2]
 Array3 = [1,2,3]
 Array4 = [1,2,3,4]
 Array5 = [1,2,3,4,5]

And

//Output
1. [1,1,2,1,2,3,1,2,3,4...]

// tried this

for (i = 0; i < arr.length; i++) {
    arr = new Array(arr[i]);
}


问:
how to call connection in class functions
I establish connection in __construct() it is proper working but when I calling this->con variable in other function of class. it is not working.
I am inserting data in database but data not inserting into database while it's printing correct query in insertUserData().

```<code>Class RP_Common {

    private $_host = 'localhost';
    private $_username = 'root';
    private $_password = '12345';
    private $_database = 'shipment';

    protected $con;

    public function __construct()
    {
        if (!isset($this->con)) {

            $this->con = new mysqli($this->_host, $this->_username, $this->_password, $this->_database);

            if (!$this->con) {
                echo 'Cannot connect to database server';
                exit;
            }
        }

        return $this->con;
    }

    /**

    for inserting user_data
    */

    public function insertUserData($username,$usermobile,$useremail,$userpassword){

        //echo $this->con;

         echo $query="insert into user_table(user_name,user_mobile,user_email,user_password) values('$username',$usermobile,$useremail,$userpassword) ";

        $res=mysqli_query($this->con,$query);

        if($res){
            echo "data inserted successfully";
        }

    }
</code>```

答:
You should use prepared statements to avoid the pesky quoting issues.

```<code>$stmt = $this->con->prepare("INSERT INTO user_table(user_name, user_mobile, user_email,user_password) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $username, $usermobile, $useremail,$userpassword);
if($stmt->execute() === true){
 echo 'Data Successfully saved';
}
</code>```

Also do not save passwords in plaintext, it is highly unsafe. Use PHP's password_hash() and password_verify()

Body:
I establish connection in __construct() it is proper working but when I calling this->con variable in other function of class. it is not working.
I am inserting data in database but data not inserting into database while it's printing correct query in insertUserData().

Class RP_Common {

    private $_host = 'localhost';
    private $_username = 'root';
    private $_password = '12345';
    private $_database = 'shipment';

    protected $con;

    public function __construct()
    {
        if (!isset($this->con)) {

            $this->con = new mysqli($this->_host, $this->_username, $this->_password, $this->_database);

            if (!$this->con) {
                echo 'Cannot connect to database server';
                exit;
            }
        }

        return $this->con;
    }

    /**

    for inserting user_data
    */

    public function insertUserData($username,$usermobile,$useremail,$userpassword){

        //echo $this->con;

         echo $query="insert into user_table(user_name,user_mobile,user_email,user_password) values('$username',$usermobile,$useremail,$userpassword) ";

        $res=mysqli_query($this->con,$query);

        if($res){
            echo "data inserted successfully";
        }

    }

Body:
You should use prepared statements to avoid the pesky quoting issues.

$stmt = $this->con->prepare("INSERT INTO user_table(user_name, user_mobile, user_email,user_password) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $username, $usermobile, $useremail,$userpassword);
if($stmt->execute() === true){
 echo 'Data Successfully saved';
}

Also do not save passwords in plaintext, it is highly unsafe. Use PHP's password_hash() and password_verify()

ContentLicense: CC BY-SA 4.0


问:
Vectorising a for loop where logic spans rows
The table below shows an example of a strategy where a signal is generated in row 2 and then an opposite signal is generated in row 5.

```<code>     row     open_signal     close_signal      live
      1           0               0             0
      2           1               0             1
      3           0               0             1
      4           0               0             1
      5           0               1             0
      6           0               0             0
</code>```

I want to optimise the calculation of the live column.

Is there a way to vectorise this problem in either Pandas or Numpy for improved performance, generating the same result as the for loop example below?

```<code>import pandas as pd
from datetime import datetime

example = {'date': [str(datetime(2017,1,1)), str(datetime(2017,1,2)),str(datetime(2017,1,3)),str(datetime(2017,1,4)),str(datetime(2017,1,5)),str(datetime(2017,1,6)),
                    str(datetime(2017,1,7)), str(datetime(2017,1,8)),str(datetime(2017,1,9)), str(datetime(2017,1,10)),str(datetime(2017,1,11)), str(datetime(2017,1,12)),
                    str(datetime(2017,1,13)),str(datetime(2017,1,14))],
           'open':        [142.11, 142.87, 141.87, 142.11, 142.00, 142.41, 142.50, 142.75, 140.87, 141.25, 141.10, 141.15, 142.55, 142.75],
           'close':       [142.87, 141.87, 142.11, 142.00, 142.41, 142.50, 142.75, 140.87, 141.25, 141.10, 141.15, 142.55, 142.75, 142.11],
           'open_signal': [False,  False,  False,  False,  False,  True,  False,  False,  False,  False,  False,  False,  False,  False],
           'close_signal':[False,  False,  False,  False,  False,  False,  False,  False,  False,   True,  False,  False,  False,  False]
           }

data = pd.DataFrame(example)

in_trade = False
for i in data.iterrows():
    if i[1].open_signal:
        in_trade = True
    if i[1].close_signal:
        in_trade = False
    data.loc[i[0],'in_trade'] = in_trade
</code>```

答:
We can compare the cumulative sum i.e</p>

```<code>data['new'] = data['open_signal'].cumsum().ne(data['close_signal'].cumsum()).astype(int)

  row  open_signal  close_signal  live  new
0    1            0             0     0    0
1    2            1             0     1    1
2    3            0             0     1    1
3    4            0             0     1    1
4    5            0             1     0    0
5    6            0             0     0    0
</code>```

Body:
The table below shows an example of a strategy where a signal is generated in row 2 and then an opposite signal is generated in row 5.

     row     open_signal     close_signal      live
      1           0               0             0
      2           1               0             1
      3           0               0             1
      4           0               0             1
      5           0               1             0
      6           0               0             0

I want to optimise the calculation of the live column.

Is there a way to vectorise this problem in either Pandas or Numpy for improved performance, generating the same result as the for loop example below?

import pandas as pd
from datetime import datetime

example = {'date': [str(datetime(2017,1,1)), str(datetime(2017,1,2)),str(datetime(2017,1,3)),str(datetime(2017,1,4)),str(datetime(2017,1,5)),str(datetime(2017,1,6)),
                    str(datetime(2017,1,7)), str(datetime(2017,1,8)),str(datetime(2017,1,9)), str(datetime(2017,1,10)),str(datetime(2017,1,11)), str(datetime(2017,1,12)),
                    str(datetime(2017,1,13)),str(datetime(2017,1,14))],
           'open':        [142.11, 142.87, 141.87, 142.11, 142.00, 142.41, 142.50, 142.75, 140.87, 141.25, 141.10, 141.15, 142.55, 142.75],
           'close':       [142.87, 141.87, 142.11, 142.00, 142.41, 142.50, 142.75, 140.87, 141.25, 141.10, 141.15, 142.55, 142.75, 142.11],
           'open_signal': [False,  False,  False,  False,  False,  True,  False,  False,  False,  False,  False,  False,  False,  False],
           'close_signal':[False,  False,  False,  False,  False,  False,  False,  False,  False,   True,  False,  False,  False,  False]
           }

data = pd.DataFrame(example)

in_trade = False
for i in data.iterrows():
    if i[1].open_signal:
        in_trade = True
    if i[1].close_signal:
        in_trade = False
    data.loc[i[0],'in_trade'] = in_trade

Body:
We can compare the cumulative sum i.e

data['new'] = data['open_signal'].cumsum().ne(data['close_signal'].cumsum()).astype(int)

  row  open_signal  close_signal  live  new
0    1            0             0     0    0
1    2            1             0     1    1
2    3            0             0     1    1
3    4            0             0     1    1
4    5            0             1     0    0
5    6            0             0     0    0


问:
Websockets on production chat apps:
As I am beginning to work my way through web-sockets using Python (Django Channels in this case), I am beginning to wonder how companies scale chat applications.

Take this specific problem:
User A has a list of "group messages" that they are involved in. User A is capable of receiving notifications from each of the groups. Lets suppose User A has 5 different groups he would like real time notifications for.

Does User A have 5 separate web socket connections? This is easiest, but the bulkiest and surely wont scale (what if we had 20 chats per user). It is quite easy to make a Django Channels "Group" that listens and sends notifications to one specific group of people.

Does User A instead have 1 web socket connection taking all notifications from many different locations? If so, what is User A subscribing to on the backend? In Django Channels, a websocket is made when users subscribe to a "Group". If we wanted one user per "Group', this would seem counter intuitive. In this case, User A is subscribing to their own personal "Group" and other backend services are delivering messages to that specific "Group" based on other logic that is implemented when a message is received from any user using the service.

This is very verbose and text heavy, but it diagrams an interesting problem that has scaled for other companies in the past. I appreciate any information or insight!

(this is a list of the problems that I thought were basically the same (ignoring language and library use))
1. Websocket multiple Channels vs. One Channel + Server Side handling [GroupChat]

答:
first create a profile model:

```<code>class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name=_("user"))
    channel = models.CharField(unique=True, max_length=255, blank=True, null=True, verbose_name=_("channel")) # channel for notify user
</code>```

then create a message model:

```<code>class Message(models.Model):
    to_user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("user"))
    from_user = models.ForeignKey(User)
    text = models.TextField(blank=True, null=True)
</code>```

then use Django signals for sending notify:

```<code>@receiver(post_save, sender=Message)
def send_notify(instance, created, **kwargs):
    if created:
        Group('chat-{}'.format(instance.to_user.profile.channel)).send({'text': {'message': 'you have a new message'}})
</code>```

sorry for my english : ))

Title: Websockets on production chat apps:

Body:
first create a profile model:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name=_("user"))
    channel = models.CharField(unique=True, max_length=255, blank=True, null=True, verbose_name=_("channel")) # channel for notify user

then create a message model:

class Message(models.Model):
    to_user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("user"))
    from_user = models.ForeignKey(User)
    text = models.TextField(blank=True, null=True)

then use Django signals for sending notify:

@receiver(post_save, sender=Message)
def send_notify(instance, created, **kwargs):
    if created:
        Group('chat-{}'.format(instance.to_user.profile.channel)).send({'text': {'message': 'you have a new message'}})

sorry for my english : ))


问:
How to show rows which only column 2 is greater than 5 and column 4 is greater than 100?
In a dataframe for example

```<code>mtcars
               mpg cyl disp  hp drat   wt ...
Mazda RX4     21.0   6  160 110 3.90 2.62 ...
Mazda RX4 Wag 21.0   6  160  98 3.90 2.88 ...
Datsun 710    22.8   4  108  93 3.85 2.32 ...
</code>```

I want to show the rows where column 2 (cyl) is greater than 5 AND column 4 (hp) is greater than 100

therefore resulting in Mazda RX4

I know how to do it with 1 column

```<code>df[(df[,2]>5),]
</code>```

but i don't know how to chain the two together

答: dfSub = subset(df, cyl > 5 & hp > 100)

Body:
In a dataframe for example

mtcars
               mpg cyl disp  hp drat   wt ...
Mazda RX4     21.0   6  160 110 3.90 2.62 ...
Mazda RX4 Wag 21.0   6  160  98 3.90 2.88 ...
Datsun 710    22.8   4  108  93 3.85 2.32 ...

I want to show the rows where column 2 (cyl) is greater than 5 AND column 4 (hp) is greater than 100

therefore resulting in Mazda RX4

I know how to do it with 1 column

df[(df[,2]>5),]

but i don't know how to chain the two together

Body: dfSub = subset(df, cyl > 5 & hp > 100)


问:
Replacing value of atribut with count condition requirement
I have a data with is shown below :

```<code>count | type of vegetation

1     | Semak Belukar, Pepohonan

2     | Pakis, Sawit, Senduduk

1     | Pakis, Sawit, Ilalang, Akasia

49    | Sawit

15    | Pakis, Karet

17    | Semak Belukar
</code>```

I'd like to replace the value of type of vegetation which has value of count that is less than 15 into 'Others'. Example below :

```<code>count | type of vegetation

1     | Others

2     | Others

1     | Others

49    | Sawit

15    | Pakis, Karet

17    | Semak Belukar
</code>```

I use postgres SQL and haven't found the solution yet.
Any help is apreciated.

答:
Use this to view the expected result.

```<code>select count,
CASE WHEN count < 15 THEN 'Others'
ELSE type_of_vegetation
END as type_of_vegetation
FROM yourtable;
</code>```

To update your table as required, use this.

```<code>update yourtable SET type_of_vegetation = (
CASE WHEN count < 15 THEN 'Others'
    ELSE type_of_vegetation
 END );
</code>```

DEMO

Body:
I have a data with is shown below :

count | type of vegetation

1     | Semak Belukar, Pepohonan

2     | Pakis, Sawit, Senduduk

1     | Pakis, Sawit, Ilalang, Akasia

49    | Sawit

15    | Pakis, Karet

17    | Semak Belukar

I'd like to replace the value of type of vegetation which has value of count that is less than 15 into 'Others'. Example below :

count | type of vegetation

1     | Others

2     | Others

1     | Others

49    | Sawit

15    | Pakis, Karet

17    | Semak Belukar

I use postgres SQL and haven't found the solution yet.
Any help is apreciated.

Body:
Use this to view the expected result.

select count,
CASE WHEN count < 15 THEN 'Others'
ELSE type_of_vegetation
END as type_of_vegetation
FROM yourtable;

To update your table as required, use this.

update yourtable SET type_of_vegetation = (
CASE WHEN count < 15 THEN 'Others'
    ELSE type_of_vegetation
 END );

DEMO


问:
Javascript: issue with inheritance test (JS Definitive Guide book supplied code issue)
I'm new to Javascript. Usually write Python/PHP. Currently reading through JavaScript: The Definitive Guide: Activate Your Web Pages (Definitive Guides).

Part of the example code used I'm trying to figure out why it won't work, and the detailed explanation why too if possible, is below over properties getter/setters and inheritance.

The function I'm using:

```<code>function inherit(p) {
     if (p == null) throw TypeError();
     if (Object.create) return Object.create(p);
     var t = typeof p;
     if (t !== "object" && t !== "function") throw TypeError();
     function f() {};
     f.prototype = p;
     return new f();
}

var p = {
    x: 1.0,
    y: 1.0,
    get r() {
        return Math.sqrt(this.x*this.x + this.y*this.y);
    },
    set r(newvalue) {
        var oldvalue = Math.sqrt(this.x*this.x + this.y*this.y);
        var ratio = newvalue/oldvalue;
        this.x *= ratio;
        this.y *= ratio;
    },
        get theta() { return Math.atan2(this.y, this.x); }
};
</code>```

When I run a test. I can't see anything being inherited.

```<code>> var q = inherit(p)
undefined
> q
{}
> p
{ x: 1, y: 1, r: [Getter/Setter], theta: [Getter] }
</code>```

Why is this? I am currently using node v6.11.3 on Mac to run this.

Update:

Discovered how to show all values in an Object. Setting enumerable:True to an object will auto-display all values. What I was trying to figure out how to do. For any who also use Node.js.

答:
Use strange class definition and instance like inherit function is considered a bad practice, consider use js class ES6 definition, if you can, or function object definition or prototype if you have to use ES5.

Here how to use ES6 class definition

```<code>class p {

    constructor() {
        this.x = 1.0;
        this.y = 1.0;
    }

    get r() {
        return Math.sqrt(this.x*this.x + this.y*this.y);
    }

    set r(newvalue) {
        var oldvalue = Math.sqrt(this.x*this.x + this.y*this.y);
        var ratio = newvalue/oldvalue;
        this.x *= ratio;
        this.y *= ratio;
    }

    get theta() { return Math.atan2(this.y, this.x); }

}

var q = new p();
> q
{x: 1, y: 1}
> q.r = 6
> q.theta
</code>```

Body:
I'm new to Javascript. Usually write Python/PHP. Currently reading through JavaScript: The Definitive Guide: Activate Your Web Pages (Definitive Guides).

Part of the example code used I'm trying to figure out why it won't work, and the detailed explanation why too if possible, is below over properties getter/setters and inheritance.

The function I'm using:

function inherit(p) {
     if (p == null) throw TypeError();
     if (Object.create) return Object.create(p);
     var t = typeof p;
     if (t !== "object" && t !== "function") throw TypeError();
     function f() {};
     f.prototype = p;
     return new f();
}

var p = {
    x: 1.0,
    y: 1.0,
    get r() {
        return Math.sqrt(this.x*this.x + this.y*this.y);
    },
    set r(newvalue) {
        var oldvalue = Math.sqrt(this.x*this.x + this.y*this.y);
        var ratio = newvalue/oldvalue;
        this.x *= ratio;
        this.y *= ratio;
    },
        get theta() { return Math.atan2(this.y, this.x); }
};

When I run a test. I can't see anything being inherited.

> var q = inherit(p)
undefined
> q
{}
> p
{ x: 1, y: 1, r: [Getter/Setter], theta: [Getter] }

Why is this? I am currently using node v6.11.3 on Mac to run this.

Update:

Discovered how to show all values in an Object. Setting enumerable:True to an object will auto-display all values. What I was trying to figure out how to do. For any who also use Node.js.

Body:
Use strange class definition and instance like inherit function is considered a bad practice, consider use js class ES6 definition, if you can, or function object definition or prototype if you have to use ES5.

Here how to use ES6 class definition

class p {

    constructor() {
        this.x = 1.0;
        this.y = 1.0;
    }

    get r() {
        return Math.sqrt(this.x*this.x + this.y*this.y);
    }

    set r(newvalue) {
        var oldvalue = Math.sqrt(this.x*this.x + this.y*this.y);
        var ratio = newvalue/oldvalue;
        this.x *= ratio;
        this.y *= ratio;
    }

    get theta() { return Math.atan2(this.y, this.x); }

}

var q = new p();
> q
{x: 1, y: 1}
> q.r = 6
> q.theta


问:
Insert objects without matching column name
This is probably a silly question, but I am new to node and postgresql, so I am struggling.

I am trying to use pgp.helpers.insert to insert multiple objects into the database, as the example bellow:

users = [{mycolumn:{name: 'John', age:23}}, {mycolumn:{name: 'Mike', age: 30}}];
query = pgp.helpers.insert(users, ['mycolumn:json'], 'mytable');
// insert into "mytable"("mycolumn") values('{"name":"John","age":23}'),('{"name":"Mike","age":30}')
```

<p>The code above inserts into <code>mytable</code> 2 rows with <code>mycolumn</code> as a jsonb.</p>

<p>But I am trying to insert straight into <code>mycolumn</code> the values inside an array of objects, without wrapping my original object, such as:</p>

<pre class="lang-js prettyprint-override"><code>users = [{name: 'John', age:23}, {name: 'Mike', age: 30}];
query = pgp.helpers.insert(users, ['mycolumn:json'], 'mytable');
// Error: Property 'mycolumn' doesn't exist.
</code>```

Of course it doesn't work, since the object doesn't contain a mycolumn attribute. But I think it is not elegant to iterate in my array wrapping the original object with the column name, specially since I am working with millions of rows (working in batches, of course).

Thanks in advance.

答:
You can use the following definition for your column, as per the Column syntax:

```<code>{
  name: 'mycolumn',
  init: c => c.source // use the source object itself
}
</code>```

i.e.

```<code>const cs = new pgp.helpers.ColumnSet([
    {
      name: 'mycolumn',
      init: c => c.source
    }
], {table: 'mytable'});
</code>```

and then use it:

```<code>const query = pgp.helpers.insert(users, cs);
</code>```

Note that we are not specifying the modifier - mod: ':json', because we are returning an object from init, and objects are formatted as JSON by default.

Body:
This is probably a silly question, but I am new to node and postgresql, so I am struggling.

I am trying to use pgp.helpers.insert to insert multiple objects into the database, as the example bellow:

users = [{mycolumn:{name: 'John', age:23}}, {mycolumn:{name: 'Mike', age: 30}}];
query = pgp.helpers.insert(users, ['mycolumn:json'], 'mytable');
// insert into "mytable"("mycolumn") values('{"name":"John","age":23}'),('{"name":"Mike","age":30}')

The code above inserts into mytable 2 rows with mycolumn as a jsonb.

But I am trying to insert straight into mycolumn the values inside an array of objects, without wrapping my original object, such as:

users = [{name: 'John', age:23}, {name: 'Mike', age: 30}];
query = pgp.helpers.insert(users, ['mycolumn:json'], 'mytable');
// Error: Property 'mycolumn' doesn't exist.

Of course it doesn't work, since the object doesn't contain a mycolumn attribute. But I think it is not elegant to iterate in my array wrapping the original object with the column name, specially since I am working with millions of rows (working in batches, of course).

Thanks in advance.

Body:
You can use the following definition for your column, as per the Column syntax:

{
  name: 'mycolumn',
  init: c => c.source // use the source object itself
}

i.e.

const cs = new pgp.helpers.ColumnSet([
    {
      name: 'mycolumn',
      init: c => c.source
    }
], {table: 'mytable'});

and then use it:

const query = pgp.helpers.insert(users, cs);

Note that we are not specifying the modifier - mod: ':json', because we are returning an object from init, and objects are formatted as JSON by default.


答:
You can use functions like Array#map and Array#slice to easily create the first function, and use Array#concat with spread syntax to flatten a 2D array.

function prefixes(array) {
  return array.map((_, index) => array.slice(0, index + 1));
}

function flatten(array) {
  return [].concat(...array);
}

const output = prefixes([1,2,3,4,5,6,7]);
console.log(output);
console.log(flatten(output));```

Title: How to get output like this in Javascript/ES6


问:
configure: error: can not find cURL or libcurl... go to http://curl.haxx.se/ to download and then install it first
```<code>configure: error: can not find cURL or libcurl... go to http://curl.haxx.se/ to download and then install it first
</code>```

Is the error I am getting when trying to run ./configure for TclCurl (which is what I really need), but I have curl installed on CentOS through yum, but it still gives this error.  How can I fix it?

答: Install curl-devel or libcurl-devel.

ContentLicense: CC BY-SA 2.5

Body:
configure: error: can not find cURL or libcurl... go to http://curl.haxx.se/ to download and then install it first

Is the error I am getting when trying to run ./configure for TclCurl (which is what I really need), but I have curl installed on CentOS through yum, but it still gives this error.  How can I fix it?

Body: Install curl-devel or libcurl-devel.


问:
Print session variables in a

I am trying to print session variables that I get from page-1.php into page-2.php into a div. I have managed to get the values via session from page-1 to page-2 but I am not able to print the values into a div(one div) that comes right beneath the menu. When I echo the output, it gets printed on the top-left. Code is mentioned below:

```<code> .output{
    height:50px;
    width:150px;
    margin-top:10px;
    border: 1px solid black;
    }
    </style>
    <title>Untitled Document</title>
    </head>

    <body>
    <?php
    session_start();
    echo '<div class="output">$_SESSION["val-2"]</div>';    //get session variables
    echo '<div class="output">$_SESSION["val-1"]</div>';
    echo '<div class="output">$_SESSION["val"]</div>';
    ?>

    <div><h1>Page-2</h1></div>
    <div class="menu">
        <ul>
            <li><a href="page-1.php">Page-1</a></li>
            <li><a href="page-2.php">Page-2</a></li>
        </ul>
    </div>
    <div class="output"></div>
    </body>
</code>```

Output I am getting:

答:
You need to have session_start() before ANYthing, even before the head tag or <!doctype>.

Change you code to:

```<code><?php session_start(); ?>

<!doctype>
<head>
....
.output{
    height:50px;
    width:150px;
    margin-top:10px;
    border: 1px solid black;
    }
    </style>
    <title>Untitled Document</title>
</head>

<body>
    <?php
    session_start();
    echo '<div class="output">';
      echo $_SESSION["val-2"];
      echo $_SESSION["val-1"];
      echo $_SESSION["val"];
    echo "</div>";
    ?>
....
</code>```

Title: Print session variables in a <div>

Body:
I am trying to print session variables that I get from page-1.php into page-2.php into a div. I have managed to get the values via session from page-1 to page-2 but I am not able to print the values into a div(one div) that comes right beneath the menu. When I echo the output, it gets printed on the top-left. Code is mentioned below:

 .output{
    height:50px;
    width:150px;
    margin-top:10px;
    border: 1px solid black;
    }
    </style>
    <title>Untitled Document</title>

    <?php
    session_start();
    echo '
$_SESSION["val-2"]
';    //get session variables
    echo '
$_SESSION["val-1"]
';
    echo '
$_SESSION["val"]
';
    ?>

Page-2

Page-1

Page-2

Output I am getting:

Body:
You need to have session_start() before ANYthing, even before the head tag or <!doctype>.

Change you code to:

<?php session_start(); ?>

<!doctype>
<head>
....
.output{
    height:50px;
    width:150px;
    margin-top:10px;
    border: 1px solid black;
    }
    </style>
    <title>Untitled Document</title>
</head>

<body>
    <?php
    session_start();
    echo '<div class="output">';
      echo $_SESSION["val-2"];
      echo $_SESSION["val-1"];
      echo $_SESSION["val"];
    echo "</div>";
    ?>
....


问:
How to display phone number and pincode separately in email body using PHP-Mailer
Email body displaying with text,numbers,pincode. I want to separate my phone number and pincode to display in bottom of email body. I tried line breaks and
 no luck.

Php code :

```<code>  <?php
  $msg = "";
  $mail->Body = $body . $phone;
  $mail->Body = $pincode;
  $mail->Body = $phone;

  if (isset($_POST['submit'])) {

    require 'phpmailer/PHPMailerAutoload.php';

    function sendemail($to, $from, $fromName, $body, $phone, $pincode) {
      $mail = new PHPMailer();
      $mail->setFrom($from, $fromName);
      $mail->addAddress($to);
      $mail->Subject = 'Naukriglobal.com - Email - Resume';
      $mail->Body = $body . $phone . $pincode;
      $mail->isHTML(false);

      return $mail->send();
    }

    $name = $_POST['username'];
    $email = $_POST['email'];
    $body = $_POST['body'];
    $phone = $_POST['phone'];
    $pincode = $_POST['pincode'];

    if (sendemail('hameed.basha278@gmail.com', $email, $name, $body, $phone, $pincode)) {
        $msg = 'Email sent!';
        sendemail('hamidsince1990@gmail.com', $email, $name, $body, $phone, $pincode);
      } else
        $msg = 'Email failed!';
    }
?>
</code>```

答:
This is the line that actually constructs the content of your message:

```<code>$mail->Body = $body . $phone . $pincode;
</code>```

Here you are just concatenating all 3 fields with no spaces or line breaks.  You can add newlines between those fields like this:

```<code>$mail->Body = $body . "\n" . $phone . "\n" . $pincode;
</code>```

Your
s did not work because you are sending a plain text message (you have specified $mail->isHTML(false);).  If you want to use HTML and
, first set isHTML(true), but do that before you set the body:

```<code>function sendemail($to, $from, $fromName, $body, $phone, $pincode) {
    $mail = new PHPMailer();
    $mail->isHTML(true);
    $mail->setFrom($from, $fromName);
    $mail->addAddress($to);
    $mail->Subject = 'Naukriglobal.com - Email - Resume';
    $mail->Body = $body . "<br>" . $phone . "<br>" . $pincode;
    return $mail->send();
}
</code>```

Or even:

```<code>$mail->Body = $body . "<br>Phone number: " . $phone . "<br>PIN: " . $pincode;
</code>```

BTW you should remove this code you have at the top:

```<code>$msg = "";
$mail->Body = $body . $phone;
$mail->Body = $pincode;
$mail->Body = $phone;
</code>```

$mail does not seem to be defined at that point, and anyway you create a new instance of $mail inside your sendemail() function so whatever you set up there will have no effect.  Remove that code to avoid confusion.

Body:
Email body displaying with text,numbers,pincode. I want to separate my phone number and pincode to display in bottom of email body. I tried line breaks and
 no luck.

Php code :

  <?php
  $msg = "";
  $mail->Body = $body . $phone;
  $mail->Body = $pincode;
  $mail->Body = $phone;

  if (isset($_POST['submit'])) {

    require 'phpmailer/PHPMailerAutoload.php';

    function sendemail($to, $from, $fromName, $body, $phone, $pincode) {
      $mail = new PHPMailer();
      $mail->setFrom($from, $fromName);
      $mail->addAddress($to);
      $mail->Subject = 'Naukriglobal.com - Email - Resume';
      $mail->Body = $body . $phone . $pincode;
      $mail->isHTML(false);

      return $mail->send();
    }

    $name = $_POST['username'];
    $email = $_POST['email'];
    $body = $_POST['body'];
    $phone = $_POST['phone'];
    $pincode = $_POST['pincode'];

    if (sendemail('hameed.basha278@gmail.com', $email, $name, $body, $phone, $pincode)) {
        $msg = 'Email sent!';
        sendemail('hamidsince1990@gmail.com', $email, $name, $body, $phone, $pincode);
      } else
        $msg = 'Email failed!';
    }
?>

Body:
This is the line that actually constructs the content of your message:

$mail->Body = $body . $phone . $pincode;

Here you are just concatenating all 3 fields with no spaces or line breaks.  You can add newlines between those fields like this:

$mail->Body = $body . "\n" . $phone . "\n" . $pincode;

Your <br>s did not work because you are sending a plain text message (you have specified $mail->isHTML(false);).  If you want to use HTML and <br>, first set isHTML(true), but do that before you set the body:

function sendemail($to, $from, $fromName, $body, $phone, $pincode) {
    $mail = new PHPMailer();
    $mail->isHTML(true);
    $mail->setFrom($from, $fromName);
    $mail->addAddress($to);
    $mail->Subject = 'Naukriglobal.com - Email - Resume';
    $mail->Body = $body . "<br>" . $phone . "<br>" . $pincode;
    return $mail->send();
}

Or even:

$mail->Body = $body . "<br>Phone number: " . $phone . "<br>PIN: " . $pincode;

BTW you should remove this code you have at the top:

$msg = "";
$mail->Body = $body . $phone;
$mail->Body = $pincode;
$mail->Body = $phone;

$mail does not seem to be defined at that point, and anyway you create a new instance of $mail inside your sendemail() function so whatever you set up there will have no effect.  Remove that code to avoid confusion.


问:
Finding an integer key of a Python dict that is closest to a given integer
I have a dictionary where the keys are integers.  I have another integer.  I want to find the value corresponding to the key in the dict that is closest to the given integer.  Is there an efficient way to do this?

Maybe a different data structure (binary tree) would be more efficient?

答:
```<code>dd = {2:'x', 6:'y', 100000:'z', 77:'w'}
ikey = 99
low = max([d for d in dd if d<= ikey])
high = min([d for d in dd if d>= ikey])
nearkey = low if ikey - low <= high - ikey else high
nearkey

77
</code>```


问:
<merge/> in custom View xml layout
I have the following custom view which is based on RelativeLayout:

```<code>public class LearningModeRadioButton extends
                                        RelativeLayout
                                     implements
                                        Checkable,
                                        View.OnClickListener {

    private void init(Context context, AttributeSet attrs) {
        LayoutInflater.from(context).inflate(R.layout.rb_learning_mode, this, true);
    }
}
</code>```

R.layout.rb_learning_mode contents are:

```<code><?xml version="1.0" encoding="utf-8"?>

<merge
        xmlns:android="http://schemas.android.com/apk/res/android"
        >

    <RadioButton
            android:id="@+id/rb"
            android:button="@drawable/sel_rb_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

    <TextView
            android:id="@+id/tv_mode_title"
            style="@style/text_regular"
            android:layout_toRightOf="@+id/rb"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

    <TextView
            android:id="@+id/tv_description"
            style="@style/text_small"
            android:layout_below="@+id/tv_mode_title"
            android:layout_alignLeft="@+id/tv_mode_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

</merge>
</code>```

It sort of works, but layout parameters (layout_xxx) are ignored. I could use another <RelativeLayout/> as root element of the layout but I want to avoid having extra level in view hierarchy.

So the question is: How do I make layout attributes inside <merge/> work?

答:
For anyone that might still be struggling with this, you should specify the parentTag attribute inside the merge tag. You will also need to specify layout_height and layout_width to make it work.

    <merge
        tools:parentTag="android.widget.RelativeLayout"
        tools:layout_width="match_parent"
        tools:layout_height="match_parent"
    >
    // Child Views
    </merge>
```

The editor should display everything properly now.

Title: <merge/> in custom View xml layout

Body:
I have the following custom view which is based on RelativeLayout:

public class LearningModeRadioButton extends
                                        RelativeLayout
                                     implements
                                        Checkable,
                                        View.OnClickListener {

    private void init(Context context, AttributeSet attrs) {
        LayoutInflater.from(context).inflate(R.layout.rb_learning_mode, this, true);
    }
}

R.layout.rb_learning_mode contents are:

<?xml version="1.0" encoding="utf-8"?>

<merge
        xmlns:android="http://schemas.android.com/apk/res/android"
        >

    <RadioButton
            android:id="@+id/rb"
            android:button="@drawable/sel_rb_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

    <TextView
            android:id="@+id/tv_mode_title"
            style="@style/text_regular"
            android:layout_toRightOf="@+id/rb"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

    <TextView
            android:id="@+id/tv_description"
            style="@style/text_small"
            android:layout_below="@+id/tv_mode_title"
            android:layout_alignLeft="@+id/tv_mode_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

</merge>

It sort of works, but layout parameters (layout_xxx) are ignored. I could use another <RelativeLayout/> as root element of the layout but I want to avoid having extra level in view hierarchy.

So the question is: How do I make layout attributes inside <merge/> work?

Body:
For anyone that might still be struggling with this, you should specify the parentTag attribute inside the merge tag. You will also need to specify layout_height and layout_width to make it work.

    <merge
        tools:parentTag="android.widget.RelativeLayout"
        tools:layout_width="match_parent"
        tools:layout_height="match_parent"
    >
    // Child Views
    </merge>

The editor should display everything properly now.


问:
Clearcase on new Windows Domain
We have migrated our Windows user PCs to new Domain.

For each clearcase user, We need to do below work manually.

```<code>1. Albd service account and password to be changed in Service window category.
2. In Registry domain name need to be changed.
3. Old domain snapshot views needs to be find and  unregistred.
4. Again same snapshot views need to be registered for New hostname.
5.Fix_Prot needs to be run to change snapshot views owner and group name.
</code>```

So for this do we have any utility/tool?Kindly advise me.

答:
There is no native utility, but it can be scripted, and executed (provided the user can launch that script as Administrator, in order to have access to regedit and other admin tools)

For changing the albs service account in the Windows service, you would use sc (after stopping the service with net stop): see "How do I determine via Windows command line whether ALBD service is running?"

And here is an example for fix_prot using aliases.

Title: Clearcase on new Windows Domain

Body:
We have migrated our Windows user PCs to new Domain.

For each clearcase user, We need to do below work manually.

1. Albd service account and password to be changed in Service window category.
2. In Registry domain name need to be changed.
3. Old domain snapshot views needs to be find and  unregistred.
4. Again same snapshot views need to be registered for New hostname.
5.Fix_Prot needs to be run to change snapshot views owner and group name.

So for this do we have any utility/tool?Kindly advise me.


问:
How do you add a homepage to your browser?
This is what i mean

When searching the internet when you type in the search bar what ever your homepage is it searches on your homepage.

for example you search dogs

this is what it does.

It does
https://www.google.com.ph/search?= + dogs

I would like to know how to do that except adding another textbox for it.

答:
Put your url in this format, for each more string you want to search +string it at the end. Navigating to that link will directly give you the page without having to set it as homepage. I guess thats what you are trying to do?

https://www.google.com/search?q=dogs+cats

https://www.google.com/search?q=dogs+cats+stringNew


问:
how to prevent infinite while loop in python 3
I am creating a program that plays the game pig dice. It should do the following:
1. Select whether the user or the computer plays the first turn.
2. If computer starts first, computer plays one turn
3. Repeat as long as computer score is less than 100:
a. User plays one turn.
b. If user’s score reaches 100, exit loop
c. Computer plays one turn.
4. Print results.
My problem is that when I run the program, there is an infinite loop, and I am not sure where it is running into this problem. Could anyone point out where the problem is occurring and possibly make suggestions as to how to prevent this? Pointing out any other errors is also appreciated as I am new to python.

```<code>from random import randint

def print_scores(uscore, cscore):
    uscore = 0
    cscore = 0

    print(uscore, cscore)

def roll_two_dice():
    roll1 = randint(1, 6)
    roll2 = randint(1, 6)

    if roll1 or roll2 == 1:
        return 0

    elif roll1 and roll2 == 1:
        return 25
    else:
        return roll1 + roll2

def computerTurn(score):

    turn_score = 0
    while score + turn_score < 100 and turn_score < 20:
        roll = roll_two_dice()
        if roll == 0:
            return 0
        score = roll + turn_score
    return turn_score

def userTurn(score):
    turn_score = 0
    while score + turn_score < 100 or user == hold:
        roll = roll_two_dice()
        if roll == 0:
            return 0
        score = roll + turn_score
    return turn_score

def final_result(uscore, cscore):
    uscore = 0
    cscore = 0
    print('Final results:{}'.format(uscore, cscore))
    if uscore >= 100:
        print('You win')
    else:
        print('Computer wins')

def main():
    c_score = 0
    u_score = 0
    if randint(0, 1) == 0:
        print('Computer starts')
        c_turn = computerTurn(c_score) + c_score
    while c_score < 100:
        print('Current scores')
        print_scores(u_score, c_score)
        u_turn = userTurn(u_score) + u_score
        if u_score >= 100:
            exit
        c_turn = computerTurn(c_score)
        print(c_turn)
        c_score = c_score + c_turn
    final_result(u_score, c_score)

main()
</code>```

codepart1

codepart2

答:
Your problem is

```<code>if u_score >= 100:
    exit
</code>```

"exit" isn't the keyword to leave a loop, it's "break". If you actually want the program to terminate, you need to call the method with exit().

Body:
I am creating a program that plays the game pig dice. It should do the following:
1. Select whether the user or the computer plays the first turn.
2. If computer starts first, computer plays one turn
3. Repeat as long as computer score is less than 100:
a. User plays one turn.
b. If user’s score reaches 100, exit loop
c. Computer plays one turn.
4. Print results.
My problem is that when I run the program, there is an infinite loop, and I am not sure where it is running into this problem. Could anyone point out where the problem is occurring and possibly make suggestions as to how to prevent this? Pointing out any other errors is also appreciated as I am new to python.

from random import randint

def print_scores(uscore, cscore):
    uscore = 0
    cscore = 0

    print(uscore, cscore)

def roll_two_dice():
    roll1 = randint(1, 6)
    roll2 = randint(1, 6)

    if roll1 or roll2 == 1:
        return 0

    elif roll1 and roll2 == 1:
        return 25
    else:
        return roll1 + roll2

def computerTurn(score):

    turn_score = 0
    while score + turn_score < 100 and turn_score < 20:
        roll = roll_two_dice()
        if roll == 0:
            return 0
        score = roll + turn_score
    return turn_score

def userTurn(score):
    turn_score = 0
    while score + turn_score < 100 or user == hold:
        roll = roll_two_dice()
        if roll == 0:
            return 0
        score = roll + turn_score
    return turn_score

def final_result(uscore, cscore):
    uscore = 0
    cscore = 0
    print('Final results:{}'.format(uscore, cscore))
    if uscore >= 100:
        print('You win')
    else:
        print('Computer wins')

def main():
    c_score = 0
    u_score = 0
    if randint(0, 1) == 0:
        print('Computer starts')
        c_turn = computerTurn(c_score) + c_score
    while c_score < 100:
        print('Current scores')
        print_scores(u_score, c_score)
        u_turn = userTurn(u_score) + u_score
        if u_score >= 100:
            exit
        c_turn = computerTurn(c_score)
        print(c_turn)
        c_score = c_score + c_turn
    final_result(u_score, c_score)

main()

codepart1

codepart2

Body:
Your problem is

if u_score >= 100:
    exit

"exit" isn't the keyword to leave a loop, it's "break". If you actually want the program to terminate, you need to call the method with exit().


问:
Concatenate character to __VA_ARGS__ in a macro redefining printf
I'm developing an embedded application that uses a library for interfacing with a SPI NAND memory chip.  The library provided uses a print function in which I, as the applications developer, must override for my specific platform.

For instance, they use the function printf_ extensively in their code.

I redefine it as such, to get the print function to print over the serial interface

```<code>#define printf_(...) serial.printf(__VA_ARGS__)
</code>```

It works fine, except that on this platform, you need to supply a carriage return ("\r") for a newline.  So right now, when the library is called, the formatting is horrible.

I'd like to append a "\r" to the end of whatever is supplied to the print function.  Like

```<code>#define printf_(...) serial.printf(__VA_ARGS__##"\r")
</code>```

Obviously that doesn't work.

I'm really not familiar with, and have sort of a hard time understanding variadic functions in C, so this would provide me with a little learning opportunity if I could figure this out, or at least I would learn if this is not possible.

I also can't just wrap the function using va_lists and vsprintfs because my platform does not support this (and I'd rather redefine it in a macro, as a performance/stylistic choice, personally).

Is there a way to do this?

答:
Perhaps you could just output '\r' after the call to serial.printf ?

```<code>#define printf_(...) do { serial.printf(__VA_ARGS__); serial.printf("\r"); } while(0)
</code>```

Body:
I'm developing an embedded application that uses a library for interfacing with a SPI NAND memory chip.  The library provided uses a print function in which I, as the applications developer, must override for my specific platform.

For instance, they use the function printf_ extensively in their code.

I redefine it as such, to get the print function to print over the serial interface

#define printf_(...) serial.printf(__VA_ARGS__)

It works fine, except that on this platform, you need to supply a carriage return ("\r") for a newline.  So right now, when the library is called, the formatting is horrible.

I'd like to append a "\r" to the end of whatever is supplied to the print function.  Like

#define printf_(...) serial.printf(__VA_ARGS__##"\r")

Obviously that doesn't work.

I'm really not familiar with, and have sort of a hard time understanding variadic functions in C, so this would provide me with a little learning opportunity if I could figure this out, or at least I would learn if this is not possible.

I also can't just wrap the function using va_lists and vsprintfs because my platform does not support this (and I'd rather redefine it in a macro, as a performance/stylistic choice, personally).

Is there a way to do this?

Body:
Perhaps you could just output '\r' after the call to serial.printf ?

#define printf_(...) do { serial.printf(__VA_ARGS__); serial.printf("\r"); } while(0)


问:
NSTableView display Image in one cell
I might be asking very simple question, but i am not able to get how to get rid of this,
the requirement is,

Table should display image and some text next to that. To do that, i have added two columns in the table

NSTableView should be transparent. To do that, i have made a CustomNSTableView class, inside override drawRect method for not to draw background, and tell cell not to drawBackground.

Now the next hurdle is how to display an image, i had to override/handled following method

.

```<code>- (NSCell *)tableView:(NSTableView *)tableView dataCellForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{

    NSImage *pCellImage = // Get a valid Image ;

    if(tableColumn == nil ) return nil;

    NSString *colName = [tableColumn identifier];
    if([colName isEqualToString:@"firstColumn"]){
        NSCell *pCell = [[NSCell alloc]initImageCell:pCellImage];
        return pCell;
    }else{
        NSCell *pCell = [[NSCell alloc]initTextCell:@"Some text"];
        return pCell;

    }
}
</code>```

i added tableColumn == nil condition, as in the documentation its given, first time for each row , this will be called with tableCOlumn nil when i need to set a single column for entire row, but if i return its crashing with the comment BAD_ACCESS,

Now my question is how to handle nil condition,
Also in this function after setting NSCell for both Column it goes to another delegate function

```<code>- (id) tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
</code>```

I believe, after setting dataSet properly i don't need to use this function,

With the following implementation its crashing, but i am not able to figure it out, what is wrong ,

i am setting proper dataSource and delegate,

答:
Have you tried calling setBackgroundColor and passing the clear colour?

```<code>[myTableView setBackgroundColor:[[NSColor clearColor]];
</code>```

If you use this method, remember to tell the surrounding NSScrollView not to draw it's background.

Alternatively, consider providing the table's background as a CALayer.

With regard to drawing the image and text in a single column, Apple's developer relations have published a custom NSCell, ImageAndTextCell. You can use this cell with NSTableView and NSOutlineView instances. This custom cell deals with drawing a image and text within a single column.

Title: NSTableView display Image in one cell

Body:
I might be asking very simple question, but i am not able to get how to get rid of this,
the requirement is,

Table should display image and some text next to that. To do that, i have added two columns in the table

NSTableView should be transparent. To do that, i have made a CustomNSTableView class, inside override drawRect method for not to draw background, and tell cell not to drawBackground.

Now the next hurdle is how to display an image, i had to override/handled following method

.

- (NSCell *)tableView:(NSTableView *)tableView dataCellForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{

    NSImage *pCellImage = // Get a valid Image ;

    if(tableColumn == nil ) return nil;

    NSString *colName = [tableColumn identifier];
    if([colName isEqualToString:@"firstColumn"]){
        NSCell *pCell = [[NSCell alloc]initImageCell:pCellImage];
        return pCell;
    }else{
        NSCell *pCell = [[NSCell alloc]initTextCell:@"Some text"];
        return pCell;

    }
}

i added tableColumn == nil condition, as in the documentation its given, first time for each row , this will be called with tableCOlumn nil when i need to set a single column for entire row, but if i return its crashing with the comment BAD_ACCESS,

Now my question is how to handle nil condition,
Also in this function after setting NSCell for both Column it goes to another delegate function

- (id) tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex

I believe, after setting dataSet properly i don't need to use this function,

With the following implementation its crashing, but i am not able to figure it out, what is wrong ,

i am setting proper dataSource and delegate,

Body:
Have you tried calling setBackgroundColor and passing the clear colour?

[myTableView setBackgroundColor:[[NSColor clearColor]];

If you use this method, remember to tell the surrounding NSScrollView not to draw it's background.

Alternatively, consider providing the table's background as a CALayer.

With regard to drawing the image and text in a single column, Apple's developer relations have published a custom NSCell, ImageAndTextCell. You can use this cell with NSTableView and NSOutlineView instances. This custom cell deals with drawing a image and text within a single column.


问:
Ruby No such file or directory @ dir_initialize even when the directory exist
I have :

```<code>ruby -v
=>ruby 2.3.1p112 (2016-04-26) [x86_64-linux-gnu]

puts arg_provide
=>/home/user/Bureau/Clips graver

input_file_or_directory = Shellwords.shellescape(arg_provide).to_s

puts input_file_or_directory
=>/home/user/Bureau/Clips\ graver
</code>```

When i do

```<code>Dir.foreach("/home/user/Bureau/Clips\ graver") do |media|
=> IT'S WORKS FINE!
</code>```

But when i do

```<code>Dir.foreach(input_file_or_directory) do |media|
=>Raise Uncaught exception: No such file or directory @ dir_initialize
- /home/user/Bureau/Clips\ graver
</code>```

I can't figure it out
Somebody help me please ?

答:
Replace

```<code>Dir.foreach(arg_provideinput_file_or_directory)
</code>```

with

```<code>Dir.foreach(arg_provide.to_s)
</code>```

Body:
I have :

ruby -v
=>ruby 2.3.1p112 (2016-04-26) [x86_64-linux-gnu]

puts arg_provide
=>/home/user/Bureau/Clips graver

input_file_or_directory = Shellwords.shellescape(arg_provide).to_s

puts input_file_or_directory
=>/home/user/Bureau/Clips\ graver

When i do

Dir.foreach("/home/user/Bureau/Clips\ graver") do |media|
=> IT'S WORKS FINE!

But when i do

Dir.foreach(input_file_or_directory) do |media|
=>Raise Uncaught exception: No such file or directory @ dir_initialize
- /home/user/Bureau/Clips\ graver

I can't figure it out
Somebody help me please ?

Body:
Replace

Dir.foreach(arg_provideinput_file_or_directory)

with

Dir.foreach(arg_provide.to_s)


问:
hidden field passes all params as strings
I have a controller called "Questions" with two actions, "practice" and "grade" both are get routes, the practice view renders a small sample of of Questions and uses forms to get user answers using submit to get the "grade path"

to grade it, I need the record objects to be passed as an array, but when passed using the hidden field I get the reference numbers as strings and not the actual object. how do i get the object so I can call question_object.answer

controllers/questions.rb

```<code>def practice
   @questions = Questions.find(params[:id])
   @sample_array =  @questions.multiple_choices.sample(params[:number_of_multiple_choices].to_i)
   @sample_array += @questions.true_falses.sample(params[:number_of_true_falses].to_i)
   @user_answers = Array.new(@questions.size, 1)
end

def grade
   @questions = Questions.find(params[:id])
   @sample_array = params[:sample_array]
   @array_answers = # create array based on sample_array's answers
   @user_answers = params[:user_answers].split(' ')
   @user_answers = @user_answers.map.with_index{|x,y| params[("user_answer#{y.to_s}")] }
end
</code>```

views/questions/practice.html.erb # don't mind the finite number of forms its just for example.

```<code><%= form_for :grade, :url => grade_path, method: :get do |f| %>
  <%= hidden_field_tag(:sample_array, @sample_array) %>
  <%= hidden_field_tag(:user_answers, @user_answers) %>

<div class="form-group">
  <%= select_tag(("user_answer#{0}"), options_for_select([["a", 1],[ "b", 2],[ "c", 3],[ "d", 4]], 1), class: "form-control") %>
  <%= select_tag(("user_answer#{1}"), options_for_select([["a", 1],[ "b", 2],[ "c", 3],[ "d", 4]], 1), class: "form-control") %>
  <%= select_tag(("user_answer#{2}"), options_for_select([["a", 1],[ "b", 2],[ "c", 3],[ "d", 4]], 1), class: "form-control") %>
  <%= select_tag(("user_answer#{3}"), options_for_select([["a", 1],[ "b", 2],[ "c", 3],[ "d", 4]], 1), class: "form-control") %>
</div>
<div id="finalscore">
  <%= button_to "act_2", class:'btn btn-success' %>
</div>
<% end %>
</code>```

in grade the parameters i passed are just strings like so. questions: ["#", "#", "#"]

I researched it and hidden_fields will pass query_strings and that's why im only getting strings, but I can't find any examples on how to obtain the array object to use in my grade controller action.

thanks in advance sorry for the long question I don't know how else to ask about this.

答:
Instead of creating the arrays in your practice method, why don’t you create them in your grade method? To do this, you can instead assign @number_of_multiple_choice and @number_of_true_false in your practice method, pass those numbers in the hidden field tag, and determine your arrays in the grade action. I’m actually not sure what you’re trying to do with @user_answers in the practice action - I assume you’re just trying to create one empty answer object, but it does not appear to be used that way in the form.

controllers/questions.rb

```<code>def practice
   @question = Question.find(params[:id])
   @number_of_multiple_choices =             params[:number_of_multiple_choices].to_i
   @number_of_true_falses = params[:number_of_true_falses].to_i
end

def grade
 @question = Question.find(params[:id])
 @sample_array =   @questions.multiple_choices.sample(params[:number_of_multiple_choices].to_i)
 @sample_array += @questions.true_falses.sample(params[:number_of_true_falses].to_i)
 @array_answers = # create array based on sample_array's answers
 @user_answers = params[:user_answers].split(' ')
 @user_answers = @user_answers.map.with_index{|x,y| params[("user_answer#{y.to_s}")] }
end
</code>```

views/questions/practice.html.erb

```<code><%= form_for :grade, :url => grade_path, method: :get do |f| %>
  <%= hidden_field_tag(:number_of_multiple_choice, @number_of_multiple_choice) %>
  <%= hidden_field_tag(:number_of_true_falses, @number_of_true_falses) %>
  ...
<% end %>
</code>```

Additionally I noticed you’re saying @questions = Questions.find(params[:id]. The .find is meant to return one record but you have a) pluralized your variable indicating you want multiple questions, and b) pluralized your model, which is not standard convention. Either your model should be renamed or that will throw an error if your model is actually not pluralized.

Body:
I have a controller called "Questions" with two actions, "practice" and "grade" both are get routes, the practice view renders a small sample of of Questions and uses forms to get user answers using submit to get the "grade path"

to grade it, I need the record objects to be passed as an array, but when passed using the hidden field I get the reference numbers as strings and not the actual object. how do i get the object so I can call question_object.answer

controllers/questions.rb

def practice
   @questions = Questions.find(params[:id])
   @sample_array =  @questions.multiple_choices.sample(params[:number_of_multiple_choices].to_i)
   @sample_array += @questions.true_falses.sample(params[:number_of_true_falses].to_i)
   @user_answers = Array.new(@questions.size, 1)
end

def grade
   @questions = Questions.find(params[:id])
   @sample_array = params[:sample_array]
   @array_answers = # create array based on sample_array's answers
   @user_answers = params[:user_answers].split(' ')
   @user_answers = @user_answers.map.with_index{|x,y| params[("user_answer#{y.to_s}")] }
end

views/questions/practice.html.erb # don't mind the finite number of forms its just for example.

<%= form_for :grade, :url => grade_path, method: :get do |f| %>
  <%= hidden_field_tag(:sample_array, @sample_array) %>
  <%= hidden_field_tag(:user_answers, @user_answers) %>

  <%= select_tag(("user_answer#{0}"), options_for_select([["a", 1],[ "b", 2],[ "c", 3],[ "d", 4]], 1), class: "form-control") %>
  <%= select_tag(("user_answer#{1}"), options_for_select([["a", 1],[ "b", 2],[ "c", 3],[ "d", 4]], 1), class: "form-control") %>
  <%= select_tag(("user_answer#{2}"), options_for_select([["a", 1],[ "b", 2],[ "c", 3],[ "d", 4]], 1), class: "form-control") %>
  <%= select_tag(("user_answer#{3}"), options_for_select([["a", 1],[ "b", 2],[ "c", 3],[ "d", 4]], 1), class: "form-control") %>

  <%= button_to "act_2", class:'btn btn-success' %>

<% end %>

in grade the parameters i passed are just strings like so. questions: ["#", "#", "#"]

I researched it and hidden_fields will pass query_strings and that's why im only getting strings, but I can't find any examples on how to obtain the array object to use in my grade controller action.

thanks in advance sorry for the long question I don't know how else to ask about this.

Body:
Instead of creating the arrays in your practice method, why don’t you create them in your grade method? To do this, you can instead assign @number_of_multiple_choice and @number_of_true_false in your practice method, pass those numbers in the hidden field tag, and determine your arrays in the grade action. I’m actually not sure what you’re trying to do with @user_answers in the practice action - I assume you’re just trying to create one empty answer object, but it does not appear to be used that way in the form.

controllers/questions.rb

def practice
   @question = Question.find(params[:id])
   @number_of_multiple_choices =             params[:number_of_multiple_choices].to_i
   @number_of_true_falses = params[:number_of_true_falses].to_i
end

def grade
 @question = Question.find(params[:id])
 @sample_array =   @questions.multiple_choices.sample(params[:number_of_multiple_choices].to_i)
 @sample_array += @questions.true_falses.sample(params[:number_of_true_falses].to_i)
 @array_answers = # create array based on sample_array's answers
 @user_answers = params[:user_answers].split(' ')
 @user_answers = @user_answers.map.with_index{|x,y| params[("user_answer#{y.to_s}")] }
end

views/questions/practice.html.erb

<%= form_for :grade, :url => grade_path, method: :get do |f| %>
  <%= hidden_field_tag(:number_of_multiple_choice, @number_of_multiple_choice) %>
  <%= hidden_field_tag(:number_of_true_falses, @number_of_true_falses) %>
  ...
<% end %>

Additionally I noticed you’re saying @questions = Questions.find(params[:id]. The .find is meant to return one record but you have a) pluralized your variable indicating you want multiple questions, and b) pluralized your model, which is not standard convention. Either your model should be renamed or that will throw an error if your model is actually not pluralized.


问:
Clear text field on pressing enter
(Solved. Sorry for wasting your guys' time.)

In a web-based app I'm developing for personal use (online community), users have the option of using a "command line" at the top, versus navigating through numerous pages. This saves time, sanity, and executes the code once.

The command line works. As of right now, when you hit enter (there is no submit button), it opens a new tab, runs "cmdline.php" with the relevant $_POST information, and then closes that tab when it's finished executing.

The problem comes in when the tab closes, the old text is still there, "NEW;1283;JSMITH". To avoid people having to highlight and delete it for another entry, I'm trying to figure out how to have it self-clear when you hit enter.

Here is what I have found so far. Note that I'm brand new to javascript/jquery.

```<code>    <script src="java/jquery.js"></script>
    <script type="text/javascript">
    $('#cmdline').bind('keyup', function(e) {
        if (e.keyCode === 13) {
        $('#cmdline').find('input:text').val('');
        }
    });
    </script>
</code>```

(later in the same file)

```<code>    <form   target="_blank"
            action="cmdline.php"
            method="POST"
            id="cmdline"
    >
        <input type="text" placeholder="Ready for Command" autocomplete="off" name="cmdline">
    </form>
</code>```

答:
If you want to use attribute-selector change 'input:text' to this 'input[type="text"]'

$('#cmdline').bind('keyup', function(e) {
  if (e.keyCode === 13) {
    $('#cmdline').find('input[type="text"]').val('');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form target="_blank" action="cmdline.php" method="POST" id="cmdline">
  <input type="text" placeholder="Ready for Command" autocomplete="off" name="cmdline">
</form></code>```

Title: Clear text field on pressing enter

Body:
(Solved. Sorry for wasting your guys' time.)

In a web-based app I'm developing for personal use (online community), users have the option of using a "command line" at the top, versus navigating through numerous pages. This saves time, sanity, and executes the code once.

The command line works. As of right now, when you hit enter (there is no submit button), it opens a new tab, runs "cmdline.php" with the relevant $_POST information, and then closes that tab when it's finished executing.

The problem comes in when the tab closes, the old text is still there, "NEW;1283;JSMITH". To avoid people having to highlight and delete it for another entry, I'm trying to figure out how to have it self-clear when you hit enter.

Here is what I have found so far. Note that I'm brand new to javascript/jquery.

(later in the same file)

    <form   target="_blank"
            action="cmdline.php"
            method="POST"
            id="cmdline"
    >
        <input type="text" placeholder="Ready for Command" autocomplete="off" name="cmdline">
    </form>

Body:
If you want to use attribute-selector change 'input:text' to this 'input[type="text"]'

$('#cmdline').bind('keyup', function(e) {
  if (e.keyCode === 13) {
    $('#cmdline').find('input[type="text"]').val('');
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form target="_blank" action="cmdline.php" method="POST" id="cmdline">
  <input type="text" placeholder="Ready for Command" autocomplete="off" name="cmdline">
</form>


问:
What is a good HSM to test with?
What is a good (and cheap) HSM to test my PKCS11 applications with ? I am currently using SoftHSM but would like a physical HSM to test with. </p>

答:
The reality is that there are so many variants in PKCS#11 library behaviors working with HSM1 does not mean your application will work with HSM2, they just do so many oddball things you more-or-less need to test with each one.

With that said you can certainly get some confidence in your use of PKCS#11 by looking at other implementations.

Probably the cheapest way to get confidence your stuff will work with HSMs people actually use is using cloud offerings like those from Amazon (https://aws.amazon.com/cloudhsm/).

Some inexpensive (but probably not representative) devices you can look at include:
- https://www.yubico.com/products/yubihsm/
- https://www.smartcard-hsm.com/
- https://shop.nitrokey.com/shop/product/nitrokey-hsm-7

If you have time you can usually pick up used nShield Edge devices for around $150 on ebay, these are fully representative (API wise) to their big brother HSMs. Be sure only to get ones that come with recent middleware you will have a hard time finding it.

Title: What is a good HSM to test with?


问:
What is a simple way to set up an on click handler for 4 quiz answer buttons?
I have 4 beautiful buttons of class .button in css. Is there a simple way (presumably jQuery is the standard method) to put a event listener on these buttons.

Obviously the code will need to record which button was clicked, because only one of them has the right answer. The code below doesn't make that distinction, as button is a class not an ID. I suspect I will have to create four separate button IDs but that will multiply my css code by four.

I have been searching for a jQuery solution for a few days but not able to get any code to suit my particular situation.

This is the first time I have used jQuery, so if I have blundered, please don't be too harsh! I will greatly appreciate any knowledgeable contribution to solve this puzzle.

Here is the code from where the answers get sorted and displayed:

$(document).ready(function() {
  $("input:button").click(function() {
    alert('a button was clicked.')
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><b>What is this?</b></p>
<div>
  <input type="button" class="button">
  <input type="button" class="button">
  <input type="button" class="button">
  <input type="button" class="button">
</div></code>```

答:
You can use $(this) to find which button was clicked as follow:

$(document).ready(function() {
  $("input:button").click(function() {
    alert($(this).attr('value') + " button was clicked.")
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><b>What is this?</b></p>
<div>
  <input type="button" class="button" value="First">
  <input type="button" class="button" value="Second">
  <input type="button" class="button" value="Third">
  <input type="button" class="button" value="Fourth">
</div></code>```

Body:
I have 4 beautiful buttons of class .button in css. Is there a simple way (presumably jQuery is the standard method) to put a event listener on these buttons.

Obviously the code will need to record which button was clicked, because only one of them has the right answer. The code below doesn't make that distinction, as button is a class not an ID. I suspect I will have to create four separate button IDs but that will multiply my css code by four.

I have been searching for a jQuery solution for a few days but not able to get any code to suit my particular situation.

This is the first time I have used jQuery, so if I have blundered, please don't be too harsh! I will greatly appreciate any knowledgeable contribution to solve this puzzle.

Here is the code from where the answers get sorted and displayed:

$(document).ready(function() {
  $("input:button").click(function() {
    alert('a button was clicked.')
  });
});

What is this?

  <input type="button" class="button">
  <input type="button" class="button">
  <input type="button" class="button">
  <input type="button" class="button">

Body:
You can use $(this) to find which button was clicked as follow:

$(document).ready(function() {
  $("input:button").click(function() {
    alert($(this).attr('value') + " button was clicked.")
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><b>What is this?</b></p>
<div>
  <input type="button" class="button" value="First">
  <input type="button" class="button" value="Second">
  <input type="button" class="button" value="Third">
  <input type="button" class="button" value="Fourth">
</div>


问:
looping through object on auto hot key
How do I loop through each of these colors so that when I press ctr j the first time it shows up "red" the second time "blue" etc.
This is what I have so far

```<code>^j::
colors := Object("red","blue","green", "black")
for key, in colors
    s .= key
Send, % s
Return
</code>```

However, when I run it the output I get is

```<code>greenredgreenredgreenredgreenredgreenred
</code>```

答:
```<code>; Creating an array:
colors := ["red","blue","green","black"]
; or:
; colors := Array("red","blue","green", "black")

;  MaxIndex returns the number of items:
MaxIndex := colors.MaxIndex()

^j::
    Index++ ; increases the number in the variable "Index" by 1, each time you press ^j.
    Send, % colors[Index]
    If (Index = MaxIndex)
        Index = 0 ; reset
return
</code>```

https://autohotkey.com/docs/Objects.htm#Usage_Simple_Arrays

Title: looping through object on auto hot key

Body:
How do I loop through each of these colors so that when I press ctr j the first time it shows up "red" the second time "blue" etc.
This is what I have so far

^j::
colors := Object("red","blue","green", "black")
for key, in colors
    s .= key
Send, % s
Return

However, when I run it the output I get is

greenredgreenredgreenredgreenredgreenred

Body:
; Creating an array:
colors := ["red","blue","green","black"]
; or:
; colors := Array("red","blue","green", "black")

;  MaxIndex returns the number of items:
MaxIndex := colors.MaxIndex()

^j::
    Index++ ; increases the number in the variable "Index" by 1, each time you press ^j.
    Send, % colors[Index]
    If (Index = MaxIndex)
        Index = 0 ; reset
return

https://autohotkey.com/docs/Objects.htm#Usage_Simple_Arrays


问:
How to get output like this in Javascript/ES6
Let's say you have an array like this:

//Input
[1,2,3,4,5,6,7]

How to write the function which will get us the output of

//Output

```<code> Array1 = [1]
 Array2 = [1,2]
 Array3 = [1,2,3]
 Array4 = [1,2,3,4]
 Array5 = [1,2,3,4,5]
</code>```

And

//Output
1. [1,1,2,1,2,3,1,2,3,4...]

// tried this

```<code>for (i = 0; i < arr.length; i++) {
    arr = new Array(arr[i]);
}
</code>```

答:
You can do this simply by using two nested for loops like this,

let arr = [1, 2, 3, 4, 5, 6, 7];
function foo(arr) {
    let rarr = [];//result array
    for (let i = 0; i < arr.length; i++) {
        let a = [];//array[i]
        for (let j = 0; j <= i; j++) {
            a.push(arr[j]);
        }
        rarr.push(a);
    }
    return rarr;
}
console.log(foo(arr));```

Body:
Let's say you have an array like this:

//Input
[1,2,3,4,5,6,7]

How to write the function which will get us the output of

//Output

 Array1 = [1]
 Array2 = [1,2]
 Array3 = [1,2,3]
 Array4 = [1,2,3,4]
 Array5 = [1,2,3,4,5]

And

//Output
1. [1,1,2,1,2,3,1,2,3,4...]

// tried this

for (i = 0; i < arr.length; i++) {
    arr = new Array(arr[i]);
}


问:
PHP Extract Direct Video Path From Openload.co Embedded URL
I'm searching solution for this problem for a long time. about 3 weeks i didn't got any solutions.

See

This is the openload embedded url to be extracted

https://openload.co/embed/nLFGFH8VuZs/

The Direct Link :
https://1fiafzt.oloadcdn.net/dl/l/5qcL-TC0FIr7GgUX/nLFGFH8VuZs/VELMA2017RIPN15.mkv.mp4

Can anybody can suggest to solution to extract it. I got the direct url using the google chrome Inspect element.
I can see once i click play. How i can get using PHP or any other

Thanks

答:
Try
openload api ( Link -
https://openload.co/api )

First you need to generate an authenticated ticket using this url

https://api.openload.co/1/file/dlticket?file={file}&login={login}&key={key}

where , file = nLFGFH8VuZs ( in your case )

You will get ticket in JSON format

Second, to generate download link using below url -

https://api.openload.co/1/file/dl?file={file}&ticket={ticket}

You will get the download link in JSON file

(eg) url : " https://1fiafzt.oloadcdn.net/dl/l/5qcL-TC0FIr7GgUX/nLFGFH8VuZs/VELMA2017RIPN15.mkv.mp4"


问:
Nested Component binding empty
I am trying to understand property binding and it has been very confusing, I was able to solve my console full of errors, but I cannot figure out why my binding

app.component.html

```<code><div class="container">
  <div class="row">
    <div class="col-xs-12">
        <app-game-control [childTitle]="parentSelector"></app-game-control>
      </div>
</div>
</code>```

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  parentSelector = "This shall pass from parent to child" ;

}
</code>```

game-control.component.html

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

@Component({
  selector: 'app-game-control',
  templateUrl: './game-control.component.html',
  styleUrls: ['./game-control.component.css']
})
export class GameControlComponent implements OnInit {
@Input() childTitle:string ;
title= "Hello from child component";

  ngOnInit() {
  }
}
</code>```

game-control.component.html

```<code><div class="row">
    <div class="col-xs-12">
      {{title}}
  </div>
</div>
</code>```

What I am doing wrong?

答:
All is right in your code, the only thing is that you dont display your "childTitle" input at all.
Try this:

game-control.component.html

```<code><div class="column">
    <div>
      <h1>Data from game-control component
      {{title}}
  </div>
  <div>
      <h1>Data from parent</h1>
      {{childTitle}}
  </div>
</div>
</code>```

Title: Nested Component binding empty

Body:
I am trying to understand property binding and it has been very confusing, I was able to solve my console full of errors, but I cannot figure out why my binding

app.component.html

        <app-game-control [childTitle]="parentSelector"></app-game-control>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  parentSelector = "This shall pass from parent to child" ;

}

game-control.component.html

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

@Component({
  selector: 'app-game-control',
  templateUrl: './game-control.component.html',
  styleUrls: ['./game-control.component.css']
})
export class GameControlComponent implements OnInit {
@Input() childTitle:string ;
title= "Hello from child component";

  ngOnInit() {
  }
}

game-control.component.html

      {{title}}

What I am doing wrong?

Body:
All is right in your code, the only thing is that you dont display your "childTitle" input at all.
Try this:

game-control.component.html

<div class="column">
    <div>
      <h1>Data from game-control component
      {{title}}
  </div>
  <div>
      <h1>Data from parent</h1>
      {{childTitle}}
  </div>
</div>