问:
C++ Storing a string into a class
I made a topic a bit ago regarding structs. And I know that classes have the same concept as structs. How would I go about storing a string into the class?

This is the class

```<code>class studentType
{
public:
    void setData(string, int);
    string getName() const;
    int getId() const;
private:
    string name;
    int sid;
};

void studentType::setData(string, int) {
    name = ??;
    sid = ??;
}

string studentType::getName() const {
    return name;
}

int studentType::getId() const {
    return sid;
}
</code>```

The main consists of:

```<code>int main() {

    studentType object, number;

    cout << "enter name and code of item1: ";
    cin >> object.setData() >> object.setData();
    cout << "enter name and code for item2: ";
    cin >> number.setData() >> number.setData();

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

How would I fix the cin issue? I already have string defined in the header. And yes, I know using namespace std; isn't preferred but it's for simplicity

答:
```<code>int id;
string name;
cout << "enter name and code of item1: ";
cin >> name >> id;
object.setData(name, id);
cout << "enter name and code for item2: ";
cin >> name >> id;
object.setData(name, id);
</code>```

You should instead use a constructor for your class though:

```<code>class studentType {
public:
    studentType(string name, int sid)
        : name(name)
        , sid(sid)
    { }
// ...
</code>```

You can then initialize your objects with the correct name and ID:

```<code>cin >> name >> id;
studentType object(name, id);
</code>```

But I suppose constructors will come up very soon in the tutorial or course you're currently doing.

Title: C++ Storing a string into a class

Body:
I made a topic a bit ago regarding structs. And I know that classes have the same concept as structs. How would I go about storing a string into the class?

This is the class

class studentType
{
public:
    void setData(string, int);
    string getName() const;
    int getId() const;
private:
    string name;
    int sid;
};

void studentType::setData(string, int) {
    name = ??;
    sid = ??;
}

string studentType::getName() const {
    return name;
}

int studentType::getId() const {
    return sid;
}

The main consists of:

int main() {

    studentType object, number;

    cout << "enter name and code of item1: ";
    cin >> object.setData() >> object.setData();
    cout << "enter name and code for item2: ";
    cin >> number.setData() >> number.setData();

    system("pause");
    return 0;
}

How would I fix the cin issue? I already have string defined in the header. And yes, I know using namespace std; isn't preferred but it's for simplicity

Body:
int id;
string name;
cout << "enter name and code of item1: ";
cin >> name >> id;
object.setData(name, id);
cout << "enter name and code for item2: ";
cin >> name >> id;
object.setData(name, id);

You should instead use a constructor for your class though:

class studentType {
public:
    studentType(string name, int sid)
        : name(name)
        , sid(sid)
    { }
// ...

You can then initialize your objects with the correct name and ID:

cin >> name >> id;
studentType object(name, id);

But I suppose constructors will come up very soon in the tutorial or course you're currently doing.


来源: stackexchange

问:
Javascript second prompt is not showing as expected
I'm trying to code a rock paper scissors game where when I hit the new game button in the middle of the screen it prompts the user for two name inputs. I've seen this in action before but I can't figure out where I'm going wrong. Hopefully this is enough code to figure it out, otherwise I can post more! Thanks in advance.</p>

```<code>$('#gameController').bind('click', function() {
    if (game.running === false) {
       if ($(this).text() == 'New Game') {
           for (i = 1; i < 3; i++) {
               do {
                  var player = prompt('Player ' + i + ', enter your name...');
            } while (!player);
            $('#player' + i + 'Name').text(player);
            game.addPlayer(player);
        }
    };
</code>```

答: You can use alert() e.g. var player = alert('Player ' + i + ', enter your name...');

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to code a rock paper scissors game where when I hit the new game button in the middle of the screen it prompts the user for two name inputs. I've seen this in action before but I can't figure out where I'm going wrong. Hopefully this is enough code to figure it out, otherwise I can post more! Thanks in advance.

$('#gameController').bind('click', function() {
    if (game.running === false) {
       if ($(this).text() == 'New Game') {
           for (i = 1; i < 3; i++) {
               do {
                  var player = prompt('Player ' + i + ', enter your name...');
            } while (!player);
            $('#player' + i + 'Name').text(player);
            game.addPlayer(player);
        }
    };


问:
Powershell New-ADUser set as enable
So i'm trying to create a list of new users in powershell on my windows server 2012 r2. I want the users name as Mike, Linda, Kurt. I run the following command

```<code>New-ADUser Kurt -enabled
</code>```

I get an error as that does not work. I know that this command exists and works

```<code>New-ADUser Kurt
</code>```

Is there a command to create a new user and set it to enabled without setting a password to it? I'm a beginner at powershell

答:
You will need to add the $true value to the -Enabled flag, like so:

```<code>New-ADUser Kurt -Enabled $true
</code>```

This is because the -Enabled flag expects a boolean value (true, false) to be sent to it.

Title: Powershell New-ADUser set as enable

Body:
So i'm trying to create a list of new users in powershell on my windows server 2012 r2. I want the users name as Mike, Linda, Kurt. I run the following command

New-ADUser Kurt -enabled

I get an error as that does not work. I know that this command exists and works

New-ADUser Kurt

Is there a command to create a new user and set it to enabled without setting a password to it? I'm a beginner at powershell

Body:
You will need to add the $true value to the -Enabled flag, like so:

New-ADUser Kurt -Enabled $true

This is because the -Enabled flag expects a boolean value (true, false) to be sent to it.


问:
Pull a certain branch from the remote server
Say that someone created a branch xyz. How do I pull the branch xyz from the remote server (e.g. GitHub) and merge it into an existing branch xyz in my local repo?

The answer to
Push branches to Git gives me the error "! [rejected]" and mentions "non fast forward".

答:
```<code>git pull <gitreponame> <branchname>
</code>```

Usually if you have only repo assigned to your code then the gitreponame would be origin.

If you are working on two repo's like one is local and another one for remote like you can check repo's list from git remote -v. this shows how many repo's are assigned to your current code.

BranchName should exists into corresponding gitreponame.

you can use following two commands to add or remove repo's

```<code>git remote add <gitreponame> <repourl>
git remote remove <gitreponame>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
git pull <gitreponame> <branchname>

Usually if you have only repo assigned to your code then the gitreponame would be origin.

If you are working on two repo's like one is local and another one for remote like you can check repo's list from git remote -v. this shows how many repo's are assigned to your current code.

BranchName should exists into corresponding gitreponame.

you can use following two commands to add or remove repo's

git remote add <gitreponame> <repourl>
git remote remove <gitreponame>


问:
encrypt href link in url using javascript
```<code>file:///C:/xx/xx/xx/xx/xx/xx/studentInfo.html
</code>```

I want to encrypt the studentInfo.html into characters like for example

file:///C:/xx/xx/xx/xx/xx/xx/A%1fs%fdd.html

using javascript? How can I do this?

答:
You could encode it in Base64 with with the atob() (decode) and btoa() (encode) javascript fonctions.

```<code>var path = "file:///C:/xx/xx/xx/xx/xx/xx/"
var file = "studentInfo.html"
console.log(path + btoa(file))
// Output: file:///C:/xx/xx/xx/xx/xx/xx/c3R1ZGVudEluZm8uaHRtbA==
</code>```

Body:
file:///C:/xx/xx/xx/xx/xx/xx/studentInfo.html

I want to encrypt the studentInfo.html into characters like for example

file:///C:/xx/xx/xx/xx/xx/xx/A%1fs%fdd.html

using javascript? How can I do this?

Body:
You could encode it in Base64 with with the atob() (decode) and btoa() (encode) javascript fonctions.

var path = "file:///C:/xx/xx/xx/xx/xx/xx/"
var file = "studentInfo.html"
console.log(path + btoa(file))
// Output: file:///C:/xx/xx/xx/xx/xx/xx/c3R1ZGVudEluZm8uaHRtbA==


问:
Print

 only?
How do I print the indicated div (without manually disabling all other content on the page)?

I want to avoid a new preview dialog, so creating a new window with this content is not useful.

The page contains a couple of tables, one of them contains the div I want to print - the table is styled with visual styles for the web, that should not show in print.

答:
printDiv(divId):  A generalized solution to print any div on any page.

I had a similar issue but I wanted (a) to be able to print the whole page, or (b) print any one of several specific areas.  My solution, thanks to much of the above, allows you to specify any div object to be printed.

The key for this solution is to add an appropriate rule to the the print media style sheet so that the requested div (and its contents) will be printed.

First, create the needed print css to suppress everything (but without the specific rule to allow the element you want to print).

```<code><style type="text/css" media="print">
   body {visibility:hidden; }
   .noprintarea {visibility:hidden; display:none}
   .noprintcontent { visibility:hidden; }
   .print { visibility:visible; display:block; }
</style>
</code>```

Note that I have added new class rules:

noprintarea allows you to suppress the printing of elements within your div- both the content and the block.

noprintcontent allows you to suppress the printing of elements within your div- the content is suppressed but and the allocated area is left empty.

print allows you to have items that show up in the printed version but
not on the screen page.  These will normally have "display:none" for the screen style.

Then insert three JavaScript functions.  The first merely toggles the print media style sheet on and off.

```<code>function disableSheet(thisSheet,setDisabled)
{ document.styleSheets[thisSheet].disabled=setDisabled; }
</code>```

The second does the real work and the third cleans up afterward.  The second (printDiv) activates the print media style sheet, then appends a new rule to allow the desired div to print, issues the print, and then adds a delay before the final housekeeping (otherwise the styles can be reset before the print is actually done.)

```<code>function printDiv(divId)
{
  //  Enable the print CSS: (this temporarily disables being able to print the whole page)
  disableSheet(0,false);
  //  Get the print style sheet and add a new rule for this div
  var sheetObj=document.styleSheets[0];
  var showDivCSS="visibility:visible;display:block;position:absolute;top:30px;left:30px;";
  if (sheetObj.rules) { sheetObj.addRule("#"+divId,showDivCSS); }
  else                { sheetObj.insertRule("#"+divId+"{"+showDivCSS+"}",sheetObj.cssRules.length); }
  print();
  //  need a brief delay or the whole page will print
  setTimeout("printDivRestore()",100);
}
</code>```

The final functions deletes the added rule and sets the print style again to disabled so the whole page can be printed.

```<code>function printDivRestore()
{
  // remove the div-specific rule
  var sheetObj=document.styleSheets[0];
  if (sheetObj.rules) { sheetObj.removeRule(sheetObj.rules.length-1); }
  else                { sheetObj.deleteRule(sheetObj.cssRules.length-1); }
  //  and re-enable whole page printing
  disableSheet(0,true);
}
</code>```

The only other thing to do is to add one line to your onload processing so that the print style is initially disabled thereby allowing whole page printing.

```<code><body onLoad='disableSheet(0,true)'>
</code>```

Then, from anywhere in your document, you can print a div. Just issue printDiv("thedivid") from a button or whatever.

A big plus for this approach it provides a general solution to printing selected content from within a page.  It also allows use of existing styles for elements that are printed - including the containing div.

NOTE:  In my implementation, this must be the first style sheet.  Change the sheet references (0) to the appropriate sheet number if you need to make it later in the sheet sequence.

OwnerDisplayName: noesgard

Title:
Print

 only?

LastEditorDisplayName: pkaeding

Body:
printDiv(divId):  A generalized solution to print any div on any page.

I had a similar issue but I wanted (a) to be able to print the whole page, or (b) print any one of several specific areas.  My solution, thanks to much of the above, allows you to specify any div object to be printed.

The key for this solution is to add an appropriate rule to the the print media style sheet so that the requested div (and its contents) will be printed.

First, create the needed print css to suppress everything (but without the specific rule to allow the element you want to print).

<style type="text/css" media="print">
   body {visibility:hidden; }
   .noprintarea {visibility:hidden; display:none}
   .noprintcontent { visibility:hidden; }
   .print { visibility:visible; display:block; }
</style>

Note that I have added new class rules:

noprintarea allows you to suppress the printing of elements within your div- both the content and the block.

noprintcontent allows you to suppress the printing of elements within your div- the content is suppressed but and the allocated area is left empty.

print allows you to have items that show up in the printed version but
not on the screen page.  These will normally have "display:none" for the screen style.

Then insert three JavaScript functions.  The first merely toggles the print media style sheet on and off.

function disableSheet(thisSheet,setDisabled)
{ document.styleSheets[thisSheet].disabled=setDisabled; }

The second does the real work and the third cleans up afterward.  The second (printDiv) activates the print media style sheet, then appends a new rule to allow the desired div to print, issues the print, and then adds a delay before the final housekeeping (otherwise the styles can be reset before the print is actually done.)

function printDiv(divId)
{
  //  Enable the print CSS: (this temporarily disables being able to print the whole page)
  disableSheet(0,false);
  //  Get the print style sheet and add a new rule for this div
  var sheetObj=document.styleSheets[0];
  var showDivCSS="visibility:visible;display:block;position:absolute;top:30px;left:30px;";
  if (sheetObj.rules) { sheetObj.addRule("#"+divId,showDivCSS); }
  else                { sheetObj.insertRule("#"+divId+"{"+showDivCSS+"}",sheetObj.cssRules.length); }
  print();
  //  need a brief delay or the whole page will print
  setTimeout("printDivRestore()",100);
}

The final functions deletes the added rule and sets the print style again to disabled so the whole page can be printed.

function printDivRestore()
{
  // remove the div-specific rule
  var sheetObj=document.styleSheets[0];
  if (sheetObj.rules) { sheetObj.removeRule(sheetObj.rules.length-1); }
  else                { sheetObj.deleteRule(sheetObj.cssRules.length-1); }
  //  and re-enable whole page printing
  disableSheet(0,true);
}

The only other thing to do is to add one line to your onload processing so that the print style is initially disabled thereby allowing whole page printing.

<body onLoad='disableSheet(0,true)'>

Then, from anywhere in your document, you can print a div. Just issue printDiv("thedivid") from a button or whatever.

A big plus for this approach it provides a general solution to printing selected content from within a page.  It also allows use of existing styles for elements that are printed - including the containing div.

NOTE:  In my implementation, this must be the first style sheet.  Change the sheet references (0) to the appropriate sheet number if you need to make it later in the sheet sequence.

ContentLicense: CC BY-SA 2.5


问:
What's the effect of "weights" argument in caret::glmnet() function?
I would like to found out what's happening if a customized weights list (not all equalling to 1 as default) is passed to glmnet(). I have looked into the glmnet package  @github: glmnet but could not figure out what's going underneath. Is it the same as up-sampling by duplicating the minority observations?

答: In glmnet vignette by Trevor Hasties et al, "weights" is explained to be used to reconstruct deviance during convergency process, therefore impacting the final fitted model. </p>


问:
Importing specific text from Word
I have a couple hundred Word docs that have some number measurements that I need in my code. Naturally, I don't want to copy and paste the measurements into python each time. What I have tried to do is:

```<code>r = []
with open('NGC1705_rotmod.dat') as fo:
    for rec in fo:
        r.append(rec[0:4])
</code>```

Which returns:

```<code>['# Di', '# Ra', '# kp', '0.22', '0.66', '1.11', '1.55', '2.00', '2.45', '2.89', '3.34', '3.78', '4.22', '4.66', '5.11', '5.56', '6.00']
</code>```

However, the first three elements (#Di, #Ra, #kp) are simply the headers for the data, they aren't part of the data that I need. Is there any way to cut off the first 3 rows?

答:
Yes, try this.  There is probably a cleaner way, but this should work.</p>

```<code>r = []
with open('NGC1705_rotmod.dat') as fo:
    next(fo)
    next(fo)
    next(fo)
    for rec in fo:
        r.append(rec[0:4])
</code>```

Title: Importing specific text from Word

Body:
I have a couple hundred Word docs that have some number measurements that I need in my code. Naturally, I don't want to copy and paste the measurements into python each time. What I have tried to do is:

r = []
with open('NGC1705_rotmod.dat') as fo:
    for rec in fo:
        r.append(rec[0:4])

Which returns:

['# Di', '# Ra', '# kp', '0.22', '0.66', '1.11', '1.55', '2.00', '2.45', '2.89', '3.34', '3.78', '4.22', '4.66', '5.11', '5.56', '6.00']

However, the first three elements (#Di, #Ra, #kp) are simply the headers for the data, they aren't part of the data that I need. Is there any way to cut off the first 3 rows?

Body:
Yes, try this.  There is probably a cleaner way, but this should work.

r = []
with open('NGC1705_rotmod.dat') as fo:
    next(fo)
    next(fo)
    next(fo)
    for rec in fo:
        r.append(rec[0:4])


问:
Display add to cart button inline on category page WooCommerce
I am trying to display all of my add to cart buttons "inline" but due to the text being longer on some products it is jumping around. I have tried various fixes but with no luck.

What is the easiest way to fix this?

I used a CSS to set a min height of the background banner, which fixed part of the issue. But the add to cart buttons still jump around.

Is it possible to set a relative height or something so they show up at the same place?

The CSS code I tried (but this doesn't really make it look proper either):

.woo-product-title {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.woo-product-box {
    min-height: 160px;
}
```

<p><strong>This is how it looks:</strong></p>

<p><img src="https://i.imgur.com/k857b3Q.png" alt="how it looks"></p>

<p><strong>This is how it should look:</strong> </p>

<p><img src="https://i.imgur.com/11l5Kfo.png" alt="how it should look"></p>

<p>I am not very good at advanced coding (primarily know CSS) and the site is built in a theme, so changing major parts of the HTML is not possible. Therefore a CSS option or PHP code for functions.php is prefered. </p>

<p><strong>This CSS code somewhat fixes the problem, but forces a very large gap on top of some products with short descriptions. Is there any CSS way to make it slightly more welcoming?</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>.box-text a:not(.button) { min-height: 90px; }</code>```

Site is on: http://detitalienskekoekken.dk.linux99.unoeuro-server.com/shop/

答:
```<code>.ajax_add_to_cart.add_to_cart_button.product_type_simple.button.primary.is-outline.mb-0.is-small {
margin-top: 20px;
width: 100%;
padding: 5px 0 5px 0;
background-color: #c31919;
color: #FFFFFF;
border-radius: 5px;}
</code>```

Should be CSS Code for the Button.

And rest needs to be done by adjusting the HTML.

Body:
I am trying to display all of my add to cart buttons "inline" but due to the text being longer on some products it is jumping around. I have tried various fixes but with no luck.

What is the easiest way to fix this?

I used a CSS to set a min height of the background banner, which fixed part of the issue. But the add to cart buttons still jump around.

Is it possible to set a relative height or something so they show up at the same place?

The CSS code I tried (but this doesn't really make it look proper either):

.woo-product-title {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.woo-product-box {
    min-height: 160px;
}

This is how it looks:

This is how it should look:

I am not very good at advanced coding (primarily know CSS) and the site is built in a theme, so changing major parts of the HTML is not possible. Therefore a CSS option or PHP code for functions.php is prefered.

This CSS code somewhat fixes the problem, but forces a very large gap on top of some products with short descriptions. Is there any CSS way to make it slightly more welcoming?

.box-text a:not(.button) { min-height: 90px; }

Site is on: http://detitalienskekoekken.dk.linux99.unoeuro-server.com/shop/

Body:
.ajax_add_to_cart.add_to_cart_button.product_type_simple.button.primary.is-outline.mb-0.is-small {
margin-top: 20px;
width: 100%;
padding: 5px 0 5px 0;
background-color: #c31919;
color: #FFFFFF;
border-radius: 5px;}

Should be CSS Code for the Button.

And rest needs to be done by adjusting the HTML.


问:
Removing duplicates from a large table with NULL columns that also need to be taken into account
I am interested in removing duplicates from a very large table (40+ million records, 3+ GB in size), that also has to count NULL columns when determining duplicates.   5.5.56-MariaDB, tables are in InnoDB format.

The problem I'm running into is that some of the recommended methods will not work when it comes to NULL field comparison.    For example, I have a table that has about a dozen columns, many of which can contain NULL values, and I want NULLs treated as any other value, in that if a row has the same NULL values in the same columns, it's considered a dupe.

The technique below does NOT work:

```<code>create table tmp like mytable;
alter table tmp ADD UNIQUE INDEX(field1,field2, field3,...);
insert IGNORE into tmp (select * from mytable);
</code>```

At this point, tmp should have all dupes removed, but NULL columns are ignored in the Unique index, so it doesn't work.  If it did work, then I could rename the tables, or truncate the original table and copy over (assuming I wanted to preserve a primary key in the original table).

What is the most efficient way of deleting dupes in large files when dealing with NULL columns that should also be taken into consideration?

Additional notes:   I have a field called "recno" that is Auto Increment that needs to be ignored.

答:
Oooo, that was a challenge.</p>

```<code>CREATE TABLE _t LIKE real;
INSERT INTO _t
    SELECT MIN(recno),   -- or MAX, if you prefer
           a,b,c,...,w   -- all the other columns
        FROM real
        GROUP BY
           a,b,c,...,w,
           ((a IS NULL) << 0) |
           ((b IS NULL) << 1) |
           ...
           ((w IS NULL) << 22) ;
-- Note: This will not work for more than 64 columns.

-- Put it in place (with no downtime):
RENAME TABLE real TO old, _t TO real;
DROP TABLE old;
</code>```

Body:
I am interested in removing duplicates from a very large table (40+ million records, 3+ GB in size), that also has to count NULL columns when determining duplicates.   5.5.56-MariaDB, tables are in InnoDB format.

The problem I'm running into is that some of the recommended methods will not work when it comes to NULL field comparison.    For example, I have a table that has about a dozen columns, many of which can contain NULL values, and I want NULLs treated as any other value, in that if a row has the same NULL values in the same columns, it's considered a dupe.

The technique below does NOT work:

create table tmp like mytable;
alter table tmp ADD UNIQUE INDEX(field1,field2, field3,...);
insert IGNORE into tmp (select * from mytable);

At this point, tmp should have all dupes removed, but NULL columns are ignored in the Unique index, so it doesn't work.  If it did work, then I could rename the tables, or truncate the original table and copy over (assuming I wanted to preserve a primary key in the original table).

What is the most efficient way of deleting dupes in large files when dealing with NULL columns that should also be taken into consideration?

Additional notes:   I have a field called "recno" that is Auto Increment that needs to be ignored.

Body:
Oooo, that was a challenge.

CREATE TABLE _t LIKE real;
INSERT INTO _t
    SELECT MIN(recno),   -- or MAX, if you prefer
           a,b,c,...,w   -- all the other columns
        FROM real
        GROUP BY
           a,b,c,...,w,
           ((a IS NULL) << 0) |
           ((b IS NULL) << 1) |
           ...
           ((w IS NULL) << 22) ;
-- Note: This will not work for more than 64 columns.

-- Put it in place (with no downtime):
RENAME TABLE real TO old, _t TO real;
DROP TABLE old;


问:
map rect component array as group of two elements
I have an array of text inputs like

```<code>var A = [<TextInput ... />, <TextInput ... />, ....]
</code>```

and I want to map these elements group by two elements inside a row.
ie, every two <TextInput /> wrapped inside a <Row> how can I implement this.
I want output like this

```<code><Row>
   <TextInput ... />
   <TextInput ... />
</Row>
<Row>
   <TextInput ... />
   <TextInput ... />
</Row>
<Row>
   <TextInput ... />
   <TextInput ... />
</Row>
....
....
</code>```

I tried this code inside the loop but it produce an error.

```<code>{index % 2 === 0 && <Row> }
      <TextInput {...props} />
{index % 2 === 1 ? </Row>}
</code>```

I think we cannot return Closing tag of </Row> only inside jsx

答:
Something like this should work. There can be errors though, I have not tested this yet</p>

```<code><div>
  {
    A.map((_, index) =>
      (index % 2 === 0) &&
      <Row>
       {A[index]}
       {A[index+1] ? A[index+1] : <div />}
      </Row>
    )
  }
</div>
</code>```

Body:
I have an array of text inputs like

var A = [<TextInput ... />, <TextInput ... />, ....]

and I want to map these elements group by two elements inside a row.
ie, every two <TextInput /> wrapped inside a <Row> how can I implement this.
I want output like this

<Row>
   <TextInput ... />
   <TextInput ... />
</Row>
<Row>
   <TextInput ... />
   <TextInput ... />
</Row>
<Row>
   <TextInput ... />
   <TextInput ... />
</Row>
....
....

I tried this code inside the loop but it produce an error.

{index % 2 === 0 && <Row> }
      <TextInput {...props} />
{index % 2 === 1 ? </Row>}

I think we cannot return Closing tag of </Row> only inside jsx

Body:
Something like this should work. There can be errors though, I have not tested this yet

<div>
  {
    A.map((_, index) =>
      (index % 2 === 0) &&
      <Row>
       {A[index]}
       {A[index+1] ? A[index+1] : <div />}
      </Row>
    )
  }
</div>


问:
How to sort a MYSQL table in a permanent way?
I am a having a table with column Symbol and Weight(only two Column) .
I need to sort table according to weight of the symbols, that i can do by

```<code>SELECT symbol, weight FROM symbols ORDER BY weight DESC
</code>```

but this wont change my table, but it will give me a sorted output(temporary).

I want to sort table permanently. How can i do that?

答: Actually you can add a new integer column sort and set it as primary key. If you already has primary key, just change that to unique would be OK.

Body:
I am a having a table with column Symbol and Weight(only two Column) .
I need to sort table according to weight of the symbols, that i can do by

SELECT symbol, weight FROM symbols ORDER BY weight DESC

but this wont change my table, but it will give me a sorted output(temporary).

I want to sort table permanently. How can i do that?


问:
In MySQL, can I copy one row to insert into the same table?
```<code>insert into table select * from table where primarykey=1
</code>```

I just want to copy one row to insert into the same table (i.e., I want to duplicate an existing row in the table) but I want to do this without having to list all the columns after the "select", because this table has too many columns.

But when I do this, I get the error:

Duplicate entry 'xxx' for key 1

I can handle this by creating another table with the same columns as a temporary container for the record I want to copy:

```<code>create table oldtable_temp like oldtable;
insert into oldtable_temp select * from oldtable where key=1;
update oldtable_tem set key=2;
insert into oldtable select * from oldtable where key=2;
</code>```

Is there a simpler way to solve this?

答:
clone row with update fields and auto increment value</p>

```<code>CREATE TEMPORARY TABLE `temp` SELECT * FROM `testing` WHERE id = 14;

UPDATE `temp` SET id = (SELECT id FROM testing ORDER by id DESC LIMIT 1
 )+1, user_id = 252 ,policy_no = "mysdddd12" where id = 14;

INSERT INTO `testing` SELECT * FROM `temp`;

DROP TEMPORARY TABLE IF EXISTS `temp`;
</code>```

Body:
insert into table select * from table where primarykey=1

I just want to copy one row to insert into the same table (i.e., I want to duplicate an existing row in the table) but I want to do this without having to list all the columns after the "select", because this table has too many columns.

But when I do this, I get the error:

Duplicate entry 'xxx' for key 1

I can handle this by creating another table with the same columns as a temporary container for the record I want to copy:

create table oldtable_temp like oldtable;
insert into oldtable_temp select * from oldtable where key=1;
update oldtable_tem set key=2;
insert into oldtable select * from oldtable where key=2;

Is there a simpler way to solve this?

Body:
clone row with update fields and auto increment value

CREATE TEMPORARY TABLE `temp` SELECT * FROM `testing` WHERE id = 14;

UPDATE `temp` SET id = (SELECT id FROM testing ORDER by id DESC LIMIT 1
 )+1, user_id = 252 ,policy_no = "mysdddd12" where id = 14;

INSERT INTO `testing` SELECT * FROM `temp`;

DROP TEMPORARY TABLE IF EXISTS `temp`;


问:
Access js variable of one file in another file using JQuery
I have 2 js files: 1.js and 2.js.

In 1.js I have a variable

```<code>var test ='Hello';
</code>```

I'm trying to access the variable in 2.js

```<code>alert(test);
</code>```

Sample Code:

1.js :

```<code>$(document).ready(function () {
    var test = 'Hello';
});
</code>```

2.js :

```<code> $(function () {
       function getData(){
            alert(test);
       }
   });
</code>```

In my aspx page order of js files:

```<code><script type="text/javascript" src="js/1.js"></script>
<script type="text/javascript" src="js/2.js?"></script>
</code>```

I know the question is asked before many times but none of the answers seems to work for me.

答:
You can use sessionStorage to store the variable value

```<code>$(document).ready(function () {
  sessionStorage.setItem('test ', 'Hello');
});
</code>```

In the next file retrieve it using

```<code>$(function () {
       function getData(){
         var data = sessionStorage.getItem('test');
            alert(data );
       }
   });
</code>```

Note the file 1.js need to be loaded before 2.js

Body:
I have 2 js files: 1.js and 2.js.

In 1.js I have a variable

var test ='Hello';

I'm trying to access the variable in 2.js

alert(test);

Sample Code:

1.js :

$(document).ready(function () {
    var test = 'Hello';
});

2.js :

 $(function () {
       function getData(){
            alert(test);
       }
   });

In my aspx page order of js files:

I know the question is asked before many times but none of the answers seems to work for me.

Body:
You can use sessionStorage to store the variable value

$(document).ready(function () {
  sessionStorage.setItem('test ', 'Hello');
});

In the next file retrieve it using

$(function () {
       function getData(){
         var data = sessionStorage.getItem('test');
            alert(data );
       }
   });

Note the file 1.js need to be loaded before 2.js


答:
```<code>cin >> object.setData() >> object.setData();
</code>```

the >> operator doesn't call object.setData; it takes a reference and sets the reference contents to the extracted input. The expression object.setData() calls the function, which returns void. Of course, the >> operator cannot take a void argument. Also, there aren't enough arguments in the funcall because object.setData expects a string and an int.

You should do this:

```<code>std::string name;
int num;
cin >> name >> num;
object.setData(name, num);
</code>```

Title: C++ Storing a string into a class

Body:
I made a topic a bit ago regarding structs. And I know that classes have the same concept as structs. How would I go about storing a string into the class?

This is the class

class studentType
{
public:
    void setData(string, int);
    string getName() const;
    int getId() const;
private:
    string name;
    int sid;
};

void studentType::setData(string, int) {
    name = ??;
    sid = ??;
}

string studentType::getName() const {
    return name;
}

int studentType::getId() const {
    return sid;
}

The main consists of:

int main() {

    studentType object, number;

    cout << "enter name and code of item1: ";
    cin >> object.setData() >> object.setData();
    cout << "enter name and code for item2: ";
    cin >> number.setData() >> number.setData();

    system("pause");
    return 0;
}

How would I fix the cin issue? I already have string defined in the header. And yes, I know using namespace std; isn't preferred but it's for simplicity

Body:
cin >> object.setData() >> object.setData();

the >> operator doesn't call object.setData; it takes a reference and sets the reference contents to the extracted input. The expression object.setData() calls the function, which returns void. Of course, the >> operator cannot take a void argument. Also, there aren't enough arguments in the funcall because object.setData expects a string and an int.

You should do this:

std::string name;
int num;
cin >> name >> num;
object.setData(name, num);


问:
Constraints not working in TableViewCell
I'm learning how to use CoreData to store images, and I'm making a blog reader. I have a view That shows all the info saved as a list and when you click it takes you to that article. My problem is that I can't make TableViewCells look as intended. I have added the constraints and not a single of them is being placed.

Here are my constraints:

And this is the result:

I've deleted them, cleaned, closed xCode, put them again and the same result. Found this answer, checked and nothing. Also this one. In the same project, I have another TableView and it works fine, any ideas why this is happening? Thanks a lot!

答:
Looks like image is overflowing form the container. Try this

Set the UIImageView content mode to UIViewContentModeScaleAspectFill

Set UIImageView clipToBounds to true.


答:
Your setData function can be as such:

```<code>void studentType::setData(string name, int sid) {
    this->name = name;
    this->sid = sid;
}
</code>```

And in your main():

First cin the values and then call the setData function, i.e.

```<code>int main(){
    string name;
    int code;

    studentType object, number;
    cout << "enter name and code of item1: ";
    cin >> name >> code;

    object = studentType();
    object.setData(name, code);

    // your remaining code

}
</code>```

Just a note of caution:
If you use cin to get the name and code, the name can only be a single word. Say if you are writing a name of two words, the first word will be put in name and the second will be attempted to put in code.

In simpler terms, cin is space-delimited.

Title: C++ Storing a string into a class

Body:
Your setData function can be as such:

void studentType::setData(string name, int sid) {
    this->name = name;
    this->sid = sid;
}

And in your main():

First cin the values and then call the setData function, i.e.

int main(){
    string name;
    int code;

    studentType object, number;
    cout << "enter name and code of item1: ";
    cin >> name >> code;

    object = studentType();
    object.setData(name, code);

    // your remaining code

}

Just a note of caution:
If you use cin to get the name and code, the name can only be a single word. Say if you are writing a name of two words, the first word will be put in name and the second will be attempted to put in code.

In simpler terms, cin is space-delimited.


答:
You can use itertools.islice

```<code>from itertools import islice

r = []
with open('NGC1705_rotmod.dat') as fo:
    for rec in islice(fo, 3, None):
        r.append(rec[0:4])
</code>```

Title: Importing specific text from Word

Body:
You can use itertools.islice

from itertools import islice

r = []
with open('NGC1705_rotmod.dat') as fo:
    for rec in islice(fo, 3, None):
        r.append(rec[0:4])


问:
Load configurable variables into a bat file
I have the below configuration file

```<code>[CLIENT1]
drive='C:/CLIENT1'
client='1'
[CLIENT2]
drive='C:/CLIENT2'
client='2'
</code>```

I am trying to pass in a parameter to my bat file from the command line that will  either be CLIENT1 or CLIENT2. The aim is to load in the drive and clientid into the bat script to change the current working directory.

Something like this

```<code>@ECHO OFF

set param=CLIENT1

for /f "delims=" %%x in (config.txt) do (
   IF "%%x" == "[%PARAM%]"
      (
         # Load the next two lines of code to set the variables
         set var1=line1
         set var2=line2
      )
)

echo var1 var2
pause
</code>```

I am having trouble coming up with the correct way to load in the variables after identifying I have found the record the bat file has been run for.

Any advice?

答:
I have ended up writing the below script could somebody please review it and let me know if I could be doing this better or utilizing some functionality to make this script alot neater?

```<code>@ECHO OFF
setlocal ENABLEDELAYEDEXPANSION
set param=CLIENT1
set /A count=0

for /f "delims=." %%x in (config.txt) do (
   set /A count=count+1
   if "%%x" == "[%PARAM%]" goto :break
)

ECHO didnt find it
goto :exit

:break
set "drive="
set "id="
for /f "skip=%count% tokens= 1, 2 delims==" %%A in (config.txt) do (
   if %%A==drive set drive=%%B
   if %%A==client set id=%%B
   if defined drive if defined id goto :exit
)

:exit
ECHO drive - %drive%
ECHO id - %id%
endlocal
pause
</code>```

outputs:

```<code>drive - 'C:/CLIENT1'
id - '1'
</code>```

I plan to hand something based of this logic out to a colleague at work and I want it to not be awful.

Thanks.

Body:
I have the below configuration file

[CLIENT1]
drive='C:/CLIENT1'
client='1'
[CLIENT2]
drive='C:/CLIENT2'
client='2'

I am trying to pass in a parameter to my bat file from the command line that will  either be CLIENT1 or CLIENT2. The aim is to load in the drive and clientid into the bat script to change the current working directory.

Something like this

@ECHO OFF

set param=CLIENT1

for /f "delims=" %%x in (config.txt) do (
   IF "%%x" == "[%PARAM%]"
      (
         # Load the next two lines of code to set the variables
         set var1=line1
         set var2=line2
      )
)

echo var1 var2
pause

I am having trouble coming up with the correct way to load in the variables after identifying I have found the record the bat file has been run for.

Any advice?

Body:
I have ended up writing the below script could somebody please review it and let me know if I could be doing this better or utilizing some functionality to make this script alot neater?

@ECHO OFF
setlocal ENABLEDELAYEDEXPANSION
set param=CLIENT1
set /A count=0

for /f "delims=." %%x in (config.txt) do (
   set /A count=count+1
   if "%%x" == "[%PARAM%]" goto :break
)

ECHO didnt find it
goto :exit

:break
set "drive="
set "id="
for /f "skip=%count% tokens= 1, 2 delims==" %%A in (config.txt) do (
   if %%A==drive set drive=%%B
   if %%A==client set id=%%B
   if defined drive if defined id goto :exit
)

:exit
ECHO drive - %drive%
ECHO id - %id%
endlocal
pause

outputs:

drive - 'C:/CLIENT1'
id - '1'

I plan to hand something based of this logic out to a colleague at work and I want it to not be awful.

Thanks.


问:
How to add design dependency in android studio 3.0. its not working in standard way
```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.rohit.ironman"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.0.0-beta1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:0.5'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:design:26.1.1'
}
</code>```

I have also tried-

Implementation 'com.android.support:design:26.1.1'
instead of

compile 'com.android.support:design:26.1.1'
but still the gradle sync fails

my gradle version is 4.1

android plugin version is 3.0.1

答:
add this in build gradle of app

```<code>repositories {
mavenCentral()
maven { url 'https://maven.google.com' }
</code>```

}

and in build script of whole app

```<code> buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }

}
</code>```

for more info about what changes are made just read here https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html

Body:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.rohit.ironman"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.0.0-beta1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:0.5'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:design:26.1.1'
}

I have also tried-

Implementation 'com.android.support:design:26.1.1'
instead of

compile 'com.android.support:design:26.1.1'
but still the gradle sync fails

my gradle version is 4.1

android plugin version is 3.0.1

Body:
add this in build gradle of app

repositories {
mavenCentral()
maven { url 'https://maven.google.com' }

}

and in build script of whole app

 buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }

}

for more info about what changes are made just read here https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html


问:
Program that guesses each position of the password
I'm a beginner in Python and my assignment is to guess the password by running through the length of the unknown, random password and then replacing that position with the correct letter/number. I know it involves running the code until a match is found but I'm stuck.

You are to write a program that will try to guess each position of the password.  The program must use a function that contains the code to hack the password.
  Use of lists and methods/functions such as list( ) and .join will be helpful.
  You should begin by displaying a string made up of asterisks (e.g.  *******)  equal to the length of the generated password.
  As you match each letter/number in the secret password, replace the asterisk in that same position with that letter/number.
  The output should look like this:

Password is yfdszk

```<code>Hacking...
Found match at position 2
*d****
Found match at position 1
*fd***
Found match at position 5
*fd**k
Found match at position 3
*fds*k
Found match at position 0
yfds*k
Found match at position 4
yfdszk
I did it! yfdszk
</code>```

Here is my code:

```<code>import random
characters="abcdefghijklmnopqrstuvwxyz0123456789"
charList=list(characters)
def generatePassword(pwLen):
    pw=""
    for i in range(pwLen):
        rand=int(random.randint(0,len(charList)-1))
        pw=pw + (charList[rand])
        pwList = list(pw)
    return pw
def hackPassword(pw):
    r`enter code here`and=int(random.randint(0,len(charList)-1))
    pw=pw + (charList[rand])
    pwList = list(pw)
    asterisk = "*" * len(pw)
    asteriskList = list(asterisk)
    print asterisk
    for numbers in range(len(charList)):
        if charList == pwList[]:
            password = pw[:index] + "*" +  pw[index+1:]
password=generatePassword(8)
# display secret
print "Password is " + password
hackPassword(password)
</code>```

I need to be able to guess the password, using a for loop to go through the length of the password, then finding a match, and then replacing that asterisk with the found letter/number.

But I'm getting this error message:

```<code>IndexError: list index out of range on line 20
</code>```

答:
Although your sample run is flawed, I believe I understand the gist of what you're trying to do. You generate a random password and then represent it with asterisks, so that the length is shown. Then, for each character in characters="abcdefghijklmnopqrstuvwxyz0123456789" you check if it matches any of the chars in the password.  By the time you've run through it, you're done. So, you're going to need a double nested loop. I won't write it for you, but i'll give you a hint, in pseudocode:

```<code>generate a random password
make a corresponding 'fake' password of the same length of asterisks
for char in charList:
    for position in actual password:
        if char matches that position:
            change the asterisk to that char in the fake password
            if my fake password is cracked (no more asterisks):
                print('Whoohoo!')
                go home, you're done
</code>```

Hope this helps!  Getting the logic right is always the hardest part of programming!

As a side note, I got the above understanding because I noticed in your example that you are cracking the password in alphabetical order... d-f-k-s-y-z...

Body:
I'm a beginner in Python and my assignment is to guess the password by running through the length of the unknown, random password and then replacing that position with the correct letter/number. I know it involves running the code until a match is found but I'm stuck.

You are to write a program that will try to guess each position of the password.  The program must use a function that contains the code to hack the password.
  Use of lists and methods/functions such as list( ) and .join will be helpful.
  You should begin by displaying a string made up of asterisks (e.g.  *******)  equal to the length of the generated password.
  As you match each letter/number in the secret password, replace the asterisk in that same position with that letter/number.
  The output should look like this:

Password is yfdszk

Hacking...
Found match at position 2
*d****
Found match at position 1
*fd***
Found match at position 5
*fd**k
Found match at position 3
*fds*k
Found match at position 0
yfds*k
Found match at position 4
yfdszk
I did it! yfdszk

Here is my code:

import random
characters="abcdefghijklmnopqrstuvwxyz0123456789"
charList=list(characters)
def generatePassword(pwLen):
    pw=""
    for i in range(pwLen):
        rand=int(random.randint(0,len(charList)-1))
        pw=pw + (charList[rand])
        pwList = list(pw)
    return pw
def hackPassword(pw):
    r`enter code here`and=int(random.randint(0,len(charList)-1))
    pw=pw + (charList[rand])
    pwList = list(pw)
    asterisk = "*" * len(pw)
    asteriskList = list(asterisk)
    print asterisk
    for numbers in range(len(charList)):
        if charList == pwList[]:
            password = pw[:index] + "*" +  pw[index+1:]
password=generatePassword(8)
# display secret
print "Password is " + password
hackPassword(password)

I need to be able to guess the password, using a for loop to go through the length of the password, then finding a match, and then replacing that asterisk with the found letter/number.

But I'm getting this error message:

IndexError: list index out of range on line 20

Body:
Although your sample run is flawed, I believe I understand the gist of what you're trying to do. You generate a random password and then represent it with asterisks, so that the length is shown. Then, for each character in characters="abcdefghijklmnopqrstuvwxyz0123456789" you check if it matches any of the chars in the password.  By the time you've run through it, you're done. So, you're going to need a double nested loop. I won't write it for you, but i'll give you a hint, in pseudocode:

generate a random password
make a corresponding 'fake' password of the same length of asterisks
for char in charList:
    for position in actual password:
        if char matches that position:
            change the asterisk to that char in the fake password
            if my fake password is cracked (no more asterisks):
                print('Whoohoo!')
                go home, you're done

Hope this helps!  Getting the logic right is always the hardest part of programming!

As a side note, I got the above understanding because I noticed in your example that you are cracking the password in alphabetical order... d-f-k-s-y-z...


问:
Issue with the AutoDesk Forge Viewer API
While getting the document to load, I am getting this error

```<code>wgs.js:21467 Uncaught TypeError: Cannot read property 'numGeoms' of undefined
    at d.RenderModel.initialize (wgs.js:21467)
    at a.onModelRootLoadDone (viewer3D.min.js:4484)
    at Worker.p (viewer3D.min.js:4432)
    RenderModel.initialize @ wgs.js:21467
    a.onModelRootLoadDone @ viewer3D.min.js:4484
    p @ viewer3D.min.js:4432
    viewer3D.min.js:4446 Uncaught TypeError: Cannot read property
    'meshToGeometry' of undefined
        at a.processReceivedMesh (viewer3D.min.js:4446)
        at a.processReceivedMesh2D (viewer3D.min.js:4465)
        at Worker.p (viewer3D.min.js:4432)
        a.processReceivedMesh @ viewer3D.min.js:4446
        a.processReceivedMesh2D @ viewer3D.min.js:4465
        p @ viewer3D.min.js:4432
       validator.html:1 [.Offscreen-For-WebGL-0x55a2800ad520]GL ERROR:GL_INVALID_FRAMEBUFFER_OPERATION : glClear: framebuffer incomplete (check) 59 viewer3D.min.js:4446
Uncaught TypeError: Cannot read property 'meshToGeometry' of undefined
    at a.processReceivedMesh (viewer3D.min.js:4446)
    at a.processReceivedMesh2D (viewer3D.min.js:4465)
    at Worker.p (viewer3D.min.js:4432)
</code>```

Can anyone please help ?

答:
This problem may be caused by the use of an outdated version of the viewer.

Currently the Viewer is on Version 3.3 I will suggest doing the migration to solve your problem and also take advantage of all the new functionality.

Here is a list of the changelogs
https://developer.autodesk.com/en/docs/viewer/v2/overview/changelog/

And here the blog post about the newer version
https://forge.autodesk.com/blog/viewer-release-notes-v33

Body:
While getting the document to load, I am getting this error

wgs.js:21467 Uncaught TypeError: Cannot read property 'numGeoms' of undefined
    at d.RenderModel.initialize (wgs.js:21467)
    at a.onModelRootLoadDone (viewer3D.min.js:4484)
    at Worker.p (viewer3D.min.js:4432)
    RenderModel.initialize @ wgs.js:21467
    a.onModelRootLoadDone @ viewer3D.min.js:4484
    p @ viewer3D.min.js:4432
    viewer3D.min.js:4446 Uncaught TypeError: Cannot read property
    'meshToGeometry' of undefined
        at a.processReceivedMesh (viewer3D.min.js:4446)
        at a.processReceivedMesh2D (viewer3D.min.js:4465)
        at Worker.p (viewer3D.min.js:4432)
        a.processReceivedMesh @ viewer3D.min.js:4446
        a.processReceivedMesh2D @ viewer3D.min.js:4465
        p @ viewer3D.min.js:4432
       validator.html:1 [.Offscreen-For-WebGL-0x55a2800ad520]GL ERROR:GL_INVALID_FRAMEBUFFER_OPERATION : glClear: framebuffer incomplete (check) 59 viewer3D.min.js:4446
Uncaught TypeError: Cannot read property 'meshToGeometry' of undefined
    at a.processReceivedMesh (viewer3D.min.js:4446)
    at a.processReceivedMesh2D (viewer3D.min.js:4465)
    at Worker.p (viewer3D.min.js:4432)

Can anyone please help ?


问:
node.js: Mock http request and response
Is there convenient way to mock the HTTP Request and Response objects for unit testing middlewares?</p>

答: I encourage you to use motty. why do we need an another code?</p>

Title: node.js: Mock http request and response


问:
Get object property name as a string
Is it possible to get the object property name as a string

```<code>person = {};
person.first_name = 'Jack';
person.last_name = 'Trades';
person.address = {};
person.address.street = 'Factory 1';
person.address.country = 'USA';
</code>```

I'd like to use it like this:

```<code>var pn = propName( person.address.country ); // should return 'country' or 'person.address.country'
var pn = propName( person.first_name );      // should return 'first_name' or 'person.first_name'
</code>```

NOTE: this code is exactly what I'm looking for. I understand it sounds even stupid, but it's not.

This is what I want to do with it.

HTML

```<code>person = {};
person.id_first_name = 'Jack';
person.id_last_name = 'Trades';
person.address = {};
person.address.id_address = 'Factory 1';
person.address.id_country = 'USA';

extPort.postMessage
(
  {
    message : MSG_ACTION,
    propName( person.first_name ): person.first_name
  }
};
</code>```

----------------------ANSWER-----------------------

Got it thanks to ibu. He pointed the right way and I used a recursive function

```<code>var res = '';

function propName(prop, value) {
    for (var i in prop) {
        if (typeof prop[i] == 'object') {
            if (propName(prop[i], value)) {
                return res;
            }
        } else {
            if (prop[i] == value) {
                res = i;
                return res;
            }
        }
    }
    return undefined;
}

var pn = propName(person, person.first_name); // returns 'first_name'
var pn = propName(person, person.address.country); // returns 'country'
</code>```

DEMO: http://jsbin.com/iyabal/1/edit

答:
You can accomplish this by creating a mirror object that stores all the property names and call a property with an expression

Javascript version

```<code>var person = {};
person.firstname = 'Jack';
person.address = "123 Street";
person.child = { name: 'Example' };

function getPropertyName(obj, expression) {
    var res = {};
    Object.keys(obj).map(k => { res[k] = k; });
    return expression(res);
}

console.log(getPropertyName(person, o => o.address)); // 'address'
console.log(getPropertyName(person.child, o => o.name)); // 'name'
</code>```

Typescript version (based on @MadSkunk answer)

```<code>function getPropertyName<T extends object>(o: T, expression: (x: { [Property in keyof T]: string }) => string) {
  const res = {} as { [Property in keyof T]: string };
  Object.keys(o).map(k => res[k as keyof T] = k);
  return expression(res);
}

console.log(getPropertyName(obj, a => a.firstname)); // 'firstname'
console.log(getPropertyName(obj.child, a => a.name)); // 'name'
</code>```

Title: Get object property name as a string

Body:
Is it possible to get the object property name as a string

person = {};
person.first_name = 'Jack';
person.last_name = 'Trades';
person.address = {};
person.address.street = 'Factory 1';
person.address.country = 'USA';

I'd like to use it like this:

var pn = propName( person.address.country ); // should return 'country' or 'person.address.country'
var pn = propName( person.first_name );      // should return 'first_name' or 'person.first_name'

NOTE: this code is exactly what I'm looking for. I understand it sounds even stupid, but it's not.

This is what I want to do with it.

HTML

person = {};
person.id_first_name = 'Jack';
person.id_last_name = 'Trades';
person.address = {};
person.address.id_address = 'Factory 1';
person.address.id_country = 'USA';

extPort.postMessage
(
  {
    message : MSG_ACTION,
    propName( person.first_name ): person.first_name
  }
};

----------------------ANSWER-----------------------

Got it thanks to ibu. He pointed the right way and I used a recursive function

var res = '';

function propName(prop, value) {
    for (var i in prop) {
        if (typeof prop[i] == 'object') {
            if (propName(prop[i], value)) {
                return res;
            }
        } else {
            if (prop[i] == value) {
                res = i;
                return res;
            }
        }
    }
    return undefined;
}

var pn = propName(person, person.first_name); // returns 'first_name'
var pn = propName(person, person.address.country); // returns 'country'

DEMO: http://jsbin.com/iyabal/1/edit

Body:
You can accomplish this by creating a mirror object that stores all the property names and call a property with an expression

Javascript version

var person = {};
person.firstname = 'Jack';
person.address = "123 Street";
person.child = { name: 'Example' };

function getPropertyName(obj, expression) {
    var res = {};
    Object.keys(obj).map(k => { res[k] = k; });
    return expression(res);
}

console.log(getPropertyName(person, o => o.address)); // 'address'
console.log(getPropertyName(person.child, o => o.name)); // 'name'

Typescript version (based on @MadSkunk answer)

function getPropertyName<T extends object>(o: T, expression: (x: { [Property in keyof T]: string }) => string) {
  const res = {} as { [Property in keyof T]: string };
  Object.keys(o).map(k => res[k as keyof T] = k);
  return expression(res);
}

console.log(getPropertyName(obj, a => a.firstname)); // 'firstname'
console.log(getPropertyName(obj.child, a => a.name)); // 'name'


问:
String or unicode input unrecognized as WKT EWKT, and HEXEWKB
It might be a easy problem but I don't seem to figure it out. I'm using GeoDjango and I have a latitude and a longitude that I converted into strings (see my_lat and my_long).

For some reason it doesn't like the  my_long_lat variable when I use it inside the fromstr('POINT(my_long_lat)') and I get this error:

String or unicode input unrecognized
  as WKT EWKT, and HEXEWKB

My code:

```<code>my_lat = str(lat)[1:10]
my_long = str(long)[21:31]
my_long_lat = my_long + " " + my_lat
mypoint = fromstr('POINT(my_long_lat)')
</code>```

Just to make sure the variables my_lat and my_long have the right data I printed them and they show these values: 30.751277 for my_lat and -101.25 for my_long.

If I just type the values like this:
mypoint = fromstr('POINT(-101.25 30.751277)')
there are no errors generated but evidently I need to use variables to pass the data in.

Any ideas? Thank you!

答:
This line is being interpreted literally:

```<code>fromstr('POINT(my_long_lat)')
</code>```

Try

```<code>fromstr('POINT(' + my_long_lat + ')')
</code>```

Body:
It might be a easy problem but I don't seem to figure it out. I'm using GeoDjango and I have a latitude and a longitude that I converted into strings (see my_lat and my_long).

For some reason it doesn't like the  my_long_lat variable when I use it inside the fromstr('POINT(my_long_lat)') and I get this error:

String or unicode input unrecognized
  as WKT EWKT, and HEXEWKB

My code:

my_lat = str(lat)[1:10]
my_long = str(long)[21:31]
my_long_lat = my_long + " " + my_lat
mypoint = fromstr('POINT(my_long_lat)')

Just to make sure the variables my_lat and my_long have the right data I printed them and they show these values: 30.751277 for my_lat and -101.25 for my_long.

If I just type the values like this:
mypoint = fromstr('POINT(-101.25 30.751277)')
there are no errors generated but evidently I need to use variables to pass the data in.

Any ideas? Thank you!

Body:
This line is being interpreted literally:

fromstr('POINT(my_long_lat)')

Try

fromstr('POINT(' + my_long_lat + ')')


问:
Multiple tables join and applying case when
I am trying to use case when phrase to change the result value while joining multiple tables.

```<code>SELECT CASE WHEN CENSUS = '0' THEN 'SP_CENSUS0' END AS SP_RESULT FROM SP
SELECT CASE WHEN CENSUS = '0' THEN 'SR_CENSUS0' END AS SR_RESULT FROM SR

    SP             SR          TARGET
   ------         ------      --------
   CODE           CODE        CODE
   CENSUS         CENSUS
</code>```

and I wish to join the  three tables TARGET, SP and SR while
SP AND SR should do 1:1 mapping and hope to use column CODE to be used
for join. Each CENSUS colulmn may/may not have different results.

I want something like this to be in my result

```<code>      SP_RESULT            SR_RESULT
-------------------------------------
 1   (0)SP_CENSUS0      (0)SR_CENSUS0
 2         1                   4
 3         2            (0)SR_CENSUS0
 4         3                   1
 5   (0)SP_CENSUS0             5
</code>```

my results may have 0,1,2,3,4,5 and I want only the result 0 to be changed and these two tables are joined

答:
What is the point of TARGET if SR and SP are 1:1 via CODE field?

You can use table.field in your case statements:

```<code>select case when SP.CENSUS = '0' then 'SP_CENSUS0'
    else SP.CENSUS
    end as SP_RESULT,

    case when SR.CENSUS = '0' then 'SR_CENSUS0'
    else SR.CENSUS
    end as SR_RESULT
FROM SR JOIN SP ON SR.CODE = SP.CODE
</code>```

Also: watch out for data types, if Census column is number, you will have to CAST to VARCHAR in the ELSE assignment.

Body:
I am trying to use case when phrase to change the result value while joining multiple tables.

SELECT CASE WHEN CENSUS = '0' THEN 'SP_CENSUS0' END AS SP_RESULT FROM SP
SELECT CASE WHEN CENSUS = '0' THEN 'SR_CENSUS0' END AS SR_RESULT FROM SR

    SP             SR          TARGET
   ------         ------      --------
   CODE           CODE        CODE
   CENSUS         CENSUS

and I wish to join the  three tables TARGET, SP and SR while
SP AND SR should do 1:1 mapping and hope to use column CODE to be used
for join. Each CENSUS colulmn may/may not have different results.

I want something like this to be in my result

      SP_RESULT            SR_RESULT
-------------------------------------
 1   (0)SP_CENSUS0      (0)SR_CENSUS0
 2         1                   4
 3         2            (0)SR_CENSUS0
 4         3                   1
 5   (0)SP_CENSUS0             5

my results may have 0,1,2,3,4,5 and I want only the result 0 to be changed and these two tables are joined

Body:
What is the point of TARGET if SR and SP are 1:1 via CODE field?

You can use table.field in your case statements:

select case when SP.CENSUS = '0' then 'SP_CENSUS0'
    else SP.CENSUS
    end as SP_RESULT,

    case when SR.CENSUS = '0' then 'SR_CENSUS0'
    else SR.CENSUS
    end as SR_RESULT
FROM SR JOIN SP ON SR.CODE = SP.CODE

Also: watch out for data types, if Census column is number, you will have to CAST to VARCHAR in the ELSE assignment.


答:
```<code>var A = [ < TextInput .../>, <TextInput ... / >,...]

    let arrTwoComp = [],
        arrComp = [];
    A.forEach((oneComp, key) => {

        arrTwoComp.push(oneComp);

        if ((key + 1) % 2 === 0) {
            arrComp.push(
                <Row>{arrTwoComp}</Row>
            );
            arrTwoComp = [];
        }
    })

    //display arrComp

    <div>{arrComp}</div>
</code>```

Title: map rect component array as group of two elements

Body:
I have an array of text inputs like

var A = [<TextInput ... />, <TextInput ... />, ....]

and I want to map these elements group by two elements inside a row.
ie, every two <TextInput /> wrapped inside a <Row> how can I implement this.
I want output like this

<Row>
   <TextInput ... />
   <TextInput ... />
</Row>
<Row>
   <TextInput ... />
   <TextInput ... />
</Row>
<Row>
   <TextInput ... />
   <TextInput ... />
</Row>
....
....

I tried this code inside the loop but it produce an error.

{index % 2 === 0 && <Row> }
      <TextInput {...props} />
{index % 2 === 1 ? </Row>}

I think we cannot return Closing tag of </Row> only inside jsx


问:
jQuery Keycode help
How could I run a simple function when a key is pressed using jQuery. So for example if a user pressed the 'Q' key which is 81 in JavaScript it would run a function.</p>

答:
```<code>$(document).bind('keypress', function(event) {
    switch(e.which) {
        case 81: {
           alert('Q!');
           break;
        }
    }
});
</code>```

Title: jQuery Keycode help


问:
ValueError: Shape must be rank 1 but is rank 0 for 'ROIAlign/Crop' (op: 'CropAndResize') with input shapes: [2,360,475,3], [1,4], [], [2]
I tried to give all input in this function but it comes out problem like below , i not sure what is the empty [] is .
There are 2 image image in RGB and the original code is from https://github.com/CharlesShang/FastMaskRCNN/blob/master/libs/layers/crop.py.

```<code>Traceback (most recent call last):
  File "croptest.py", line 77, in <module>
    crop(img, boxes, batch_inds,1,7,7,'ROIAlign')
  File "croptest.py", line 64, in crop
    name='Crop')
  File "/home/ubuntu/Desktop/WK/my_project/lib/python2.7/site-packages/tensorflow/python/ops/gen_image_ops.py", line 166, in crop_and_resize
    name=name)
  File "/home/ubuntu/Desktop/WK/my_project/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
    op_def=op_def)
  File "/home/ubuntu/Desktop/WK/my_project/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2632, in create_op
    set_shapes_for_outputs(ret)
  File "/home/ubuntu/Desktop/WK/my_project/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1911, in set_shapes_for_outputs
    shapes = shape_func(op)
  File "/home/ubuntu/Desktop/WK/my_project/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1861, in call_with_requiring
    return call_cpp_shape_fn(op, require_shape_fn=True)
  File "/home/ubuntu/Desktop/WK/my_project/lib/python2.7/site-packages/tensorflow/python/framework/common_shapes.py", line 595, in call_cpp_shape_fn
    require_shape_fn)
  File "/home/ubuntu/Desktop/WK/my_project/lib/python2.7/site-packages/tensorflow/python/framework/common_shapes.py", line 659, in _call_cpp_shape_fn_impl
    raise ValueError(err.message)
ValueError: Shape must be rank 1 but is rank 0 for 'ROIAlign/Crop' (op: 'CropAndResize') with input shapes: [2,360,475,3], [1,4], [], [2].
</code>```

the code i run is shown as below.

```<code>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import glob
import tensorflow as tf
import numpy as np
import cv2

def crop(images, boxes, batch_inds, stride, pooled_height, pooled_width, scope):
  """Cropping areas of features into fixed size
  Params:
  --------
  images: a 4-d Tensor of shape (N, H, W, C)
  boxes: rois in the original image, of shape (N, ..., 4), [x1, y1, x2, y2]
  batch_inds:

  Returns:
  --------
  A Tensor of shape (N, pooled_height, pooled_width, C)
  """
  with tf.name_scope(scope):
    boxes = [x / (stride+0.0) for x in boxes]
    boxes = tf.reshape(boxes, [-1, 4])
    print(images)

    print(images.shape)
    shape = tf.shape(images)
    boxes = tf.reshape(boxes, [-1, 2]) # to (x, y)
    xs = boxes[:, 0]
    ys = boxes[:, 1]
    xs = xs / tf.cast(shape[2], tf.float32)
    ys = ys / tf.cast(shape[1], tf.float32)
    boxes = tf.concat([ys[:, tf.newaxis], xs[:, tf.newaxis]], axis=1)
    boxes = tf.reshape(boxes, [-1, 4])  # to (y1, x1, y2, x2)
    assert_op = tf.Assert(tf.greater(tf.size(images), 0), [images, batch_inds])
    print(assert_op)
    print("-----------------------")
    print(images.astype('float'))
    print("-----------------------")
    print(batch_inds)
    x=images.astype('float')
    print("-----------------------")
    print(batch_inds)
    print("-----------------------")
    print(pooled_height)
    print("-----------------------")
    pools =[pooled_height, pooled_width]

    arg = tf.convert_to_tensor(x, dtype=tf.float32)
    arg1 = tf.convert_to_tensor(batch_inds)
    with tf.control_dependencies([assert_op, arg,arg1 ]):
        return  tf.image.crop_and_resize(images, boxes, batch_inds,
                                         pools,
                                         method='bilinear',
                                         name='Crop')
images = [cv2.imread(file) for file in glob.glob("/home/ubuntu/Pictures/TeImage/*.png")]
img= np.asarray(images)
boxes = [100, 100, 200, 200]
batch_inds=2
crop(img, boxes, batch_inds,1,7,7,'ROIAlign')
</code>```

答: [] means that it was a scalar (aka tensor with rank=0), and the op is expecting a 1D tensor (rank=1). Try to pass something like [batch_inds] to the crop_and_resize op, or change it in some other way to make it a vector, not a scalar.

Body:
I tried to give all input in this function but it comes out problem like below , i not sure what is the empty [] is .
There are 2 image image in RGB and the original code is from https://github.com/CharlesShang/FastMaskRCNN/blob/master/libs/layers/crop.py.

Traceback (most recent call last):
  File "croptest.py", line 77, in <module>
    crop(img, boxes, batch_inds,1,7,7,'ROIAlign')
  File "croptest.py", line 64, in crop
    name='Crop')
  File "/home/ubuntu/Desktop/WK/my_project/lib/python2.7/site-packages/tensorflow/python/ops/gen_image_ops.py", line 166, in crop_and_resize
    name=name)
  File "/home/ubuntu/Desktop/WK/my_project/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
    op_def=op_def)
  File "/home/ubuntu/Desktop/WK/my_project/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2632, in create_op
    set_shapes_for_outputs(ret)
  File "/home/ubuntu/Desktop/WK/my_project/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1911, in set_shapes_for_outputs
    shapes = shape_func(op)
  File "/home/ubuntu/Desktop/WK/my_project/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1861, in call_with_requiring
    return call_cpp_shape_fn(op, require_shape_fn=True)
  File "/home/ubuntu/Desktop/WK/my_project/lib/python2.7/site-packages/tensorflow/python/framework/common_shapes.py", line 595, in call_cpp_shape_fn
    require_shape_fn)
  File "/home/ubuntu/Desktop/WK/my_project/lib/python2.7/site-packages/tensorflow/python/framework/common_shapes.py", line 659, in _call_cpp_shape_fn_impl
    raise ValueError(err.message)
ValueError: Shape must be rank 1 but is rank 0 for 'ROIAlign/Crop' (op: 'CropAndResize') with input shapes: [2,360,475,3], [1,4], [], [2].

the code i run is shown as below.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import glob
import tensorflow as tf
import numpy as np
import cv2

def crop(images, boxes, batch_inds, stride, pooled_height, pooled_width, scope):
  """Cropping areas of features into fixed size
  Params:
  --------
  images: a 4-d Tensor of shape (N, H, W, C)
  boxes: rois in the original image, of shape (N, ..., 4), [x1, y1, x2, y2]
  batch_inds:

  Returns:
  --------
  A Tensor of shape (N, pooled_height, pooled_width, C)
  """
  with tf.name_scope(scope):
    boxes = [x / (stride+0.0) for x in boxes]
    boxes = tf.reshape(boxes, [-1, 4])
    print(images)

    print(images.shape)
    shape = tf.shape(images)
    boxes = tf.reshape(boxes, [-1, 2]) # to (x, y)
    xs = boxes[:, 0]
    ys = boxes[:, 1]
    xs = xs / tf.cast(shape[2], tf.float32)
    ys = ys / tf.cast(shape[1], tf.float32)
    boxes = tf.concat([ys[:, tf.newaxis], xs[:, tf.newaxis]], axis=1)
    boxes = tf.reshape(boxes, [-1, 4])  # to (y1, x1, y2, x2)
    assert_op = tf.Assert(tf.greater(tf.size(images), 0), [images, batch_inds])
    print(assert_op)
    print("-----------------------")
    print(images.astype('float'))
    print("-----------------------")
    print(batch_inds)
    x=images.astype('float')
    print("-----------------------")
    print(batch_inds)
    print("-----------------------")
    print(pooled_height)
    print("-----------------------")
    pools =[pooled_height, pooled_width]

    arg = tf.convert_to_tensor(x, dtype=tf.float32)
    arg1 = tf.convert_to_tensor(batch_inds)
    with tf.control_dependencies([assert_op, arg,arg1 ]):
        return  tf.image.crop_and_resize(images, boxes, batch_inds,
                                         pools,
                                         method='bilinear',
                                         name='Crop')
images = [cv2.imread(file) for file in glob.glob("/home/ubuntu/Pictures/TeImage/*.png")]
img= np.asarray(images)
boxes = [100, 100, 200, 200]
batch_inds=2
crop(img, boxes, batch_inds,1,7,7,'ROIAlign')


问:
SQL Server 2012 - using select * into along with dynamic SQL

Hi I have the the following code:

```<code>use TSQL2012;
go

if OBJECT_ID('Sales.FreightTotals') is not null drop table
Sales.FreightTotals
go

declare @shipperid as nvarchar(max) ='';
declare @dsql as nvarchar(max);
select @shipperid += quotename(shipperid,'')+',' from sales.Orders group by
shipperid;
set @shipperid = LEFT(@shipperid, LEN(@shipperid)-1)

print @shipperid;

set @dsql='
select empid,'+@shipperid+' from
(select empid, shipperid, freight from Sales.Orders )as d
pivot(sum(freight) for shipperid in('+@shipperid+')) as pvt
order by pvt.empid
'
</code>```

print @dsql

--exec sp_executesql @dsql

```<code>select * into Sales.FreightTotals from @dsql;
</code>```

I am trying to use select * into with dynamic pivot as shown above.If I use

```<code>exec sp_executesql @dsql
</code>```

I get the following result the result i am looking for

```<code>empid       1                     2                     3
----------- --------------------- --------------------- --------------------
1           2194.73               3259.99               3381.92
2           2281.09               4350.20               2065.12
3           2491.74               4258.90               4134.10
4           3129.39               4926.73               3290.02
5           1218.27               1991.84               708.60
6           1049.83               1270.42               1460.22
7           1204.60               3155.18               2305.66
8           1889.27               3297.40               2301.21
9           726.41                1734.19               865.66

(9 rows affected)
</code>```

but if I do
    select * into Sales.FreightTotals from @dsql;

i get:

```<code>Msg 1087, Level 16, State 1, Line 26
Must declare the table variable "@dsql".
</code>```

any suggestion as to why this is the case?

答:
It looks like your local variable '@dsql' is declared within your stored procedure.

So when you call the sp the variable is declared before it's printed - 'PRINT'

When you run the same printed line, the varable has not been declared and so you recieve the error.

Body:
Hi I have the the following code:

use TSQL2012;
go

if OBJECT_ID('Sales.FreightTotals') is not null drop table
Sales.FreightTotals
go

declare @shipperid as nvarchar(max) ='';
declare @dsql as nvarchar(max);
select @shipperid += quotename(shipperid,'')+',' from sales.Orders group by
shipperid;
set @shipperid = LEFT(@shipperid, LEN(@shipperid)-1)

print @shipperid;

set @dsql='
select empid,'+@shipperid+' from
(select empid, shipperid, freight from Sales.Orders )as d
pivot(sum(freight) for shipperid in('+@shipperid+')) as pvt
order by pvt.empid
'

print @dsql

--exec sp_executesql @dsql

select * into Sales.FreightTotals from @dsql;

I am trying to use select * into with dynamic pivot as shown above.If I use

exec sp_executesql @dsql

I get the following result the result i am looking for

empid       1                     2                     3
----------- --------------------- --------------------- --------------------
1           2194.73               3259.99               3381.92
2           2281.09               4350.20               2065.12
3           2491.74               4258.90               4134.10
4           3129.39               4926.73               3290.02
5           1218.27               1991.84               708.60
6           1049.83               1270.42               1460.22
7           1204.60               3155.18               2305.66
8           1889.27               3297.40               2301.21
9           726.41                1734.19               865.66

(9 rows affected)

but if I do
    select * into Sales.FreightTotals from @dsql;

i get:

Msg 1087, Level 16, State 1, Line 26
Must declare the table variable "@dsql".

any suggestion as to why this is the case?


答:
something like this

```<code>render() {
  var temp = [], arr = []
  while(A.length){
    temp.push(A.shift())
    A.length && temp.push(A.shift())
    arr.push(temp)
    temp = []
  } // creates array of arrays
  return arr.map(rowOfTwo =>
    <Row>
     {rowOfTwo[0]}
     {rowOfTwo.length > 1 && rowOfTwo[1]}
    </Row>
  )
}
</code>```

basically preform your split :)

Body:
something like this

render() {
  var temp = [], arr = []
  while(A.length){
    temp.push(A.shift())
    A.length && temp.push(A.shift())
    arr.push(temp)
    temp = []
  } // creates array of arrays
  return arr.map(rowOfTwo =>
    <Row>
     {rowOfTwo[0]}
     {rowOfTwo.length > 1 && rowOfTwo[1]}
    </Row>
  )
}

basically preform your split :)


