问:
How do I rewrite this code for V8 from Rhino?
I used to a script on GAS.
Because I do manage attendance by Chat and Google spread sheet with GAS.
Chat tool is Chat work.
It works on Gas(Rhino).
But It doesn't work V8.

I tried to rewrite line19 for each (var obj in json){ to for (var obj in json){

Please tell me what is bad...
Which should I rewrite it?

```<code>function recordTime(){
  /*Sheet setting*/
  var wsData = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("data"); //DataSheetSetting
  var wsStaff = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("coworkers"); //CoworkersMasterSetting
  /*ChatworkURLrequest*/
  var params = {
    headers : {"X-ChatWorkToken" : 'anynumber'},
    method : "get"
  };
  var roomID = anynumber; //ROOMID
  var url = "https://api.chatwork.com/v2/rooms/" + roomID + "/messages?force=0"; //GetMessageFromGroupchat
  try{
    var respons = UrlFetchApp.fetch(url, params); //GetResponseFromChatworkAPIendpoint
    var json = JSON.parse(respons.getContentText()); //Returnjson
    for each(var obj in json){　//I understand that I should rewrite "for (var obj in json){
      /*Get YMDhm and ID*/
      var date = new Date(obj.send_time*1000);
      var date_D = new Date(date.getFullYear(),date.getMonth(),date.getDate(),0,0,0);
      var date_T = new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),0);
      var date_TH = new Date(0,0,0,date.getHours(),date.getMinutes(),0);
      /*dateToSn Setting*/
      var MILLIS_DIFFERENCE = 9 * 60 * 60 * 1000;
      var COEFFICIENT = 24 * 60 * 60 * 1000;
      var DATES_OFFSET = 70 * 365 + 17 + 1 + 1;
      function dateToSn(date){ //Date→Serial
        return convertUt2Sn(date.getTime());
      }
      function convertUt2Sn(unixTimeMillis){ //UNIX→Serial
        return (unixTimeMillis + MILLIS_DIFFERENCE) / COEFFICIENT + DATES_OFFSET;
      }
      /*findRow*/
      function findRow(sheet,val,col){
        var dat = sheet.getDataRange().getValues();
        for(var i=1;i<dat.length;i++){
          if(dat[i][col-1] === val){
            return i+1;
          }
        }
        return 0;
      }
      /*StaffID*/
      var staffID = wsStaff.getRange(findRow(wsStaff,obj.account.account_id,1),2).getValue();
      var dataRow=findRow(wsData,dateToSn(date_D)+staffID.toString(),1);
      if(obj.body.match(/出勤/)){
        if(!dataRow){
          wsData.appendRow(
            ["=INDIRECT(\"RC[1]\",FALSE) & INDIRECT(\"RC[2]\",FALSE)",date_D,
             "=VLOOKUP(" + obj.account.account_id + ",'coworkers'!A:B,2,FALSE)","=VLOOKUP(" + obj.account.account_id + ",'coworkers'!A:E,4,FALSE)","出勤",date_T
            ]);
        }
      }else if(obj.body.match(/外出/) || obj.body.match(/直行/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,8);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }else if(obj.body.match(/帰社/) || obj.body.match(/直帰/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,9);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }else if (obj.body.match(/中抜け/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,10);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }else if (obj.body.match(/戻り/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,11);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }else if(obj.body.match(/退勤/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,7);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }
    }
  }catch(e){
    Logger.log('Error');
    Logger.log(e.message);
  }
}
</code>```

答:
Google apps script switched runtime engines from Rhino to V8. This caught me by surprise too and borked a bunch of my code, including date and year manipulation.

Years are handled differently. getYear() no longer works as expected.

You can switch back to the old Rhino. See Enabling the Rhino Runtime

There is info about V8 available at https://developers.google.com/apps-script/guides/v8-runtime

Google has published a list of incompatibilities and other differences which contains good documentation about work arounds.

Full link for script migration: https://developers.google.com/apps-script/guides/v8-runtime/migration

Fortunately it's not the drama I was expecting. It would have been nice to have been given a heads up beforehand though.

Body:
I used to a script on GAS.
Because I do manage attendance by Chat and Google spread sheet with GAS.
Chat tool is Chat work.
It works on Gas(Rhino).
But It doesn't work V8.

I tried to rewrite line19 for each (var obj in json){ to for (var obj in json){

Please tell me what is bad...
Which should I rewrite it?

function recordTime(){
  /*Sheet setting*/
  var wsData = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("data"); //DataSheetSetting
  var wsStaff = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("coworkers"); //CoworkersMasterSetting
  /*ChatworkURLrequest*/
  var params = {
    headers : {"X-ChatWorkToken" : 'anynumber'},
    method : "get"
  };
  var roomID = anynumber; //ROOMID
  var url = "https://api.chatwork.com/v2/rooms/" + roomID + "/messages?force=0"; //GetMessageFromGroupchat
  try{
    var respons = UrlFetchApp.fetch(url, params); //GetResponseFromChatworkAPIendpoint
    var json = JSON.parse(respons.getContentText()); //Returnjson
    for each(var obj in json){　//I understand that I should rewrite "for (var obj in json){
      /*Get YMDhm and ID*/
      var date = new Date(obj.send_time*1000);
      var date_D = new Date(date.getFullYear(),date.getMonth(),date.getDate(),0,0,0);
      var date_T = new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),0);
      var date_TH = new Date(0,0,0,date.getHours(),date.getMinutes(),0);
      /*dateToSn Setting*/
      var MILLIS_DIFFERENCE = 9 * 60 * 60 * 1000;
      var COEFFICIENT = 24 * 60 * 60 * 1000;
      var DATES_OFFSET = 70 * 365 + 17 + 1 + 1;
      function dateToSn(date){ //Date→Serial
        return convertUt2Sn(date.getTime());
      }
      function convertUt2Sn(unixTimeMillis){ //UNIX→Serial
        return (unixTimeMillis + MILLIS_DIFFERENCE) / COEFFICIENT + DATES_OFFSET;
      }
      /*findRow*/
      function findRow(sheet,val,col){
        var dat = sheet.getDataRange().getValues();
        for(var i=1;i<dat.length;i++){
          if(dat[i][col-1] === val){
            return i+1;
          }
        }
        return 0;
      }
      /*StaffID*/
      var staffID = wsStaff.getRange(findRow(wsStaff,obj.account.account_id,1),2).getValue();
      var dataRow=findRow(wsData,dateToSn(date_D)+staffID.toString(),1);
      if(obj.body.match(/出勤/)){
        if(!dataRow){
          wsData.appendRow(
            ["=INDIRECT(\"RC[1]\",FALSE) & INDIRECT(\"RC[2]\",FALSE)",date_D,
             "=VLOOKUP(" + obj.account.account_id + ",'coworkers'!A:B,2,FALSE)","=VLOOKUP(" + obj.account.account_id + ",'coworkers'!A:E,4,FALSE)","出勤",date_T
            ]);
        }
      }else if(obj.body.match(/外出/) || obj.body.match(/直行/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,8);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }else if(obj.body.match(/帰社/) || obj.body.match(/直帰/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,9);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }else if (obj.body.match(/中抜け/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,10);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }else if (obj.body.match(/戻り/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,11);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }else if(obj.body.match(/退勤/)){
        if(dataRow){
          var rng = wsData.getRange(dataRow,7);
          if(!rng.getValue()){
            rng.setValue(date_T);
          }
        }
      }
    }
  }catch(e){
    Logger.log('Error');
    Logger.log(e.message);
  }
}


来源: stackexchange

问:
Trying to get selenium to work property with drop down menu (select element)
I am trying to get selenium to select a specific value from a dropdown menu.

Here is a picture of the elements.

Heres is a code of the element.

<select _ngcontent-c31="" class="input productEntry ng-valid ng-touched ng-dirty" formcontrolname="handlingUnit" tabindex="1022" style="">
    <option _ngcontent-c31="" value="0">N/A</option>

    <option _ngcontent-c31="" value="1" class="ng-star-inserted">Pallet</option>
    <option _ngcontent-c31="" value="2" class="ng-star-inserted">Skid</option>
    <option _ngcontent-c31="" value="3" class="ng-star-inserted">Loose</option>
    <option _ngcontent-c31="" value="4" class="ng-star-inserted">Other</option>
    <option _ngcontent-c31="" value="5" class="ng-star-inserted">Gaylord</option>
    <option _ngcontent-c31="" value="6" class="ng-star-inserted">Master Bundles</option>
    <option _ngcontent-c31="" value="7" class="ng-star-inserted">Carrier</option>
</select>
```

<p><strong>Here is a picture of the website in which I am try to get selenium to auto-select. It is for the category "Handling Unit". I want it to select pallet. (First option is N/A, Second option is Pallet, Third option is Skid etc)</strong></p>

<p><img src="https://i.stack.imgur.com/5dqUQ.png" alt="Interface"></p>

<p>I've tried the following code.</p>

```from selenium.webdriver.support.ui import Select

select_element = Select(driver.find_element(By.XPATH, "//select[@class='input productEntry ng-valid ng-dirty ng-touched']"))
select_element.select_by_value('$1')
```

<p>This line cause the rest of my code to bug out. What is the best way to code a select element with selenium?</p>

<p><strong>Updated Solution</strong></p>

```select_element = Select(driver.find_element_by_xpath('/html[1]/body[1]/app-root[1]/div[1]/div[1]/app-record[1]/div[1]/div[2]/div[1]/app-record-quoting[1]/div[1]/app-record-product-list-panel[1]/form[1]/div[3]/div[1]/div[3]/div[1]/select[1]'))
select_element.select_by_value('1')
```

答:
You must use Select method like this:

```<code>select_element = Select(driver.find_element_by_xpath(''))
select_element.select_by_value('$1')
</code>```

Also you can Use full Xpath instead of Xpath to get element with selenium.
In your picture, you must get abs Xpath. it's same as full Xpath that i said.

To get the element with selenium you can use this:

```<code>driver.find_element_by_xpath('')
</code>```

If you want to click on it, use this:

```<code>driver.find_element_by_xpath('').click()
</code>```

If you want to get element text, use this:

```<code>driver.find_element_by_xpath('').text
</code>```

If you want to write a text in element, use this:

```<code>driver.find_element_by_xpath('').send_keys('')
</code>```

You can use both abs and rell Xpath, but the problem in abs Xpath is that any changes in html can make that selenium don't find the element or find wrong element.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get selenium to select a specific value from a dropdown menu.

Here is a picture of the elements.

Heres is a code of the element.

<select _ngcontent-c31="" class="input productEntry ng-valid ng-touched ng-dirty" formcontrolname="handlingUnit" tabindex="1022" style="">
    <option _ngcontent-c31="" value="0">N/A</option>

    <option _ngcontent-c31="" value="1" class="ng-star-inserted">Pallet</option>
    <option _ngcontent-c31="" value="2" class="ng-star-inserted">Skid</option>
    <option _ngcontent-c31="" value="3" class="ng-star-inserted">Loose</option>
    <option _ngcontent-c31="" value="4" class="ng-star-inserted">Other</option>
    <option _ngcontent-c31="" value="5" class="ng-star-inserted">Gaylord</option>
    <option _ngcontent-c31="" value="6" class="ng-star-inserted">Master Bundles</option>
    <option _ngcontent-c31="" value="7" class="ng-star-inserted">Carrier</option>
</select>

Here is a picture of the website in which I am try to get selenium to auto-select. It is for the category "Handling Unit". I want it to select pallet. (First option is N/A, Second option is Pallet, Third option is Skid etc)

I've tried the following code.

from selenium.webdriver.support.ui import Select

select_element = Select(driver.find_element(By.XPATH, "//select[@class='input productEntry ng-valid ng-dirty ng-touched']"))
select_element.select_by_value('$1')

This line cause the rest of my code to bug out. What is the best way to code a select element with selenium?

Updated Solution

select_element = Select(driver.find_element_by_xpath('/html[1]/body[1]/app-root[1]/div[1]/div[1]/app-record[1]/div[1]/div[2]/div[1]/app-record-quoting[1]/div[1]/app-record-product-list-panel[1]/form[1]/div[3]/div[1]/div[3]/div[1]/select[1]'))
select_element.select_by_value('1')

Body:
You must use Select method like this:

select_element = Select(driver.find_element_by_xpath(''))
select_element.select_by_value('$1')

Also you can Use full Xpath instead of Xpath to get element with selenium.
In your picture, you must get abs Xpath. it's same as full Xpath that i said.

To get the element with selenium you can use this:

driver.find_element_by_xpath('')

If you want to click on it, use this:

driver.find_element_by_xpath('').click()

If you want to get element text, use this:

driver.find_element_by_xpath('').text

If you want to write a text in element, use this:

driver.find_element_by_xpath('').send_keys('')

You can use both abs and rell Xpath, but the problem in abs Xpath is that any changes in html can make that selenium don't find the element or find wrong element.


问:
How to access Activity UI from my class?
I have an activity which creates an object instance of my class:

```<code>file MyActivity.java:
public class MyActivity extends Activity {
    TextView myView = (TextView)findViewById(R.id.myView);
    ...
    Points myPoints new Points();
    ...
}
--------------------------------------------------------------

file Points.java:
private class Points {
    ...
    HOW TO USE myView HERE ???
    ...
}
--------------------------------------------------------------
</code>```

How do I use the UI objects in my class (which does not extend an
Activity)? Should I pass some context to my Points class? How do I do, exactly?

答:
You could just pass the view to your class.</p>

```<code>Points myPoints = new Points(myView);

private class Points
{
  private TextView mTextView;

  Points(TextView textView)
  {
     this.mTextView = textView;
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an activity which creates an object instance of my class:

file MyActivity.java:
public class MyActivity extends Activity {
    TextView myView = (TextView)findViewById(R.id.myView);
    ...
    Points myPoints new Points();
    ...
}
--------------------------------------------------------------

file Points.java:
private class Points {
    ...
    HOW TO USE myView HERE ???
    ...
}
--------------------------------------------------------------

How do I use the UI objects in my class (which does not extend an
Activity)? Should I pass some context to my Points class? How do I do, exactly?

Body:
You could just pass the view to your class.

Points myPoints = new Points(myView);

private class Points
{
  private TextView mTextView;

  Points(TextView textView)
  {
     this.mTextView = textView;
  }
}


问:
How do I pass a double pointer from a third function to a fourth in C?
I need to pass a double pointer from one function to a second to a third. For instance:

```<code>char *text = "some text";
func2(&text);

void func2(char **text){
  func3(&text);
}

void func3(char **text) ...
</code>```

Is this valid? Is there a better way to ensure that all these functions can edit this variable (without it being global)?

答:
There's no need to use &text in func2(). text is already a pointer to the original variable, you can just pass it as it is.

You also need to specify the type that the pointer points to in the function signatures.

```<code>void func2(char **text){
  func3(text);
}
void func3(char **text) ...
</code>```

Body:
I need to pass a double pointer from one function to a second to a third. For instance:

char *text = "some text";
func2(&text);

void func2(char **text){
  func3(&text);
}

void func3(char **text) ...

Is this valid? Is there a better way to ensure that all these functions can edit this variable (without it being global)?

Body:
There's no need to use &text in func2(). text is already a pointer to the original variable, you can just pass it as it is.

You also need to specify the type that the pointer points to in the function signatures.

void func2(char **text){
  func3(text);
}
void func3(char **text) ...


问:
Is it possible to use Appery to access data from Neo4J Graph Database?
I have a web application that has to be linked with a graph database (Neo4J). Is it possible to read or write data to Neo4J using Appery?

I have chosen Appery because I am a beginner when it comes to databases and Appery seems to be easy in using REST API, as well as there is a free trial.

Feedback would be highly helpful. Thanks in advance.

Edit: I am aware that Neo4J uses Cypher queries. I would like to know if Appery supports Cypher as well.

Side note: The reason I am asking the question here without trying it out is because I dont have an active DB and my application is private due to my company's security policy

答: You can do that as long as Neo4J database has a REST API. If it does, then you can make calls to it from an Appery app (from Server Code or API Express). Hope this helps. </p>


问:
Fastest way to merge Dataframe into one data frame

I would like to merge two Dataframes into 1 fast as possible.

DF1:

```<code>    A   B   C
0  A0  B0  C0
1  A1  B1  C1
2  A2  B2  C2
3  A3  B3  C3
4  A4  B4  C4
5  A5  B5  C5
6  A6  B6  C6
7  A7  B7  C7

```
```

<p>DF2:
    ```
        A   Z
    0  A3  Z4
    1  A5  Z5
    2  A6  Z6
    3  A7  Z7
    ```</p>

<p>Current Results:
    ```
        A   B   C     Z
    0  A0  B0  C0   NaN
    1  A1  B1  C1   NaN
    2  A2  B2  C2   NaN
    3  A3  B3  C3  [Z4]
    4  A4  B4  C4  [Z4]
    5  A5  B5  C5  [Z5]
    6  A6  B6  C6  [Z6]
    7  A7  B7  C7  [Z7]
    ```</p>

<p>Required Results:
        ```
        A   B   C    Z
    0  A0  B0  C0  NaN
    1  A1  B1  C1  NaN
    2  A2  B2  C2  NaN
    3  A3  B3  C3  Z4
    4  A4  B4  C4  NaN
    5  A5  B5  C5  Z5
    6  A6  B6  C6  Z6
    7  A7  B7  C7  Z7
    ```</p>

<blockquote>
  <p>Three problems I have with my code.
  1) I would not like the Z4 to repeat. if its null I would just like NaN.<br>
  2) I am not sure why but is coming as list when it should be string format.<br>
  3) very slow.</p>

  <p>NOTE: Everything that is in DF2 dataframe column A will always be in D2 column A<br>
  My current Code</p>
</blockquote>

``````
import pandas as pd
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7'],
'B': ['B0', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7'],
'C': ['C0', 'C1', 'C2', 'C3','C4', 'C5', 'C6', 'C7']},
index=[0, 1, 2, 3, 4, 5, 6, 7])

df2 = pd.DataFrame({'A': ['A3', 'A5', 'A6', 'A7'],
'Z': ['Z4', 'Z5', 'Z6', 'Z7'],
},
index=[0, 1, 2, 3])

def mergeDF(df1, df2):
   import pandas as pd
   v = df1.merge(df2[['A', 'Z']])\
      .groupby(df1.columns.tolist())\
      .Z\
      .apply(pd.Series.tolist)

   df = pd.DataFrame(v.tolist(), index=v.index)\
      .rename(columns=lambda x: x + 1)\
      .add_prefix('Z')\
      .reset_index()

   df = df1.merge(v, how='left', on='A').ffill()

   print (df)

mergeDF(df1, df2)

print (df1)

```
```

答:
You can do this in a much simpler way that what you've done now:

```<code> pd.merge(df1,df2,how='left',on='A')
</code>```

You've got a list because you converted v to list in your function and added ffill which will replace null values by the last non null value in the column

Body:
I would like to merge two Dataframes into 1 fast as possible.

DF1:

    A   B   C
0  A0  B0  C0
1  A1  B1  C1
2  A2  B2  C2
3  A3  B3  C3
4  A4  B4  C4
5  A5  B5  C5
6  A6  B6  C6
7  A7  B7  C7

DF2:

        A   Z
    0  A3  Z4
    1  A5  Z5
    2  A6  Z6
    3  A7  Z7

Current Results:

        A   B   C     Z
    0  A0  B0  C0   NaN
    1  A1  B1  C1   NaN
    2  A2  B2  C2   NaN
    3  A3  B3  C3  [Z4]
    4  A4  B4  C4  [Z4]
    5  A5  B5  C5  [Z5]
    6  A6  B6  C6  [Z6]
    7  A7  B7  C7  [Z7]

Required Results:

        A   B   C    Z
    0  A0  B0  C0  NaN
    1  A1  B1  C1  NaN
    2  A2  B2  C2  NaN
    3  A3  B3  C3  Z4
    4  A4  B4  C4  NaN
    5  A5  B5  C5  Z5
    6  A6  B6  C6  Z6
    7  A7  B7  C7  Z7

Three problems I have with my code.
  1) I would not like the Z4 to repeat. if its null I would just like NaN.

  2) I am not sure why but is coming as list when it should be string format.

  3) very slow.

NOTE: Everything that is in DF2 dataframe column A will always be in D2 column A

  My current Code

```
import pandas as pd
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7'],
'B': ['B0', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7'],
'C': ['C0', 'C1', 'C2', 'C3','C4', 'C5', 'C6', 'C7']},
index=[0, 1, 2, 3, 4, 5, 6, 7])

df2 = pd.DataFrame({'A': ['A3', 'A5', 'A6', 'A7'],
'Z': ['Z4', 'Z5', 'Z6', 'Z7'],
},
index=[0, 1, 2, 3])

def mergeDF(df1, df2):
   import pandas as pd
   v = df1.merge(df2[['A', 'Z']])\
      .groupby(df1.columns.tolist())\
      .Z\
      .apply(pd.Series.tolist)

   df = pd.DataFrame(v.tolist(), index=v.index)\
      .rename(columns=lambda x: x + 1)\
      .add_prefix('Z')\
      .reset_index()

   df = df1.merge(v, how='left', on='A').ffill()

   print (df)

mergeDF(df1, df2)

print (df1)

```

Body:
You can do this in a much simpler way that what you've done now:

 pd.merge(df1,df2,how='left',on='A')

You've got a list because you converted v to list in your function and added ffill which will replace null values by the last non null value in the column


问:
error:static_cast undeclared->Objective C
I was porting from cpp to Objective C.

Objective C:

```<code>[pPacket SetHeaderSequenceNumber:static_cast<char>(m_transmitSequenceNumber + ASCII_ZERO)];
</code>```

cpp:

```<code>pPacket->SetHeaderSequenceNumber(static_cast <char>(m_transmitSequenceNumber + ASCII_ZERO));
</code>```

error:static_cast undeclared.

答:
objective-c is a superset of c, not c++ so static_cast is not supported in it. You can just use c-style cast:</p>

```<code>[pPacket SetHeaderSequenceNumber:(char)(m_transmitSequenceNumber + ASCII_ZERO)];
</code>```

Body:
I was porting from cpp to Objective C.

Objective C:

[pPacket SetHeaderSequenceNumber:static_cast<char>(m_transmitSequenceNumber + ASCII_ZERO)];

cpp:

pPacket->SetHeaderSequenceNumber(static_cast <char>(m_transmitSequenceNumber + ASCII_ZERO));

error:static_cast undeclared.

Body:
objective-c is a superset of c, not c++ so static_cast is not supported in it. You can just use c-style cast:

[pPacket SetHeaderSequenceNumber:(char)(m_transmitSequenceNumber + ASCII_ZERO)];


问:
How to add S3 BucketPolicy with AWS CDK?
I wanna translate this CloudFormation piece into CDK:

```<code>Type: AWS::S3::BucketPolicy
Properties:
  Bucket:
    Ref: S3BucketImageUploadBuffer
  PolicyDocument:
    Version: "2012-10-17"
    Statement:
      Action:
        - s3:PutObject
        - s3:PutObjectAcl
      Effect: Allow
      Resource:
        - ...
</code>```

Looking at the documentation here, I don't see a way to provide the policy document itself.

答: The CDK does this a little differently. I believe you are supposed to use bucket.addToResourcePolicy, as documented here.

Body:
I wanna translate this CloudFormation piece into CDK:

Type: AWS::S3::BucketPolicy
Properties:
  Bucket:
    Ref: S3BucketImageUploadBuffer
  PolicyDocument:
    Version: "2012-10-17"
    Statement:
      Action:
        - s3:PutObject
        - s3:PutObjectAcl
      Effect: Allow
      Resource:
        - ...

Looking at the documentation here, I don't see a way to provide the policy document itself.


答:
Quick one:

>>>df1.join(df2.set_index('A'), how='outer', on='A')`
    A   B   C   Z
0   A0  B0  C0  NaN
1   A1  B1  C1  NaN
2   A2  B2  C2  NaN
3   A3  B3  C3  Z4
4   A4  B4  C4  NaN
5   A5  B5  C5  Z5
6   A6  B6  C6  Z6
7   A7  B7  C7  Z7
```

Title: Fastest way to merge Dataframe into one data frame


问:
Laravel dispatching Queues at set time
I am currently dispatching queued jobs to send API Events instantly, in busy times these queued jobs need to be held until overnight when the API is less busy, how can I hold these queued jobs or schedule them to only run from 01:00am the following day.

the Queued Job call currently looks like:

```<code>EliQueueIdentity::dispatch($EliIdentity->id)->onQueue('eli');
</code>```

there are other jobs on the same queue, all of which will need to be held in busy times

答:
Use delay to run job at a certain time.

```<code>EliQueueIdentity::dispatch($EliIdentity->id)
    ->onQueue('eli')
    ->delay($this->scheduleDate());
</code>```

Helper for calculating the time, handling a edge case between 00:00 to 01:00, where it would delay it a whole day. While not specified how to handle busy, made an pseudo example you can implement.

```<code>private function scheduleDate()
{
    $now = Carbon::now();

    if (! $this->busy()) {
        return $now;
    }

    // check for edge case of 00:00:00 to 01
    if ($now->hour <= 1) {
        $now->setTime(1, 0, 0);
        return $now;
    }

    return Carbon::tomorrow()->addHour();
}
</code>```

Title: Laravel dispatching Queues at set time

Body:
I am currently dispatching queued jobs to send API Events instantly, in busy times these queued jobs need to be held until overnight when the API is less busy, how can I hold these queued jobs or schedule them to only run from 01:00am the following day.

the Queued Job call currently looks like:

EliQueueIdentity::dispatch($EliIdentity->id)->onQueue('eli');

there are other jobs on the same queue, all of which will need to be held in busy times

Body:
Use delay to run job at a certain time.

EliQueueIdentity::dispatch($EliIdentity->id)
    ->onQueue('eli')
    ->delay($this->scheduleDate());

Helper for calculating the time, handling a edge case between 00:00 to 01:00, where it would delay it a whole day. While not specified how to handle busy, made an pseudo example you can implement.

private function scheduleDate()
{
    $now = Carbon::now();

    if (! $this->busy()) {
        return $now;
    }

    // check for edge case of 00:00:00 to 01
    if ($now->hour <= 1) {
        $now->setTime(1, 0, 0);
        return $now;
    }

    return Carbon::tomorrow()->addHour();
}


问:
Finding first previous 0 from starting cell
I'm trying to count the number of cells between two cells that I need to find with vba.  The first cell is going to be in the same column as the current date today.  The column headers are left to right in date order (May 1st, May 2nd, May 3rd, etc..).  Once I find the column to begin with, I need to count the number of cells backwards that contain 0 until I find a cell without a 0.  So say I'm starting in column U, I need to count the number of contiguous cells with 0 until say column R has a 1.  My answer would then be 2 because columns T and S had 0's.

The issue I'm running into with the below code is that I'm trying to find first the column I'm supposed to be in based on the date (This part works).  Next I'm declaring the rowNum as the activecell row number (This part work).  Next I need to find which column to count backwards to (This part does not work).  I'm getting the same column number on the colNum FIND code as I am the colStart FIND code.

I'm not getting any errors, it just doesn't seem like it's finding the previous cell with 0 and is instead just giving me the same column.  I hope this is clear.  Let me know if you need any additional info.  Thanks everyone!

```<code>today = Date

colNum = Cells.Find(today, searchorder:=xlByRows,
         searchdirection:=xlPrevious).Column
rowNum = ActiveCell.Row
colStart = Cells.Find(0, after:=Cells(rowNum, colNum),
           searchorder:=xlByColumns, searchdirection:=xlPrevious).Column
</code>```

答:
Try this code:

```<code>Public Function countZeros(ws As Worksheet, rowNum As Long, colNum As Long, Optional stopColumn As Long = 1) As Long
Dim currentCol As Long
    countZeros = 0
    If colNum <= stopColumn Then Exit Function   'prevents going past a certain point (for example your label column)
    For currentCol = colNum - 1 To stopColumn + 1 Step -1
        If ws.Cells(rowNum, currentCol) = 0 Then
            countZeros = countZeros + 1
        Else
            Exit Function
        End If
    Next 'currentCol
End Function

Public Sub mySub()
Dim colNum As Long
Dim rowNum As Long
Dim output As String
Dim today
Dim rng As Range
    today = Date

    Set rng = Cells.Find(today, searchorder:=xlByRows, searchdirection:=xlPrevious)
    If rng Is Nothing Then
        MsgBox "Did not find todays date, make sure your active cell is in the right location"
        Exit Sub
    End If

    colNum = rng.Column
    rowNum = ActiveCell.Row
    output = "Total number of cells from " & Cells(rowNum, colNum).Address & " that have zeros: "
    output = output & CStr(countZeros(ActiveWorkbook.ActiveSheet, rowNum, colNum))
    MsgBox output
End Sub
</code>```

With this data set:

you get the output:
Total number of cells from $K$7 that have zeros: 6

Body:
I'm trying to count the number of cells between two cells that I need to find with vba.  The first cell is going to be in the same column as the current date today.  The column headers are left to right in date order (May 1st, May 2nd, May 3rd, etc..).  Once I find the column to begin with, I need to count the number of cells backwards that contain 0 until I find a cell without a 0.  So say I'm starting in column U, I need to count the number of contiguous cells with 0 until say column R has a 1.  My answer would then be 2 because columns T and S had 0's.

The issue I'm running into with the below code is that I'm trying to find first the column I'm supposed to be in based on the date (This part works).  Next I'm declaring the rowNum as the activecell row number (This part work).  Next I need to find which column to count backwards to (This part does not work).  I'm getting the same column number on the colNum FIND code as I am the colStart FIND code.

I'm not getting any errors, it just doesn't seem like it's finding the previous cell with 0 and is instead just giving me the same column.  I hope this is clear.  Let me know if you need any additional info.  Thanks everyone!

today = Date

colNum = Cells.Find(today, searchorder:=xlByRows,
         searchdirection:=xlPrevious).Column
rowNum = ActiveCell.Row
colStart = Cells.Find(0, after:=Cells(rowNum, colNum),
           searchorder:=xlByColumns, searchdirection:=xlPrevious).Column

Body:
Try this code:

Public Function countZeros(ws As Worksheet, rowNum As Long, colNum As Long, Optional stopColumn As Long = 1) As Long
Dim currentCol As Long
    countZeros = 0
    If colNum <= stopColumn Then Exit Function   'prevents going past a certain point (for example your label column)
    For currentCol = colNum - 1 To stopColumn + 1 Step -1
        If ws.Cells(rowNum, currentCol) = 0 Then
            countZeros = countZeros + 1
        Else
            Exit Function
        End If
    Next 'currentCol
End Function

Public Sub mySub()
Dim colNum As Long
Dim rowNum As Long
Dim output As String
Dim today
Dim rng As Range
    today = Date

    Set rng = Cells.Find(today, searchorder:=xlByRows, searchdirection:=xlPrevious)
    If rng Is Nothing Then
        MsgBox "Did not find todays date, make sure your active cell is in the right location"
        Exit Sub
    End If

    colNum = rng.Column
    rowNum = ActiveCell.Row
    output = "Total number of cells from " & Cells(rowNum, colNum).Address & " that have zeros: "
    output = output & CStr(countZeros(ActiveWorkbook.ActiveSheet, rowNum, colNum))
    MsgBox output
End Sub

With this data set:

you get the output:
Total number of cells from $K$7 that have zeros: 6


问:
Android build c++ with dependency
I am working on an Android application with NDK. My c++ code has some dependencies from c++ open source libraries, so I can download the source code of the dependencies and package them in my app. I have created my CMakeList files, but I don't know how to include the external library.

I would like to build the dependency to be able to use it in my own project, so the flow would be as follows:

cd external/library/path

./configure

make

build my app and link the built dependency

Is this possible? If so, how can this be done? Sorry if this is a dumb question, I'm new on C++ and Cmake.

答: The way I solved this was by cross compiling the libraries and adding them as static libraries. You can cross compile using the clang binaries included in the ndk directory, using the one that targets your app min sdk.</p>

Title: Android build c++ with dependency


答:
Objective C is a superset of C not C++. static_cast is a C++ operator so Objective C cannot use this.

However there is Objective C++ which does understand C++. To use this rename your .m file to .mm and Xcode will compile this as Objective C++

Title: error:static_cast undeclared->Objective C


问:
Processing RAW audio data from Android
I’m struggling since days trying to obtain a raw audio stream from the microphone. I am trying different ways: the low-level JNI way with Oboe Library (either AAudio and OpenSL ES implementations) and the Android’s AudioRecord Java classes.

The problem I am facing is that I am not able to retrieve amplitudes near -/+1.0 while being sure of saturating the microphone input with a calibrated pure tone with such a high amplitude.
I think that the problem is that I am not able to effectively disable the signal preprocessing from AndroidOS (Automatic Gain Control or Noise Cancelling).

```<code>AutomaticGainControl.create(id).setEnabled(false)
</code>```

(not working!)

Also, it seems that it is not possible also to disable any additional microphone rather than the one "selected" (done that as selecting the setPreferredDevice on AudioRecord instance). Used as audio source: unprocessed, mic, voice_recognition.

Is there anyway doing this or am I missing something?

Thank you

答: Which audio source are you using for your recording? VOICE_RECOGNITION or UNPROCESSED are mandated to not have any pre-processing enabled by default (i.e. see https://source.android.com/compatibility/10/android-10-cdd#5_11_capture_for_unprocessed) and therefore would allow you to check your signal path.</p>

Title: Processing RAW audio data from Android

Body:
I’m struggling since days trying to obtain a raw audio stream from the microphone. I am trying different ways: the low-level JNI way with Oboe Library (either AAudio and OpenSL ES implementations) and the Android’s AudioRecord Java classes.

The problem I am facing is that I am not able to retrieve amplitudes near -/+1.0 while being sure of saturating the microphone input with a calibrated pure tone with such a high amplitude.
I think that the problem is that I am not able to effectively disable the signal preprocessing from AndroidOS (Automatic Gain Control or Noise Cancelling).

AutomaticGainControl.create(id).setEnabled(false)

(not working!)

Also, it seems that it is not possible also to disable any additional microphone rather than the one "selected" (done that as selecting the setPreferredDevice on AudioRecord instance). Used as audio source: unprocessed, mic, voice_recognition.

Is there anyway doing this or am I missing something?

Thank you


问:
scrollIntoView Scrolls just too far
I have a page where a scroll bar containing table rows with divs in them is dynamically generated from the database. Each table row acts like a link, sort of like you'd see on a YouTube playlist next to the video player.

When a user visits the page, the option they are on is supposed to go to the top of the scrolling div. This functionality is working. The issue is that it goes just a tad too far. Like the option they are on is about 10px too high. So, the page is visited, the url is used to identify which option was selected and then scrolls that option to the top of the scrolling div. Note: This is not the scroll bar for the window, it is a div with a scrollbar.

I am using this code to make it move the selected option to the top of the div:

```<code>var pathArray = window.location.pathname.split( '/' );

var el = document.getElementById(pathArray[5]);

el.scrollIntoView(true);
</code>```

It moves it to the top of the div but about 10 pixels too far up.
Anyone know how to fix that?

答:
Another solution is to use "offsetTop", like this:</p>

```<code>var elementPosition = document.getElementById('id').offsetTop;

window.scrollTo({
  top: elementPosition - 10, //add your necessary value
  behavior: "smooth"  //Smooth transition to roll
});
</code>```

Title: scrollIntoView Scrolls just too far

Body:
I have a page where a scroll bar containing table rows with divs in them is dynamically generated from the database. Each table row acts like a link, sort of like you'd see on a YouTube playlist next to the video player.

When a user visits the page, the option they are on is supposed to go to the top of the scrolling div. This functionality is working. The issue is that it goes just a tad too far. Like the option they are on is about 10px too high. So, the page is visited, the url is used to identify which option was selected and then scrolls that option to the top of the scrolling div. Note: This is not the scroll bar for the window, it is a div with a scrollbar.

I am using this code to make it move the selected option to the top of the div:

var pathArray = window.location.pathname.split( '/' );

var el = document.getElementById(pathArray[5]);

el.scrollIntoView(true);

It moves it to the top of the div but about 10 pixels too far up.
Anyone know how to fix that?

Body:
Another solution is to use "offsetTop", like this:

var elementPosition = document.getElementById('id').offsetTop;

window.scrollTo({
  top: elementPosition - 10, //add your necessary value
  behavior: "smooth"  //Smooth transition to roll
});


问:
Angular6 (click) not passing event in case of div
I was following :
https://coursetro.com/posts/code/59/Angular-4-Event-Binding

and my code is as below: I am using div at place of button:

```<code><div (click)="updateSelectedLanguage($event)">
    <!-- More items -->
</div>
</code>```

And :

```<code>  updateSelectedLanguage(event : any) {
    console.log(event);
  }
</code>```

However, event is always undefined. What am I missing here?

答:
In the example given, its tag is a button, so when you pass $event, you pass the button click event. buttons have predefined structures, which will be part of that event.

In your case, you have it attached to a div, divs don't have predefined structures, you have to give it to them with data, maybe ngModel or ngForm structures.

Body:
I was following :
https://coursetro.com/posts/code/59/Angular-4-Event-Binding

and my code is as below: I am using div at place of button:

And :

  updateSelectedLanguage(event : any) {
    console.log(event);
  }

However, event is always undefined. What am I missing here?


问:
Null Values in Zones in Highcharts
I have graphs that have zones. Currently if there is a null value, that null value is displayed in the tooltip with the zone color of the point before it. I want the null value to always be the color black.

For example,

The tooltip in graph 1 has all the correct information... but "Strength: null" has a green dot. I want to make this dot black because it is a null value.

Is it possible to make this happen? Thanks so much.

https://codepen.io/austeng/pen/gOppRWY

```<code>zones: [
  {
    value: 0.3,
    color: "green"
  },
  {
    value: 0.5,
    color: "black",
  },
  {
    color: "red"
  }
]
</code>```

答:
look at this code. change AFTER point = chart.series[0].points[pointIndex]; BEFORE });

```<code>if (thisChart === Highcharts.charts[Highcharts.hoverChartIndex]) {
    Highcharts.charts.forEach(function(chart) {
        point = chart.series[0].points[pointIndex];

        // CHANGE START
        if (point.y == null) {
            // set here your color for null values
            result +=
                '<span style="color:black' +
                '">●</span> ' +
                point.series.name +
                ": <b>" +
                point.y +
                "</b><br/>";
        } else {
          result +=
            '<span style="color:' +
            point.color +
            '">●</span> ' +
            point.series.name +
            ": <b>" +
            point.y +
            "</b><br/>";
        }
        // CHANGE END
    });

  } else {
    result =
      '<span style="color:' +
      this.color +
      '">●</span> ' +
      this.series.name +
      ": <b>" +
      this.y +
      "</b><br/>";
  }
</code>```

Title: Null Values in Zones in Highcharts

Body:
I have graphs that have zones. Currently if there is a null value, that null value is displayed in the tooltip with the zone color of the point before it. I want the null value to always be the color black.

For example,

The tooltip in graph 1 has all the correct information... but "Strength: null" has a green dot. I want to make this dot black because it is a null value.

Is it possible to make this happen? Thanks so much.

https://codepen.io/austeng/pen/gOppRWY

zones: [
  {
    value: 0.3,
    color: "green"
  },
  {
    value: 0.5,
    color: "black",
  },
  {
    color: "red"
  }
]

Body:
look at this code. change AFTER point = chart.series[0].points[pointIndex]; BEFORE });

if (thisChart === Highcharts.charts[Highcharts.hoverChartIndex]) {
    Highcharts.charts.forEach(function(chart) {
        point = chart.series[0].points[pointIndex];

        // CHANGE START
        if (point.y == null) {
            // set here your color for null values
            result +=
                '<span style="color:black' +
                '">●</span> ' +
                point.series.name +
                ": <b>" +
                point.y +
                "</b><br/>";
        } else {
          result +=
            '<span style="color:' +
            point.color +
            '">●</span> ' +
            point.series.name +
            ": <b>" +
            point.y +
            "</b><br/>";
        }
        // CHANGE END
    });

  } else {
    result =
      '<span style="color:' +
      this.color +
      '">●</span> ' +
      this.series.name +
      ": <b>" +
      this.y +
      "</b><br/>";
  }


问:
Evaluate different layout algorithms / interaction with graphs
I have to write a report on the following question:

Evaluate different layout algorithms / interaction with graphs

Where can I find useful resource to understand graph layout algorithms?

I have no experience in graph programming or visualisation, so resources starting from basics would be very helpful.

Thank You

答: The GraphViz project contain lots of different approaches and links to several references.</p>


问:
Dynamically resizing an array being passed in as a double pointer: double free detected
TL;DR: Am I correctly passing my array into grow()?

I am trying to dynamically resize an array when adding elements to it.  Currently I am getting an error message:

```<code>free(): double free detected in tcache 2
</code>```

I am very sure that I am somehow passing this argument incorrectly but I'm relatively knew to pointers so I could use a tip.  here is my main function, I've stripped out most of it.  The problem is most like with the add() and grow() methods.

Edit:  I should add that if I bypass add() just try calling grow() from main it works correctly.

main:

```<code>int main(int argc, char *argv[]){
    // declaring the dynamic array
    const int SIZE = 2;
    float * q;
    q = (float*)malloc(sizeof(float) * SIZE); // initial memory allocation
    int tail = 0;   // tail is the index in which we will add items
    int capacity = SIZE;

    // add stuff to the array
    add(10.0, q, &tail, &capacity);
    add(20.0, q, &tail, &capacity); // crashes during this call!

    return 0;
}

</code>```

Here are my add() and grow() methods which are contained in another file.  Everything seems to be working great until I try to call grow for the second time.

add:

```<code>void add(float element, float* q, int* tail, int* capacity){
    // add the element
    q[*tail] = element;

    // increment tail
    ++*tail;

    // do we need to resize the array?
    if(*tail >= (*capacity) / 2){
        // capacity is already an int* so we don't need the & symbol
        grow(&q, *capacity);
        // update capacity
        *capacity = (*capacity) * 2;
    }
    return;
}
</code>```

grow

```<code>void grow(float* *q, const int capacity){
    printf("# start of grow... capacity = %d\n", capacity);

    // creating temp array
    float  * tmp = (float*)malloc(sizeof(float) * (capacity * 2));

    // copying values
    int i;
    for (i = 0; i < capacity; ++i){
        tmp[i] = (*q)[i];
    }

    // de-allocate old q
    free(*q);

    // re-assign
    *q = tmp;
}
</code>```

答:
```<code>void add(float element, float* q, int* tail, int* capacity){
* * *
        grow(&q, *capacity);
</code>```

You pass the inner q, used in the add. Not the original one. Like changing any other parameter (for example, element = 1.0) it'll not affect the q in main.

You should pass it like

```<code>void add(float element, float* *q, int* tail, int* capacity){
* * *
        grow(q, *capacity);
</code>```

and call it like

```<code>add(10.0, &q, &tail, &capacity);
</code>```

in order to make the q itself as changeable, as tail and capacity currently are. Also, grow can be easily replaced with realloc().

Body:
TL;DR: Am I correctly passing my array into grow()?

I am trying to dynamically resize an array when adding elements to it.  Currently I am getting an error message:

free(): double free detected in tcache 2

I am very sure that I am somehow passing this argument incorrectly but I'm relatively knew to pointers so I could use a tip.  here is my main function, I've stripped out most of it.  The problem is most like with the add() and grow() methods.

Edit:  I should add that if I bypass add() just try calling grow() from main it works correctly.

main:

int main(int argc, char *argv[]){
    // declaring the dynamic array
    const int SIZE = 2;
    float * q;
    q = (float*)malloc(sizeof(float) * SIZE); // initial memory allocation
    int tail = 0;   // tail is the index in which we will add items
    int capacity = SIZE;

    // add stuff to the array
    add(10.0, q, &tail, &capacity);
    add(20.0, q, &tail, &capacity); // crashes during this call!

    return 0;
}

Here are my add() and grow() methods which are contained in another file.  Everything seems to be working great until I try to call grow for the second time.

add:

void add(float element, float* q, int* tail, int* capacity){
    // add the element
    q[*tail] = element;

    // increment tail
    ++*tail;

    // do we need to resize the array?
    if(*tail >= (*capacity) / 2){
        // capacity is already an int* so we don't need the & symbol
        grow(&q, *capacity);
        // update capacity
        *capacity = (*capacity) * 2;
    }
    return;
}

grow

void grow(float* *q, const int capacity){
    printf("# start of grow... capacity = %d\n", capacity);

    // creating temp array
    float  * tmp = (float*)malloc(sizeof(float) * (capacity * 2));

    // copying values
    int i;
    for (i = 0; i < capacity; ++i){
        tmp[i] = (*q)[i];
    }

    // de-allocate old q
    free(*q);

    // re-assign
    *q = tmp;
}

Body:
void add(float element, float* q, int* tail, int* capacity){
* * *
        grow(&q, *capacity);

You pass the inner q, used in the add. Not the original one. Like changing any other parameter (for example, element = 1.0) it'll not affect the q in main.

You should pass it like

void add(float element, float* *q, int* tail, int* capacity){
* * *
        grow(q, *capacity);

and call it like

add(10.0, &q, &tail, &capacity);

in order to make the q itself as changeable, as tail and capacity currently are. Also, grow can be easily replaced with realloc().


问:
My URL isn't being rewritten using the WEB CONFIG
Current URL:

localhost:62859/review.aspx?c=football&t=Liverpool

The URL I'm trying to achieve

localhost:62859/football/Liverpool

The code in web config I'm using to try and achieve this

```<code><rule name="Rewrite Review">
  <match url="^review/([0-9]+)/([_0-9a-z-]+)" />
  <action type="Rewrite" url="?c={R:1}&t={R:2}" />
</rule>
</code>```

This just returns a 404 response. What am I doing wrong?

答:
```<code><rule name="rewrite">
  <match url="^([^/]+)/([^/]+)?$" />
<action type="Rewrite" url="/review.aspx?c={R:1}&t={R:2}" appendQueryString="false" />
</rule>
</code>```

Works.

Body:
Current URL:

localhost:62859/review.aspx?c=football&t=Liverpool

The URL I'm trying to achieve

localhost:62859/football/Liverpool

The code in web config I'm using to try and achieve this

<rule name="Rewrite Review">
  <match url="^review/([0-9]+)/([_0-9a-z-]+)" />
  <action type="Rewrite" url="?c={R:1}&t={R:2}" />
</rule>

This just returns a 404 response. What am I doing wrong?

Body:
<rule name="rewrite">
  <match url="^([^/]+)/([^/]+)?$" />
<action type="Rewrite" url="/review.aspx?c={R:1}&amp;t={R:2}" appendQueryString="false" />
</rule>

Works.


问:
Why aren't changes saved to device after hot reload?
Sometimes I'll write and save some code, Android Studio hot reloads my attached (Android) device, and the changes work as expected. However, if I stop the program on the phone or disconnect the device from Android Studio, the changes are not present--the program looks or works the way it did before I hot reloaded changes. It's as if the changes were in the phone's memory, but not saved as part of the APK on the device. ... Is this the expected behavior? (If so, what setting changes behavior so reloaded code is compiled and saved as part of the APK loaded on the attached phone device?)

I have Android Studio 3.5.3. I did see this post, but it's a few years old now, and I do see my changes; they're just not saved on the device.

答: In debug mode, Flutter app runs on a Dart VM, and hot reload is just reloading the VM, not reinstalling the actual APK.</p>


问:
How can I get data from a Select query as a String data type from a SQLite database?
I'm using this query:

```<code>string query = "SELECT CAST(FullName AS STRING) FROM Register WHERE ID = 1;

DataTable result = SQLiteDataAccess.MakeQuery(query);
</code>```

from this SQLite Table. I'm using System.Data and Dapper to access the SQLite database. The following code is used to access the database:

```<code>public static DataTable MakeQuery(string query)
{
            SQLiteDataReader result;
            DataTable datatable = new DataTable();

        using (SQLiteConnection cnn = new SQLiteConnection(LoadConnectionString()))
        {
            cnn.Open();

            SQLiteCommand command = new SQLiteCommand(query, cnn);
            result = command.ExecuteReader();
            datatable.Load(result);

            cnn.Close();
        }

        return datatable;
    }
</code>```

When I try to use the result, for example with this code:

```<code>        foreach (DataRow record in result.Rows)
        {
            names.Add((string)record["FullName"]);
        }
</code>```

I get the error "System.ArgumentException: 'Column 'FullName' does not belong to table .'" The following locals window screenshot shows that the name of the column is "CAST(FullName AS STRING)" and not "FullName", and the data type is int64, not string.

It seems that I'm using the wrong syntax for casting data types. It must be different in SQLite because it works in SQL Server. What's the correct query in SQLite? Thanks

Edit: Tried a suggestion in a comment and got this error showing the data type is still Int64.

答:
I don't see the point for casting, since your data seems to be stored in a string-like datatype already. So why not just do:

```<code>SELECT FullName FROM Register WHERE ID = 1;
</code>```

If, for some reason, you do nee to cast, then you would need to alias the expression, so you can later on access it from your code:

```<code>SELECT CAST(FullName AS TEXT) FullName FROM Register WHERE ID = 1;
</code>```

Body:
I'm using this query:

string query = "SELECT CAST(FullName AS STRING) FROM Register WHERE ID = 1;

DataTable result = SQLiteDataAccess.MakeQuery(query);

from this SQLite Table. I'm using System.Data and Dapper to access the SQLite database. The following code is used to access the database:

public static DataTable MakeQuery(string query)
{
            SQLiteDataReader result;
            DataTable datatable = new DataTable();

        using (SQLiteConnection cnn = new SQLiteConnection(LoadConnectionString()))
        {
            cnn.Open();

            SQLiteCommand command = new SQLiteCommand(query, cnn);
            result = command.ExecuteReader();
            datatable.Load(result);

            cnn.Close();
        }

        return datatable;
    }

When I try to use the result, for example with this code:

        foreach (DataRow record in result.Rows)
        {
            names.Add((string)record["FullName"]);
        }

I get the error "System.ArgumentException: 'Column 'FullName' does not belong to table .'" The following locals window screenshot shows that the name of the column is "CAST(FullName AS STRING)" and not "FullName", and the data type is int64, not string.

It seems that I'm using the wrong syntax for casting data types. It must be different in SQLite because it works in SQL Server. What's the correct query in SQLite? Thanks

Edit: Tried a suggestion in a comment and got this error showing the data type is still Int64.

Body:
I don't see the point for casting, since your data seems to be stored in a string-like datatype already. So why not just do:

SELECT FullName FROM Register WHERE ID = 1;

If, for some reason, you do nee to cast, then you would need to alias the expression, so you can later on access it from your code:

SELECT CAST(FullName AS TEXT) FullName FROM Register WHERE ID = 1;


问:
What caused bin/rails: compared with non class/module (TypeError)?
I was in the process of Rails upgrade from Rails 5.0.6 to 5.1.7.
I ran this command

```<code>bundle update composite_primary_keys rails activerecord-oracle_enhanced-adapter state_machines-activerecord
</code>```

and then now running rails c gives this:

```<code>Traceback (most recent call last):
bin/rails: compared with non class/module (TypeError)
</code>```

I have no idea how to start fixing

```<code>Traceback (most recent call last):
bin/rails: compared with non class/module (TypeError)
</code>```

Any idea what caused this error?

答:
In the end, running bundle update solve this problem and rails c start running correctly. I suspect the following gem upgrade might be the solution to this issue:

From:

```<code>state_machines-activerecord (0.4.1)
  activerecord (>= 4.1, < 5.2)
  state_machines-activemodel (>= 0.3.0)
</code>```

To:

```<code>state_machines-activerecord (0.6.0)
  activerecord (>= 4.1)
  state_machines-activemodel (>= 0.5.0)
</code>```

Body:
I was in the process of Rails upgrade from Rails 5.0.6 to 5.1.7.
I ran this command

bundle update composite_primary_keys rails activerecord-oracle_enhanced-adapter state_machines-activerecord

and then now running rails c gives this:

Traceback (most recent call last):
bin/rails: compared with non class/module (TypeError)

I have no idea how to start fixing

Traceback (most recent call last):
bin/rails: compared with non class/module (TypeError)

Any idea what caused this error?

Body:
In the end, running bundle update solve this problem and rails c start running correctly. I suspect the following gem upgrade might be the solution to this issue:

From:

state_machines-activerecord (0.4.1)
  activerecord (>= 4.1, < 5.2)
  state_machines-activemodel (>= 0.3.0)

To:

state_machines-activerecord (0.6.0)
  activerecord (>= 4.1)
  state_machines-activemodel (>= 0.5.0)


问:
AWS Congito .NET Core JWT Lambda
We currently have a .NET Core 3.1 app that uses AWS Cognito to log in - that works all fine.

However, we are struggling to get an access token (JWT) which we can then pass on to a request to a Lambda function. All the guides I find seem are either outdated or missing something crucial.

It would be great if we could get the token automatically but then also retrieve it on demand from user claims or similar. We can then add the Bearer token to the request header calling a Lambda function via the API Gateway.

Below is what I have, but I have two issues:

It doesn't provided an error if I purposely give it false information. Is this correct?

I don't know how to get the token from a PageModel so that I can add the token to a header before making a GET request to a Lambda function.

答: You can't really supply the key here because AWS will change it frequently. The solution is to have the code look it up dynamically. This answer to a similar question should help you out.</p>

Title: AWS Congito .NET Core JWT Lambda


问:
Associate user to a post in Django
hi everyone i'm trying to make a blog and i want to associate a user to post .. and to comment , it's a multi-user blog and i don't know how to do it , any help guys ? !

here is the model file :

```<code>from django.db import models
from django.utils import timezone
from django.conf import settings
from django.utils.text import slugify

# Create your models here.
#this is for categories
class Category(models.Model):
    title=models.CharField(max_length=100,default='')
    def __str__(self):
        return self.title
        #this is where a user can create his own gigs
class Gigposter(models.Model):

    title=models.CharField(default='',max_length=100,blank=False)
    user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=False)
    categories=models.OneToOneField(Category,on_delete=models.PROTECT,default='',null=False)
    published_at=models.DateTimeField(auto_now_add=True)
    description=models.TextField(default='',max_length=None,blank=False)
    mainphoto=models.ImageField(default='')
    photo=models.ImageField()
    def __str__(self):
        return self.title

#this is where a user can comment and say what he thinks about others work
class Comment_area(models.Model):

    user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=False)
    comment=models.TextField(max_length=None,default='')
    commented_at=models.DateTimeField(auto_now_add=True)
</code>```

and the views file is empty as you can see :

```<code>from django.shortcuts import render

# Create your views here.
</code>```

答:
If you want to automatically associate a user to a post when working on the admin page, you should redefine save_model method of your model. This method describes everything what should be done when you save your model. In your case you should add something like

```<code>class GigposterAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
    obj.user = `request.user`
    super().save_model(request, obj, form, change)

admin.site.register(Gigposter, GigposterAdmin)
</code>```

to your admin.py. You should also exclude the user field from fieldset in GigposterAdmin. See this for reference.

If you need to identify user in your views, you can always use request.user. In particular, you can pass it as a part of the context for generating a view. Hope this helps.

Title: Associate user to a post in Django

Body:
hi everyone i'm trying to make a blog and i want to associate a user to post .. and to comment , it's a multi-user blog and i don't know how to do it , any help guys ? !

here is the model file :

from django.db import models
from django.utils import timezone
from django.conf import settings
from django.utils.text import slugify

# Create your models here.
#this is for categories
class Category(models.Model):
    title=models.CharField(max_length=100,default='')
    def __str__(self):
        return self.title
        #this is where a user can create his own gigs
class Gigposter(models.Model):

    title=models.CharField(default='',max_length=100,blank=False)
    user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=False)
    categories=models.OneToOneField(Category,on_delete=models.PROTECT,default='',null=False)
    published_at=models.DateTimeField(auto_now_add=True)
    description=models.TextField(default='',max_length=None,blank=False)
    mainphoto=models.ImageField(default='')
    photo=models.ImageField()
    def __str__(self):
        return self.title

#this is where a user can comment and say what he thinks about others work
class Comment_area(models.Model):

    user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=False)
    comment=models.TextField(max_length=None,default='')
    commented_at=models.DateTimeField(auto_now_add=True)

and the views file is empty as you can see :

from django.shortcuts import render

# Create your views here.

Body:
If you want to automatically associate a user to a post when working on the admin page, you should redefine save_model method of your model. This method describes everything what should be done when you save your model. In your case you should add something like

class GigposterAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
    obj.user = `request.user`
    super().save_model(request, obj, form, change)

admin.site.register(Gigposter, GigposterAdmin)

to your admin.py. You should also exclude the user field from fieldset in GigposterAdmin. See this for reference.

If you need to identify user in your views, you can always use request.user. In particular, you can pass it as a part of the context for generating a view. Hope this helps.


答:
This might work for you (GNU sed):

```<code>sed 's/[^|]*/\n&/44;s/\(|.\)\([^|]*|\)\n/\1\n\2/;P;D' file
</code>```

If there is a 44th field, insert a newline before it. Then remove that newline and insert it following the first character of the 43rd field. Print the first line, delete the first line and repeat.

Title: Bash command/script to split line on a certain character

Body:
I would like to split the below data to the expected output:

Raw Data:

931096|376601|1|ART|AT-2151780724|2151780724|2|102809198|I|CGM44I|MIL3VF03|52576377.3600|PENDING|MO|PEND-INFO|Pend ACS4R|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|52576377.3600|1317720|system|2020-02-13 02:00:42|0
931097|375789|1|AYT|AT-2151509210|2151509210|7|102614605|A|CTHGMI|OZF19|444006.6400|APPROVED|NULL|APPROVED|Approved|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|kg17718|NULL|NULL|0.0000|1317722|system|2020-02-13 02:00:43|0931098|375979|1|AHT|AT-2151780726|2151780726|2|102809199|I|CGMI|MILaesLF11|26312.0000|PENDING|MO|PEND-INFO|Pend ACRES|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|26312.0000|1317721|system|2020-02-13 02:00:43|0
931099|376572|1|AT|AT-2151399812|2151399812|5|102673999|I|CG2rMI|WEL44LF15|60991.6956|PENDING|MO|PEND-INFO|Pend ACERS|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|0.0000|1317723|system|2020-02-13 02:00:45|0

Expected Output:

931096|376601|1|ART|AT-2151780724|2151780724|2|102809198|I|CGM44I|MIL3VF03|52576377.3600|PENDING|MO|PEND-INFO|Pend ACS4R|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|52576377.3600|1317720|system|2020-02-13 02:00:42|0
931097|375789|1|AYT|AT-2151509210|2151509210|7|102614605|A|CTHGMI|OZF19|444006.6400|APPROVED|NULL|APPROVED|Approved|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|kg17718|NULL|NULL|0.0000|1317722|system|2020-02-13 02:00:43|0
931098|375979|1|AHT|AT-2151780726|2151780726|2|102809199|I|CGMI|MILaesLF11|26312.0000|PENDING|MO|PEND-INFO|Pend ACRES|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|26312.0000|1317721|system|2020-02-13 02:00:43|0
931099|376572|1|AT|AT-2151399812|2151399812|5|102673999|I|CG2rMI|WEL44LF15|60991.6956|PENDING|MO|PEND-INFO|Pend ACERS|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|0.0000|1317723|system|2020-02-13 02:00:45|0

Basically the \n character is getting lost sometimes in the data and the lines are getting merged. Sometimes more than 1 line gets merged as well (even the opposite happens but we can get to that later).

The data always has 43 columns | separated. The last but one column(42nd) always is a timestamp and the last column is usually 0 or 1.

Trying for the below approach:
If cols > 43
Split 44th column to add \n and print the remaining.
Repeat process until cols=43

echo "${curr}" | awk -F\| ' { if(NF > 43) {for(i=43;i<NF;i++) "sed '${NR}s/\(^0\)/\1\n/p' $i" }}' filename

Body:
This might work for you (GNU sed):

sed 's/[^|]*/\n&/44;s/\(|.\)\([^|]*|\)\n/\1\n\2/;P;D' file

If there is a 44th field, insert a newline before it. Then remove that newline and insert it following the first character of the 43rd field. Print the first line, delete the first line and repeat.


问:
Tensorflow API, Tensorflow hub and Keras input shape
I am working with tf=2.0.0, and tensorflow hub. Currently I am using the Tensorflow data API to load my data which is stored in a tfrecords file.

I am successfully loading the dataset and compiling the model but when I try to fit the data into the model I get the error:

Error when checking input: expected inputs_input to have 1 dimensions,
  but got array with shape (64, 1)

This is how I am loading my data:

```<code>def _dataset_parser(value):
    """Parse a record from value."""
    featdef={
        'id':  tf.io.FixedLenFeature([1], tf.int64),
        'question': tf.io.FixedLenFeature([1], tf.string),
        'label': tf.io.FixedLenFeature([1], tf.int64)
    }

    example = tf.io.parse_single_example(value, featdef)

    label = tf.cast(example['label'], tf.int32)
    question = tf.cast(example['question'], tf.string)
    return example['question'], example['label']
def _input(epochs, batch_size, filenames):
    dataset = tf.data.TFRecordDataset(filenames)

    dataset = dataset.repeat(epochs)
    dataset = dataset.prefetch(1)

    # Parse records.
    dataset = dataset.map(_dataset_parser)
    dataset = dataset.shuffle(100)

    # Batch it up.
    dataset = dataset.batch(batch_size)
    iterator = tf.compat.v1.data.make_one_shot_iterator(dataset)

    question_batch, label_batch = iterator.get_next()
    label_batch = tf.one_hot(label_batch, NUM_CLASSES)

    return question_batch, label_batch

train_ds = _input(20, 64, ['train_xs.tfrecords'])
</code>```

This is my model:

```<code>model = tf.keras.Sequential([
        hub.KerasLayer(HUB_URL, dtype=tf.string, input_shape=[], output_shape=[WIDTH], name='inputs'),
        tf.keras.layers.Dense(256, 'relu', name ='layer_1'),
        tf.keras.layers.Dense(128, 'relu', name = 'layer_2'),
        tf.keras.layers.Dense(NUM_CLASSES, activation='softmax', name='output')
    ])

    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=["accuracy"])
</code>```

I already tried setting the input shape of the entry layer as (None, 1) but it keeps failing, not sure if the problem is due to TensorFlow hub however I tried running this example from the hands-on-ml book:

```<code>model = tf.keras.Sequential([
    hub.KerasLayer("https://tfhub.dev/google/tf2-preview/nnlm-en-dim50/1",
                   dtype=tf.string, input_shape=[], output_shape=[50]),
    tf.keras.layers.Dense(128, activation="relu"),
    tf.keras.layers.Dense(1, activation="sigmoid")
])
model.compile(loss="binary_crossentropy", optimizer="adam",
              metrics=["accuracy"])
datasets, info = tfds.load("imdb_reviews", as_supervised=True, with_info=True)
train_size = info.splits["train"].num_examples
batch_size = 32
train_set = datasets["train"].repeat().batch(batch_size).prefetch(1)
history = model.fit(train_set, steps_per_epoch=5, epochs=5)#steps_per_epoch=train_size // batch_size, epochs=5)
</code>```

and it works fine, however one difference I found is that if I print the train_set on the example from the book I get:

```<code><PrefetchDataset shapes: ((None,), (None,)), types: (tf.string, tf.int64)>
</code>```

Whereas with my code I get this when I print the dataset that I am feeding to the model:

```<code>(<tf.Tensor: id=11409, shape=(64, 1), dtype=string, numpy=  array([[b'Restroom score out of 9'],
        [b'Name'],
        [b'Lastname'],
        [b'Type of house'],
        [b'Inspection date'],
        [b'Pet'],
        [b'Phone'], dtype=object)>,  <tf.Tensor: id=11414, shape=(64, 1, 80), dtype=float32, numpy=  array([[[0., 0., 0., ...,
0., 0., 0.]],

        [[0., 0., 0., ..., 0., 0., 0.]],

        [[0., 0., 0., ..., 0., 0., 0.]],

        ...,

        [[0., 0., 0., ..., 0., 0., 0.]],

        [[0., 0., 0., ..., 0., 0., 0.]],

        [[0., 0., 0., ..., 0., 0., 0.]]], dtype=float32)>)
</code>```

Does someone know why the difference in the shape of the data?

答:
Not sure why, but by changing the feature definition to

```<code> featdef={
        'id':  tf.io.FixedLenFeature([], tf.int64),
        'question': tf.io.FixedLenFeature([], tf.string),
        'label': tf.io.FixedLenFeature([], tf.int64)
    }
</code>```

it worked

Body:
I am working with tf=2.0.0, and tensorflow hub. Currently I am using the Tensorflow data API to load my data which is stored in a tfrecords file.

I am successfully loading the dataset and compiling the model but when I try to fit the data into the model I get the error:

Error when checking input: expected inputs_input to have 1 dimensions,
  but got array with shape (64, 1)

This is how I am loading my data:

def _dataset_parser(value):
    """Parse a record from value."""
    featdef={
        'id':  tf.io.FixedLenFeature([1], tf.int64),
        'question': tf.io.FixedLenFeature([1], tf.string),
        'label': tf.io.FixedLenFeature([1], tf.int64)
    }

    example = tf.io.parse_single_example(value, featdef)

    label = tf.cast(example['label'], tf.int32)
    question = tf.cast(example['question'], tf.string)
    return example['question'], example['label']
def _input(epochs, batch_size, filenames):
    dataset = tf.data.TFRecordDataset(filenames)

    dataset = dataset.repeat(epochs)
    dataset = dataset.prefetch(1)

    # Parse records.
    dataset = dataset.map(_dataset_parser)
    dataset = dataset.shuffle(100)

    # Batch it up.
    dataset = dataset.batch(batch_size)
    iterator = tf.compat.v1.data.make_one_shot_iterator(dataset)

    question_batch, label_batch = iterator.get_next()
    label_batch = tf.one_hot(label_batch, NUM_CLASSES)

    return question_batch, label_batch

train_ds = _input(20, 64, ['train_xs.tfrecords'])

This is my model:

model = tf.keras.Sequential([
        hub.KerasLayer(HUB_URL, dtype=tf.string, input_shape=[], output_shape=[WIDTH], name='inputs'),
        tf.keras.layers.Dense(256, 'relu', name ='layer_1'),
        tf.keras.layers.Dense(128, 'relu', name = 'layer_2'),
        tf.keras.layers.Dense(NUM_CLASSES, activation='softmax', name='output')
    ])

    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=["accuracy"])

I already tried setting the input shape of the entry layer as (None, 1) but it keeps failing, not sure if the problem is due to TensorFlow hub however I tried running this example from the hands-on-ml book:

model = tf.keras.Sequential([
    hub.KerasLayer("https://tfhub.dev/google/tf2-preview/nnlm-en-dim50/1",
                   dtype=tf.string, input_shape=[], output_shape=[50]),
    tf.keras.layers.Dense(128, activation="relu"),
    tf.keras.layers.Dense(1, activation="sigmoid")
])
model.compile(loss="binary_crossentropy", optimizer="adam",
              metrics=["accuracy"])
datasets, info = tfds.load("imdb_reviews", as_supervised=True, with_info=True)
train_size = info.splits["train"].num_examples
batch_size = 32
train_set = datasets["train"].repeat().batch(batch_size).prefetch(1)
history = model.fit(train_set, steps_per_epoch=5, epochs=5)#steps_per_epoch=train_size // batch_size, epochs=5)

and it works fine, however one difference I found is that if I print the train_set on the example from the book I get:

<PrefetchDataset shapes: ((None,), (None,)), types: (tf.string, tf.int64)>

Whereas with my code I get this when I print the dataset that I am feeding to the model:

(<tf.Tensor: id=11409, shape=(64, 1), dtype=string, numpy=  array([[b'Restroom score out of 9'],
        [b'Name'],
        [b'Lastname'],
        [b'Type of house'],
        [b'Inspection date'],
        [b'Pet'],
        [b'Phone'], dtype=object)>,  <tf.Tensor: id=11414, shape=(64, 1, 80), dtype=float32, numpy=  array([[[0., 0., 0., ...,
0., 0., 0.]],

        [[0., 0., 0., ..., 0., 0., 0.]],

        [[0., 0., 0., ..., 0., 0., 0.]],

        ...,

        [[0., 0., 0., ..., 0., 0., 0.]],

        [[0., 0., 0., ..., 0., 0., 0.]],

        [[0., 0., 0., ..., 0., 0., 0.]]], dtype=float32)>)

Does someone know why the difference in the shape of the data?

Body:
Not sure why, but by changing the feature definition to

 featdef={
        'id':  tf.io.FixedLenFeature([], tf.int64),
        'question': tf.io.FixedLenFeature([], tf.string),
        'label': tf.io.FixedLenFeature([], tf.int64)
    }

it worked


问:
Extract all values when I have key : value and store all value in an array
If I have an array,I want to extract each values in each line (values after (:) )

```<code>Array =
0:Object {node-input-audio_services1: "79388", audio_ip: "127.0.0.1", audio_port_1: "7654"}
1:Object {node-input-video_services1: "80788", video_ip: "127.0.0.1", video_port_1: "7654"}
2:Object {node-input-audio_services1: "4fe10"}
3:Object {node-input-video_services1: "4fe10"}
</code>```

Imagine I have several key : value then I want to extract Just value like bellow:

```<code>Array =
0:Object {key1 : "value" , Key2 : "value2" , key3: "value3"}
1:Object {key1 : "value5" , Key2 : "value6" , key3: "value7"}

</code>```

I have the result like this :

```<code>var result = ["value","value2",value3","value5","value6","value7"];
</code>```

The problem is, I can't use (key1.array) because each time in my program have one key's name.I really new in JavaScript and don't know how I can start

答:
const arr = [{
    key1: "value",
    Key2: "value2",
    key3: "value3"
  },
  {
    key1: "value5",
    Key2: "value6",
    key3: "value7"
  }
];

let out = arr.reduce(
  (c, v) => c.concat(Object.values(v)), []
);
console.log(out);```

Body:
If I have an array,I want to extract each values in each line (values after (:) )

Array =
0:Object {node-input-audio_services1: "79388", audio_ip: "127.0.0.1", audio_port_1: "7654"}
1:Object {node-input-video_services1: "80788", video_ip: "127.0.0.1", video_port_1: "7654"}
2:Object {node-input-audio_services1: "4fe10"}
3:Object {node-input-video_services1: "4fe10"}

Imagine I have several key : value then I want to extract Just value like bellow:

Array =
0:Object {key1 : "value" , Key2 : "value2" , key3: "value3"}
1:Object {key1 : "value5" , Key2 : "value6" , key3: "value7"}

I have the result like this :

var result = ["value","value2",value3","value5","value6","value7"];

The problem is, I can't use (key1.array) because each time in my program have one key's name.I really new in JavaScript and don't know how I can start


问:
How to make MutableLiveData<String> to trigger onChanged?
Help me out please.

I want to observe some String using LiveData.

OnChanged() getting triggered once upon app start, but when Im changing the value of string1 by button click, onChange() does not trigger and information is not updated. TextView keeps showing "Wow"

I do everything exactly as described here.

The ViewModel:

```<code>class CurrentViewModel : ViewModel() {

val currentName: MutableLiveData<String> by lazy {
    MutableLiveData<String>()
}
}
</code>```

The Fragment:

```<code>class CurrentFragment : Fragment(R.layout.current_fragment) {
        private val viewModel: CurrentViewModel by viewModels()
       var string1 = "Wow!"

  override fun onActivityCreated(savedInstanceState: Bundle?)
       val nameObserver = Observer<String> { newName ->
            textview.text = newName        }
       viewModel.currentName.value = string1
       viewModel.currentName.observe(activity!!, nameObserver)

   button.setOnClickListener {
            string1 = "some new string"
        }
}
</code>```

答:
You are not updating the value of viewModel.currentName you should always update the MutableLiveData's value to notify the observers.

Inside of your OnClickListener do:

```<code>button.setOnClickListener {
    // update viewModel value to notify listeners/observers
    viewModel.currentName.value = "some new string"
}
</code>```

Obs: You can remove string1 as it is useless!

Body:
Help me out please.

I want to observe some String using LiveData.

OnChanged() getting triggered once upon app start, but when Im changing the value of string1 by button click, onChange() does not trigger and information is not updated. TextView keeps showing "Wow"

I do everything exactly as described here.

The ViewModel:

class CurrentViewModel : ViewModel() {

val currentName: MutableLiveData<String> by lazy {
    MutableLiveData<String>()
}
}

The Fragment:

class CurrentFragment : Fragment(R.layout.current_fragment) {
        private val viewModel: CurrentViewModel by viewModels()
       var string1 = "Wow!"

  override fun onActivityCreated(savedInstanceState: Bundle?)
       val nameObserver = Observer<String> { newName ->
            textview.text = newName        }
       viewModel.currentName.value = string1
       viewModel.currentName.observe(activity!!, nameObserver)

   button.setOnClickListener {
            string1 = "some new string"
        }
}

Body:
You are not updating the value of viewModel.currentName you should always update the MutableLiveData's value to notify the observers.

Inside of your OnClickListener do:

button.setOnClickListener {
    // update viewModel value to notify listeners/observers
    viewModel.currentName.value = "some new string"
}

Obs: You can remove string1 as it is useless!


问:
Conditionally changing the label of a navigation bar item to a shorter label results in incorrect alignment
When switching the navigation bar item label from a longer label to a shorter one, the new, shorter, label will be aligned at the center of the old label, as in the two images below:

This is the code for the problem:

```<code>struct NavBarItemIssueView: View {
    @State private var isLargeView = true

    var body: some View {
        NavigationView {
            Text("Some text")
                .navigationBarItems(leading: Button(action: {
                    self.isLargeView.toggle()
                }) {
                    if self.isLargeView == true {
                        Text("Show small label")
                    } else {
                        Text("Small")

                    }
                })
        }
    }
}
</code>```

In the app I am making I have to switch between two labels when the edit mode is enabled or disabled and this problem occurs. Is there a way to fix this alignment in swift(ui)?

答:
You can set a frame on your button with minWidth that is about the width of your biggest button, then you can align the button to the leading edge:

        NavigationView {
            Text("Some text")
                .navigationBarItems(leading: Button(action: {
                    self.isLargeView.toggle()
                }) {
                    if self.isLargeView == true {
                        Text("Show small label")
                    } else {
                        Text("Small")

                    }
                }
                .frame(minWidth: 200, alignment: .leading)
            )
        }
```

Body:
When switching the navigation bar item label from a longer label to a shorter one, the new, shorter, label will be aligned at the center of the old label, as in the two images below:

This is the code for the problem:

struct NavBarItemIssueView: View {
    @State private var isLargeView = true

    var body: some View {
        NavigationView {
            Text("Some text")
                .navigationBarItems(leading: Button(action: {
                    self.isLargeView.toggle()
                }) {
                    if self.isLargeView == true {
                        Text("Show small label")
                    } else {
                        Text("Small")

                    }
                })
        }
    }
}

In the app I am making I have to switch between two labels when the edit mode is enabled or disabled and this problem occurs. Is there a way to fix this alignment in swift(ui)?


问:
seleniumElement.click() wasnot work vb.net
what wrong of code that make this error pleze
error ;click is not member of openqa.selenium</p>

```<code>Imports System.Text
Imports OpenQA.Selenium
Imports OpenQA.Selenium.Chrome

Module Module1

    Sub Main()
        Dim driver As IWebDriver
        driver = New ChromeDriver
        driver.Navigate().GoToUrl("https://m.facebook.com/")
        Dim element As IWebDriver = driver.FindElement(By.Id("u_0_b"))
        System.Threading.Thread.Sleep(10000)
        element.Click()
    End Sub

End Module
</code>```

答:
The type IWebDriver does not have a click method. Change the type for the element variable in the declaration to IWebElement:

```<code>Dim element As IWebElement = driver.FindElement(By.Id("u_0_b"))
</code>```

Body:
what wrong of code that make this error pleze
error ;click is not member of openqa.selenium

Imports System.Text
Imports OpenQA.Selenium
Imports OpenQA.Selenium.Chrome

Module Module1

    Sub Main()
        Dim driver As IWebDriver
        driver = New ChromeDriver
        driver.Navigate().GoToUrl("https://m.facebook.com/")
        Dim element As IWebDriver = driver.FindElement(By.Id("u_0_b"))
        System.Threading.Thread.Sleep(10000)
        element.Click()
    End Sub

End Module

Body:
The type IWebDriver does not have a click method. Change the type for the element variable in the declaration to IWebElement:

Dim element As IWebElement = driver.FindElement(By.Id("u_0_b"))


问:
Pandas Dataframe Update Rows
Let's say that I have a dataframe, X, initiated with 0s and a dimension m x n. I have n unique values (1,2,3,...,n) in a pandas.series, Y, that has length m. How do I set the Y[i] column of the ith row of X (change 0 to 1) efficiently without using a loop. Especially for large m and n.</p>

```<code>For example, for Y = [3,2,1]
X
row     1       2      3
0       0       0      0
1       0       0      0
2       0       0      0

to
row     1       2      3
0       0       0      1
1       0       1      0
2       1       0      0
</code>```

答:
I'm not sure why you are against for loops.  This should be fairly efficient.

```<code>for row, col in enumerate(Y):
    df.iat[n, col] = 1
</code>```

You could also compute the index locations and set their values to one, then reshape the result to the m x n shape of the matrix.

```<code>Y = [3, 2, 1]
n = 5
m = len(Y)
locations = set(row * n + col for row, col in enumerate(Y))
df = pd.DataFrame(
    np.array([1 if idx in locations else 0 for idx in range(m * n)]).reshape((m, n))
)
>>> df
   0  1  2  3  4
0  0  0  0  1  0
1  0  0  1  0  0
2  0  1  0  0  0
</code>```

Title: Pandas Dataframe Update Rows

Body:
Let's say that I have a dataframe, X, initiated with 0s and a dimension m x n. I have n unique values (1,2,3,...,n) in a pandas.series, Y, that has length m. How do I set the Y[i] column of the ith row of X (change 0 to 1) efficiently without using a loop. Especially for large m and n.

For example, for Y = [3,2,1]
X
row     1       2      3
0       0       0      0
1       0       0      0
2       0       0      0

to
row     1       2      3
0       0       0      1
1       0       1      0
2       1       0      0

Body:
I'm not sure why you are against for loops.  This should be fairly efficient.

for row, col in enumerate(Y):
    df.iat[n, col] = 1

You could also compute the index locations and set their values to one, then reshape the result to the m x n shape of the matrix.

Y = [3, 2, 1]
n = 5
m = len(Y)
locations = set(row * n + col for row, col in enumerate(Y))
df = pd.DataFrame(
    np.array([1 if idx in locations else 0 for idx in range(m * n)]).reshape((m, n))
)
>>> df
   0  1  2  3  4
0  0  0  0  1  0
1  0  0  1  0  0
2  0  1  0  0  0


问:
How To Trigger Button Click On A Web That Uses History API HTML5 Using JavaScript?
I'm developing a Chrome Extension that automates click. My extension worked on Multi-Page Application. It can click the buttons on the website. But I'm having a problem with this specific website which is a Single Page Application.

My extension can't trigger button click using this JavaScript

```<code>function clickButton(){
var submit =  document.getElementsByClassName(".class");
submit.click();
}
</code>```

My Question is, how to trigger button click on a single page application? Because it seems like using .click() isn't working

Further information

The way my extension works is that I click on a search button, it shows me result. If there is a result, I do specific things. But if result is empty, I go back to previous page (search page) and then hit the search button again. And my extension can't click the search button nor back button. My assumption is, when I click the button using .click(), the web doesn't request that specific HTML page to show. Am I wrong?

Another Info About This Site

So this web is a single page application. After I login to this site, it brings me to https://sample.com/page1 -which is a home. Then I go to the search page (the URL is still the same but it shows a different layout, which is search page). On the search page, I input the search parameters, then hit the search button (the URL is still the same but it shows the different layout, which is search results). So I guess the way these web works is every time I click on a certain page, it requests page layout using history.pushState -i guess. So I'm wondering if there's a way to manipulate this history.pushState? For example, instead of clicking the back button, can I just go straight to the desired page?

答:
document.getElementsByClassName(".class") returns an array, so array.onclick() will not work.

To trigger html event, not only click:

```<code>function trigger(elm, type) {
  if (elm) {
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent(type, true, true);
    elm.dispatchEvent(evt);
  }
}
</code>```

In your case, I think you want:

```<code>trigger(document.querySelector('.class'), 'click')
</code>```

Body:
I'm developing a Chrome Extension that automates click. My extension worked on Multi-Page Application. It can click the buttons on the website. But I'm having a problem with this specific website which is a Single Page Application.

My extension can't trigger button click using this JavaScript

function clickButton(){
var submit =  document.getElementsByClassName(".class");
submit.click();
}

My Question is, how to trigger button click on a single page application? Because it seems like using .click() isn't working

Further information

The way my extension works is that I click on a search button, it shows me result. If there is a result, I do specific things. But if result is empty, I go back to previous page (search page) and then hit the search button again. And my extension can't click the search button nor back button. My assumption is, when I click the button using .click(), the web doesn't request that specific HTML page to show. Am I wrong?

Another Info About This Site

So this web is a single page application. After I login to this site, it brings me to https://sample.com/page1 -which is a home. Then I go to the search page (the URL is still the same but it shows a different layout, which is search page). On the search page, I input the search parameters, then hit the search button (the URL is still the same but it shows the different layout, which is search results). So I guess the way these web works is every time I click on a certain page, it requests page layout using history.pushState -i guess. So I'm wondering if there's a way to manipulate this history.pushState? For example, instead of clicking the back button, can I just go straight to the desired page?

Body:
document.getElementsByClassName(".class") returns an array, so array.onclick() will not work.

To trigger html event, not only click:

function trigger(elm, type) {
  if (elm) {
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent(type, true, true);
    elm.dispatchEvent(evt);
  }
}

In your case, I think you want:

trigger(document.querySelector('.class'), 'click')


问:
Create methods in object in javascript
Can anyone help me for solving this question.I can't understand how we access methods from functions

Task: implement a function to create a "user" object.

Technical requirements:

Write the createNewUser() function, which will create and return the newUser object.

The function should ask the caller for the name and surname during the call.
  Create an object newUser with properties firstName and lastName, using the data entered by the user.

Add the getLogin() method to the newUser object, which will return the first letter of the user name connected to the user surname, all in lower case (for example, Ivan Kravchenko → ikravchenko).

Create a user using the createNewUser() function. Call the getLogin() function from the user. Display the result of the function execution in the console.

An optional advanced complexity assignment:

Make the properties firstName and lastName cannot be changed directly. Create setter functions setFirstName() and setLastName(), which will allow you to change these properties.

This is how I approached this, but it doesn't work:

```<code>let user = {
    firstName:firstName,
    lastName:lastName,
    createNewUser:function(){
        this.firstName=prompt("Enter your first name: ");
        this.lastName=prompt("Enter your last name: ");
        return `${this.firstName} ${this.lastName}`;
    },
    getLogin:function(){
        return `${this.firstName[0]}+${this.lastName}`.toLowerCase();
    },
    setFirstName:function(){
        this.firstName=prompt("Set your first name: ");
    },
    setLastName:function(){
        this.lastName=prompt("Set your last name: ");
    }
}

user.createNewUser();
</code>```

答:
This should get you started check out here.</p>

```<code>class User {

constructor(first, last) {
  this.firstName = first;
  this.lastName = last;
}

getLogin(){
// Your code here

}

var person = new User("John", "Doe");
</code>```

Title: Create methods in object in javascript

Body:
Can anyone help me for solving this question.I can't understand how we access methods from functions

Task: implement a function to create a "user" object.

Technical requirements:

Write the createNewUser() function, which will create and return the newUser object.

The function should ask the caller for the name and surname during the call.
  Create an object newUser with properties firstName and lastName, using the data entered by the user.

Add the getLogin() method to the newUser object, which will return the first letter of the user name connected to the user surname, all in lower case (for example, Ivan Kravchenko → ikravchenko).

Create a user using the createNewUser() function. Call the getLogin() function from the user. Display the result of the function execution in the console.

An optional advanced complexity assignment:

Make the properties firstName and lastName cannot be changed directly. Create setter functions setFirstName() and setLastName(), which will allow you to change these properties.

This is how I approached this, but it doesn't work:

let user = {
    firstName:firstName,
    lastName:lastName,
    createNewUser:function(){
        this.firstName=prompt("Enter your first name: ");
        this.lastName=prompt("Enter your last name: ");
        return `${this.firstName} ${this.lastName}`;
    },
    getLogin:function(){
        return `${this.firstName[0]}+${this.lastName}`.toLowerCase();
    },
    setFirstName:function(){
        this.firstName=prompt("Set your first name: ");
    },
    setLastName:function(){
        this.lastName=prompt("Set your last name: ");
    }
}

user.createNewUser();

Body:
This should get you started check out here.

class User {

constructor(first, last) {
  this.firstName = first;
  this.lastName = last;
}

getLogin(){
// Your code here

}

var person = new User("John", "Doe");


问:
Using Groovy beta 3, but can't find a Spock version that will work it
I'm using Groovy beta 3 to use the method references feature etc

I can't find a Spock version that seems to work with the Groovy 3 beta.

Is there a test version of Spock that works with the Groovy 3 codelines?

I tried this in my Gradle build, exclude the default Groovy 2.5 dependency, but this gives a build failure:

```<code>testCompile (group: 'org.spockframework', name: 'spock-core', version: '1.3-groovy-2.5') {
        exclude group: 'org.codehaus.groovy', name: 'groovy-all'
    }
</code>```

答:
Spock supports Groovy 3 starting with version 2.0-M2.

For Gradle it should be enough to add a Spock's JAR dedicated for Groovy 3:

```<code>testImplementation('org.spockframework:spock-core:2.0-M2-groovy-3.0')
</code>```

and enable JUnit Platform:

```<code>test {
    useJUnitPlatform()
}
</code>```

As a person who developed support for Groovy 3 in Spock I gathered various aspects (including caveats) relating migration from Spock 1.3 to 2.0 in a blog post - it might be worth to read it :-).

Body:
I'm using Groovy beta 3 to use the method references feature etc

I can't find a Spock version that seems to work with the Groovy 3 beta.

Is there a test version of Spock that works with the Groovy 3 codelines?

I tried this in my Gradle build, exclude the default Groovy 2.5 dependency, but this gives a build failure:

testCompile (group: 'org.spockframework', name: 'spock-core', version: '1.3-groovy-2.5') {
        exclude group: 'org.codehaus.groovy', name: 'groovy-all'
    }

Body:
Spock supports Groovy 3 starting with version 2.0-M2.

For Gradle it should be enough to add a Spock's JAR dedicated for Groovy 3:

testImplementation('org.spockframework:spock-core:2.0-M2-groovy-3.0')

and enable JUnit Platform:

test {
    useJUnitPlatform()
}

As a person who developed support for Groovy 3 in Spock I gathered various aspects (including caveats) relating migration from Spock 1.3 to 2.0 in a blog post - it might be worth to read it :-).