问:
R sum of random numbers?
I am trying to Write a R function that will generate n(that are passed to a function) random numbers and return the sum of the numbers and show that random set of numbers

I am new to R and assuming an array would be used here,but not sure.
Also, my attempt only allows for 10 numbers, but if i try to do it for any amount other than 10 it gives wrong sum.

I don't know what I am doing wrong, but this is what i have got so far.

```<code>random.sum <- function(n) {
x[1:n] <- ceiling(10*runif(n))
cat("x:", x[1:n], "\n")
return(sum(x))
}
x <- rep(100, 10)
show(random.sum(10))
</code>```

答:
You are almost correct.

You don't need to assign x to anything outside the function, and inside your function you don't need to subset x, you can just assign it with the n random numbers. Then it will work

```<code>random.sum <- function(n) {
    x <- ceiling(10*runif(n))
    cat("x:", x, "\n")
    return(sum(x))
    }

random.sum(13)
x: 4 6 10 4 6 10 8 2 5 10 4 4 6
[1] 79
</code>```

Explanation

If you assign x <- rep(100, 10) outside the function, you are creating a vector size 10, each element being value 100.

Due to 'lexical scoping', this x is available inside the random.sum function, so when you have the line

```<code>x[1:4] <- ceiling(10*runif(n))   ## where n = 4
</code>```

You are assigning the first 4 values of x to be a random number, but the remaining values are still 100. So your sum is actually (100 * 6) + 4 random numbers

You can see this happening if you throw in a few print statements into your original function

```<code>random.sum <- function(n) {
    print(x)
    x[1:n] <- ceiling(10*runif(n))
    print(x)
    cat("x:", x[1:n], "\n")
    print(x)
    return(sum(x))
}

x <- rep(100, 10)
random.sum(4)

# [1] 100 100 100 100 100 100 100 100 100 100
# [1]   5   2   1   3 100 100 100 100 100 100
# x: 5 2 1 3
# [1]   5   2   1   3 100 100 100 100 100 100
# [1] 611
</code>```

Title: R sum of random numbers?

Body:
I am trying to Write a R function that will generate n(that are passed to a function) random numbers and return the sum of the numbers and show that random set of numbers

I am new to R and assuming an array would be used here,but not sure.
Also, my attempt only allows for 10 numbers, but if i try to do it for any amount other than 10 it gives wrong sum.

I don't know what I am doing wrong, but this is what i have got so far.

random.sum <- function(n) {
x[1:n] <- ceiling(10*runif(n))
cat("x:", x[1:n], "\n")
return(sum(x))
}
x <- rep(100, 10)
show(random.sum(10))

Body:
You are almost correct.

You don't need to assign x to anything outside the function, and inside your function you don't need to subset x, you can just assign it with the n random numbers. Then it will work

random.sum <- function(n) {
    x <- ceiling(10*runif(n))
    cat("x:", x, "\n")
    return(sum(x))
    }

random.sum(13)
x: 4 6 10 4 6 10 8 2 5 10 4 4 6
[1] 79

Explanation

If you assign x <- rep(100, 10) outside the function, you are creating a vector size 10, each element being value 100.

Due to 'lexical scoping', this x is available inside the random.sum function, so when you have the line

x[1:4] <- ceiling(10*runif(n))   ## where n = 4

You are assigning the first 4 values of x to be a random number, but the remaining values are still 100. So your sum is actually (100 * 6) + 4 random numbers

You can see this happening if you throw in a few print statements into your original function

random.sum <- function(n) {
    print(x)
    x[1:n] <- ceiling(10*runif(n))
    print(x)
    cat("x:", x[1:n], "\n")
    print(x)
    return(sum(x))
}

x <- rep(100, 10)
random.sum(4)

# [1] 100 100 100 100 100 100 100 100 100 100
# [1]   5   2   1   3 100 100 100 100 100 100
# x: 5 2 1 3
# [1]   5   2   1   3 100 100 100 100 100 100
# [1] 611


问:
Php add 5 working days to current date excluding weekends (sat-sun) and excluding (multiple) holidays
For delivery of our webshop, we need to calculate 5 working days from the current date in php.

Our working days are from monday to friday and we have several closing days (holidays) which cannot be included either.

I've found this script, but this doesn't include holidays.

```<code><?php

    $_POST['startdate'] = date("Y-m-d");
    $_POST['numberofdays'] = 5;

    $d = new DateTime( $_POST['startdate'] );
    $t = $d->getTimestamp();

    // loop for X days
    for($i=0; $i<$_POST['numberofdays']; $i++){

        // add 1 day to timestamp
        $addDay = 86400;

        // get what day it is next day
        $nextDay = date('w', ($t+$addDay));

        // if it's Saturday or Sunday get $i-1
        if($nextDay == 0 || $nextDay == 6) {
            $i--;
        }

        // modify timestamp, add 1 day
        $t = $t+$addDay;
    }

    $d->setTimestamp($t);

    echo $d->format('Y-m-d'). "\n";

?>
</code>```

答:
A function based on Tinh Dang's answer:

```<code>function getFutureBusinessDay($num_business_days, $today_ymd = null, $holiday_dates_ymd = []) {
    $num_business_days = min($num_business_days, 1000);
    $business_day_count = 0;
    $current_timestamp = empty($today_ymd) ? time() : strtotime($today_ymd);
    while ($business_day_count < $num_business_days) {
        $next1WD = strtotime('+1 weekday', $current_timestamp);
        $next1WDDate = date('Y-m-d', $next1WD);
        if (!in_array($next1WDDate, $holiday_dates_ymd)) {
            $business_day_count++;
        }
        $current_timestamp = $next1WD;
    }
    return date('Y-m-d', $current_timestamp);
}
</code>```

I made it limit the loop to 1000 business days. There could be no limit if desired.

Body:
For delivery of our webshop, we need to calculate 5 working days from the current date in php.

Our working days are from monday to friday and we have several closing days (holidays) which cannot be included either.

I've found this script, but this doesn't include holidays.

<?php

    $_POST['startdate'] = date("Y-m-d");
    $_POST['numberofdays'] = 5;

    $d = new DateTime( $_POST['startdate'] );
    $t = $d->getTimestamp();

    // loop for X days
    for($i=0; $i<$_POST['numberofdays']; $i++){

        // add 1 day to timestamp
        $addDay = 86400;

        // get what day it is next day
        $nextDay = date('w', ($t+$addDay));

        // if it's Saturday or Sunday get $i-1
        if($nextDay == 0 || $nextDay == 6) {
            $i--;
        }

        // modify timestamp, add 1 day
        $t = $t+$addDay;
    }

    $d->setTimestamp($t);

    echo $d->format('Y-m-d'). "\n";

?>

Body:
A function based on Tinh Dang's answer:

function getFutureBusinessDay($num_business_days, $today_ymd = null, $holiday_dates_ymd = []) {
    $num_business_days = min($num_business_days, 1000);
    $business_day_count = 0;
    $current_timestamp = empty($today_ymd) ? time() : strtotime($today_ymd);
    while ($business_day_count < $num_business_days) {
        $next1WD = strtotime('+1 weekday', $current_timestamp);
        $next1WDDate = date('Y-m-d', $next1WD);
        if (!in_array($next1WDDate, $holiday_dates_ymd)) {
            $business_day_count++;
        }
        $current_timestamp = $next1WD;
    }
    return date('Y-m-d', $current_timestamp);
}

I made it limit the loop to 1000 business days. There could be no limit if desired.


问:
How to get a UIViewController from a UIView via code
There is a way to get a view controller reference from a UIView object? I need something like this:

```<code>MyParentViewController *myParentViewController = [self.view.superview controller];
</code>```

答: You can use the -nextResponder method to do it. According to http://developer.apple.com/library/ios/documentation/uikit/reference/UIResponder_Class/Reference/Reference.html#//apple_ref/occ/instm/UIResponder/nextResponder , "UIView implements this method by returning the UIViewController object that manages it (if it has one) or its superview (if it doesn’t)"

Body:
There is a way to get a view controller reference from a UIView object? I need something like this:

MyParentViewController *myParentViewController = [self.view.superview controller];


问:
How overflow property in CSS actually works?
I have few queries related to overflow property in CSS-
Check this below code snippet,

.outer-div {
    display: flex;
    position: relative;
    height: 3.5em;
    width: 20%;
    border: 2px solid #000000a3;
    margin-left: 300px;
    align-items: center;
    border: 1px solid green;
}
.inner-div {
 border: 1px solid blue;
    position: absolute;
    right: 1%;
    font-size: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
</head>
<body>
  <div class = "outer-div">
    <div class = "inner-div">HelloWorld</div>
  </div>
</body></code>```

In the above snippet, the inner-div container is overflowing in the x-direction and not in y-direction. But if I add overflow: scroll, then it adds a scroll bar in both directions(fine till here), but I am able to use the scroll bar of y-direction and not x-direction, despite the fact that the inner-div container is overflowing in the x-direction. Why is it so?
Check this snippet,

.outer-div {
    display: flex;
    position: relative;
    height: 3.5em;
    width: 20%;
    border: 2px solid #000000a3;
    margin-left: 300px;
    align-items: center;
    border: 1px solid green;
    overflow: scroll;
}
.inner-div {
 border: 1px solid blue;
    position: absolute;
    right: 1%;
    font-size: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
</head>
<body>
  <div class = "outer-div">
    <div class = "inner-div">HelloWorld</div>
  </div>
</body>
</html></code>```

My last query is, if I separate the text with a hyphen(-) or a space, why it breaks into 2 lines and not continue in the same line? I know it may be because of the size of my outer container but why not it splits when I enter text without spaces? Check below,

.outer-div {
    display: flex;
    position: relative;
    height: 3.5em;
    width: 20%;
    border: 2px solid #000000a3;
    margin-left: 300px;
    align-items: center;
    border: 1px solid green;
}
.inner-div {
 border: 1px solid blue;
    position: absolute;
    right: 1%;
    font-size: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
</head>
<body>
  <div class = "outer-div">
    <div class = "inner-div">Hello World</div>
  </div>
</body>
</html></code>```

Thanks a lot for giving your time and for your help!

答:
The div has no horizontal scroll bars because it is absolutely positioned. Set your .inner-div's position property to something other than absolute orfixed, and your div will have the desired scrolling function.

As for the line splitting, that is because of automatic word wrapping that breaks the line at the end of a word or hyphen.

Body:
I have few queries related to overflow property in CSS-
Check this below code snippet,

.outer-div {
    display: flex;
    position: relative;
    height: 3.5em;
    width: 20%;
    border: 2px solid #000000a3;
    margin-left: 300px;
    align-items: center;
    border: 1px solid green;
}
.inner-div {
 border: 1px solid blue;
    position: absolute;
    right: 1%;
    font-size: 40px;
}

HelloWorld

In the above snippet, the inner-div container is overflowing in the x-direction and not in y-direction. But if I add overflow: scroll, then it adds a scroll bar in both directions(fine till here), but I am able to use the scroll bar of y-direction and not x-direction, despite the fact that the inner-div container is overflowing in the x-direction. Why is it so?
Check this snippet,

.outer-div {
    display: flex;
    position: relative;
    height: 3.5em;
    width: 20%;
    border: 2px solid #000000a3;
    margin-left: 300px;
    align-items: center;
    border: 1px solid green;
    overflow: scroll;
}
.inner-div {
 border: 1px solid blue;
    position: absolute;
    right: 1%;
    font-size: 40px;
}

HelloWorld

My last query is, if I separate the text with a hyphen(-) or a space, why it breaks into 2 lines and not continue in the same line? I know it may be because of the size of my outer container but why not it splits when I enter text without spaces? Check below,

.outer-div {
    display: flex;
    position: relative;
    height: 3.5em;
    width: 20%;
    border: 2px solid #000000a3;
    margin-left: 300px;
    align-items: center;
    border: 1px solid green;
}
.inner-div {
 border: 1px solid blue;
    position: absolute;
    right: 1%;
    font-size: 40px;
}

Hello World

Thanks a lot for giving your time and for your help!


问:
How to handle DynamoDB Global streams
Looking to create a DynamoDB global table for storing customer information. The problem I have is my current pattern is to listen to changes on this table and send email updates using Lambda triggers.

i.e. Your profile information was changed. If this was not you..

Do I now need to have that Lambda in each region and will data replication mean that it is triggered for each region?

答:
I think you might have misunderstood with streams.

Global Tables needs streams enabled on the table to replicate between regions. You can check the requirements and how it works.

http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables_HowItWorks.html

If you have trigger, you can have only in one region. Whichever region is having the lambda associated to the trigger will get notified with the updates.

The benefit from the global table you get is, if any regions updates the data, the lambda in the region you have configured will get triggered. Only one trigger will be sent to the lambda.

Enabling streams is one of the requirements for DynamoDB Global Tables.

If you create trigger in multiple regions, you need to implement your Lambda with idempotency i.e., if the same data is delivered any number of times, it will perform the operation only once.

Hope it helps.

Title: How to handle DynamoDB Global streams