问:
change text when button selected
I need to be able to have a series of buttons that when you select one, it assigns the address for that button to the value.  Problem is that it only does it once & I can't figure out a way to fix this.  If you run the code you will see initially I assign the value="Seattle, WA", then when you click one of the buttons I want it to change it to the new value.

I added a function ClearFields() as I thought that would fix the problem.

function AddressTextBox() {
         document.getElementById('address').value =
         document.getElementById('address1').value;
       }

function ClearFields() {
         document.getElementById("address1").value = "";
         document.getElementById("address").value = "";
       }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div>
       <Button onclick="AddressTextBox();" id="address1" data-toggle="modal"
          data-target="#Business-Signup" type="text" value="12080 SW Myslony
          St., Tualatin, OR">
          Business Information - Tualatin, Or
       </button>

       <Button onclick="AddressTextBox();" id="address1" data-toggle="modal"
          data-target="#Business-Signup" type="text" value="13009 SE Jennifer
          St, Clackamas, OR">
          Business Information - Clakamas, Or
       </button>
    </div>

    <div class="officeaddress">
      <ul>
         <li>
           <br />
           <label class="buslabel" for="Name">Address:
              <strong><input id="address" tabindex="6" style="margin-left:
                 5px; border: none; padding: 0;" type="text"
                 class="busaddinput" placeholder="Street Address" size="25"
                 name="streetaddress" maxlength="34" value="Seattle, WA"
                 required>
              </strong>
            </label>
        </li>
        <li>
          <label class="buslabel" for="Name">City:
            <strong><input tabindex="7" style="margin-left: 32px; border:
               none; padding: 0;" type="text" class="busaddinput"
               placeholder="City" name="city" size="20" maxlength="30"
               value="Puyallup" required></strong>
          </label>
       </li>
       <li>
         <label class="buslabel" for="Name">State:
            <strong><input type="text" tabindex="8" style="margin-left: 24px;
            border: none; padding: 0;" class="busaddinput"
            placeholder="State" name="state" size="10" maxlength="10"
            value="WA" required></strong>
         </label>
        </li>
       </ul>
     </div></code>```

答:
You have two button elements with the same id="address1".

document.getElementById('address1').value only returns the first element that matches the ID, so it is only retrieving the value from the first button. To retrieve the value from the second button, you would need to give the second button a unique ID like "address2", and use document.getElementById('address2').value to access it.

A better way to handle this may be to reference the clicked element in your AddressTextBox function. Then you don't even need to rely on ID's for your buttons, just for the field you want to set:

  function AddressTextBox(element) {
     document.getElementById('address').value =
     element.value;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
   <Button onclick="AddressTextBox(this);" data-toggle="modal"
      data-target="#Business-Signup" type="text" value="12080 SW Myslony
      St., Tualatin, OR">
      Business Information - Tualatin, Or
   </button>

   <Button onclick="AddressTextBox(this);" data-toggle="modal"
      data-target="#Business-Signup" type="text" value="13009 SE Jennifer
      St, Clackamas, OR">
      Business Information - Clakamas, Or
   </button>
</div>

<div class="officeaddress">
  <ul>
     <li>
       <br />
       <label class="buslabel" for="Name">Address:
          <strong><input id="address" tabindex="6" style="margin-left:
             5px; border: none; padding: 0;" type="text"
             class="busaddinput" placeholder="Street Address" size="25"
             name="streetaddress" maxlength="34" value="Seattle, WA"
             required>
          </strong>
        </label>
    </li>
    <li>
      <label class="buslabel" for="Name">City:
        <strong><input tabindex="7" style="margin-left: 32px; border:
           none; padding: 0;" type="text" class="busaddinput"
           placeholder="City" name="city" size="20" maxlength="30"
           value="Puyallup" required></strong>
      </label>
   </li>
   <li>
     <label class="buslabel" for="Name">State:
        <strong><input type="text" tabindex="8" style="margin-left: 24px;
        border: none; padding: 0;" class="busaddinput"
        placeholder="State" name="state" size="10" maxlength="10"
        value="WA" required></strong>
     </label>
    </li>
   </ul>
 </div></code>```

In the example above I have included a parameter called element in the AddressTextBox function. I then used the this keyword in the onclick event of each button to call AddressTextBox() with the button element that was clicked.

Title: change text when button selected

Body:
I need to be able to have a series of buttons that when you select one, it assigns the address for that button to the value.  Problem is that it only does it once & I can't figure out a way to fix this.  If you run the code you will see initially I assign the value="Seattle, WA", then when you click one of the buttons I want it to change it to the new value.

I added a function ClearFields() as I thought that would fix the problem.

function AddressTextBox() {
         document.getElementById('address').value =
         document.getElementById('address1').value;
       }

function ClearFields() {
         document.getElementById("address1").value = "";
         document.getElementById("address").value = "";
       }

       <Button onclick="AddressTextBox();" id="address1" data-toggle="modal"
          data-target="#Business-Signup" type="text" value="12080 SW Myslony
          St., Tualatin, OR">
          Business Information - Tualatin, Or
       </button>

       <Button onclick="AddressTextBox();" id="address1" data-toggle="modal"
          data-target="#Business-Signup" type="text" value="13009 SE Jennifer
          St, Clackamas, OR">
          Business Information - Clakamas, Or
       </button>

           Address:
              <input id="address" tabindex="6" style="margin-left:
                 5px; border: none; padding: 0;" type="text"
                 class="busaddinput" placeholder="Street Address" size="25"
                 name="streetaddress" maxlength="34" value="Seattle, WA"
                 required>

          City:
            <input tabindex="7" style="margin-left: 32px; border:
               none; padding: 0;" type="text" class="busaddinput"
               placeholder="City" name="city" size="20" maxlength="30"
               value="Puyallup" required>

         State:
            <input type="text" tabindex="8" style="margin-left: 24px;
            border: none; padding: 0;" class="busaddinput"
            placeholder="State" name="state" size="10" maxlength="10"
            value="WA" required>

Body:
You have two button elements with the same id="address1".

document.getElementById('address1').value only returns the first element that matches the ID, so it is only retrieving the value from the first button. To retrieve the value from the second button, you would need to give the second button a unique ID like "address2", and use document.getElementById('address2').value to access it.

A better way to handle this may be to reference the clicked element in your AddressTextBox function. Then you don't even need to rely on ID's for your buttons, just for the field you want to set:

  function AddressTextBox(element) {
     document.getElementById('address').value =
     element.value;
  }

<div>
   <Button onclick="AddressTextBox(this);" data-toggle="modal"
      data-target="#Business-Signup" type="text" value="12080 SW Myslony
      St., Tualatin, OR">
      Business Information - Tualatin, Or
   </button>

   <Button onclick="AddressTextBox(this);" data-toggle="modal"
      data-target="#Business-Signup" type="text" value="13009 SE Jennifer
      St, Clackamas, OR">
      Business Information - Clakamas, Or
   </button>
</div>

<div class="officeaddress">
  <ul>
     <li>
       <br />
       <label class="buslabel" for="Name">Address:
          <strong><input id="address" tabindex="6" style="margin-left:
             5px; border: none; padding: 0;" type="text"
             class="busaddinput" placeholder="Street Address" size="25"
             name="streetaddress" maxlength="34" value="Seattle, WA"
             required>
          </strong>
        </label>
    </li>
    <li>
      <label class="buslabel" for="Name">City:
        <strong><input tabindex="7" style="margin-left: 32px; border:
           none; padding: 0;" type="text" class="busaddinput"
           placeholder="City" name="city" size="20" maxlength="30"
           value="Puyallup" required></strong>
      </label>
   </li>
   <li>
     <label class="buslabel" for="Name">State:
        <strong><input type="text" tabindex="8" style="margin-left: 24px;
        border: none; padding: 0;" class="busaddinput"
        placeholder="State" name="state" size="10" maxlength="10"
        value="WA" required></strong>
     </label>
    </li>
   </ul>
 </div>

In the example above I have included a parameter called element in the AddressTextBox function. I then used the this keyword in the onclick event of each button to call AddressTextBox() with the button element that was clicked.


来源: stackexchange

问:
Remove default text/placeholder present in html5 input element of type=date
I am using html input element with type as date,

```<code><input type="date">
</code>```

When I use above element it creates a default date format i.e. mm/dd/yyyy text within that input element. How do I remove this default text?

I tried adding below style on my page but it is hiding the selected date value as well,

```<code>input[type=date]::-webkit-datetime-edit-text {
    -webkit-appearance: none;
    display: none;
}
input[type=date]::-webkit-datetime-edit-month-field{
    -webkit-appearance: none;
    display: none;
}
input[type=date]::-webkit-datetime-edit-day-field {
    -webkit-appearance: none;
    display: none;
}
input[type=date]::-webkit-datetime-edit-year-field {
    -webkit-appearance: none;
    display: none;
}
</code>```

答:
This works in chrome and doesn't make the value dissapear when set (Version 74)</p>

```<code>input[value=""]::-webkit-datetime-edit{ color: transparent; }
input:focus::-webkit-datetime-edit{ color: #000; }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using html input element with type as date,

<input type="date">

When I use above element it creates a default date format i.e. mm/dd/yyyy text within that input element. How do I remove this default text?

I tried adding below style on my page but it is hiding the selected date value as well,

input[type=date]::-webkit-datetime-edit-text {
    -webkit-appearance: none;
    display: none;
}
input[type=date]::-webkit-datetime-edit-month-field{
    -webkit-appearance: none;
    display: none;
}
input[type=date]::-webkit-datetime-edit-day-field {
    -webkit-appearance: none;
    display: none;
}
input[type=date]::-webkit-datetime-edit-year-field {
    -webkit-appearance: none;
    display: none;
}

Body:
This works in chrome and doesn't make the value dissapear when set (Version 74)

input[value=""]::-webkit-datetime-edit{ color: transparent; }
input:focus::-webkit-datetime-edit{ color: #000; }

ContentLicense: CC BY-SA 4.0


问:
Laravel Eloquent Relationship: misunderstanding them?
Good day! I think I am doing something wrong or I'm misunderstanding Eloquent practices.

I have three tables.

orders { city, county }

cities { id, name }

counties { id, name }

I am performing queries upon these tables using Laravel Eloquent One-To-Many-Inverse Relationship. orders.city holds one id of cities and orders.county holds one id of counties. Below is the code of my models.

App\Orders

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Orders extends Model
{
    /*
    *   Table name
    */
    protected $table = 'orders';

    /*
    *   Get county
    */
    public function county()
    {
        return $this -> hasOne('App\Counties', 'id', 'county');
    }

    /*
    *   Get city
    */
    public function city()
    {
        return $this -> hasOne('App\Cities', 'id', 'city');
    }

}
</code>```

App\Counties

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Counties extends Model
{
    protected $table = 'account_county';
    public $timestamps = false;

    /*
    *   Counties relationship
    */
    public function county()
    {
        return $this -> belongsTo('App\Orders', 'county', 'id');
    }
}

</code>```

App\Cities

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Cities extends Model
{
    protected $table = 'account_city';
    public $timestamps = false;

    /*
    *   City relationship
    */
    public function city()
    {
        return $this -> belongsTo('App\Orders', 'city', 'id');
    }
}

</code>```

When I execute the following in Tinker: $order = App\Orders::with(['city', 'county']) -> first();

....I get the following response:

```<code>App\Orders {#3042
     county: App\Counties {#3041
       id: 23,
       name: "Argeș",
     },
     city: App\Cities {#3046
       id: 6924,
       name: "Argeșelu",
     },
   }
</code>```

Now when I run the following code: $order -> city

I get the following response:

```<code>"6924"
</code>```

When I execute the following code however: $order -> City

I get the whole collection:

```<code>App\Cities {#3046
       id: 6924,
       name: "Argeșelu",
     },
</code>```

Why do I need to uppercase the first letter of property to get the collection instance? In documentation it states I should use the dynamic property name directly: $order -> city however in my case this returns the raw string ID not the collection instance. Am I missing something? I am concerned about performance and good practice reasons. I apologize if it's a bad question or if it has been explained somewhere else already.

答:
You're experiencing this problem because of the naming convention you are using for your database fields and relationships.

When loading data from a database table, will assign each field that you pull from your database to an attribute on your model. These are retrieved via PHP's __get and __set magic methods, based on the name of the database field. So $order->city actually fetches the value of the database field on the row of that table.

One thing to note here is that city as the attribute name is case sensitive, which brings us to the next issue.

When you call $order->City on the model (note the case), it first looks for a database field attribute called City. Because of case sensitivity, it cannot find a database field of that name.

The next thing Eloquent does is it checks to see if there is a relationship function called city. Note the case. PHP class functions are not case sensitive, so you can defined a function called city and call it as City(). So when you ask for $order->City, it calls the relationship function of that name and returns the DB results.

This is the reason you get the correct results when you call City instead of city.

To fix the issue, I recommend renaming your relationship fields city and county to the more standard (for Eloquent) values of city_id and county_id. Not only will this reduce your confusions, but you'll benefit from some of the built in Eloquent functionality to make your life easier.

As an aside to this, the reason your $order->city was coming back as a string was due to the way Eloquent treats database fields by convention. It does not generally read the schema to look at the datatypes, but generally treats everything as strings unless you explicitly cast it to a PHP type, or it meets a specific naming convention. For instance,  Eloquent will assuming any field ending in _id is a number, and treat it as a integer by default. So renaming city to city_id will fix this for you automagically.

Also, check your relationships as a whole. It seems to be you would be better with BelongsTo relationships both on City and County.

Body:
Good day! I think I am doing something wrong or I'm misunderstanding Eloquent practices.

I have three tables.

orders { city, county }

cities { id, name }

counties { id, name }

I am performing queries upon these tables using Laravel Eloquent One-To-Many-Inverse Relationship. orders.city holds one id of cities and orders.county holds one id of counties. Below is the code of my models.

App\Orders

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Orders extends Model
{
    /*
    *   Table name
    */
    protected $table = 'orders';

    /*
    *   Get county
    */
    public function county()
    {
        return $this -> hasOne('App\Counties', 'id', 'county');
    }

    /*
    *   Get city
    */
    public function city()
    {
        return $this -> hasOne('App\Cities', 'id', 'city');
    }

}

App\Counties

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Counties extends Model
{
    protected $table = 'account_county';
    public $timestamps = false;

    /*
    *   Counties relationship
    */
    public function county()
    {
        return $this -> belongsTo('App\Orders', 'county', 'id');
    }
}

App\Cities

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Cities extends Model
{
    protected $table = 'account_city';
    public $timestamps = false;

    /*
    *   City relationship
    */
    public function city()
    {
        return $this -> belongsTo('App\Orders', 'city', 'id');
    }
}

When I execute the following in Tinker: $order = App\Orders::with(['city', 'county']) -> first();

....I get the following response:

App\Orders {#3042
     county: App\Counties {#3041
       id: 23,
       name: "Argeș",
     },
     city: App\Cities {#3046
       id: 6924,
       name: "Argeșelu",
     },
   }

Now when I run the following code: $order -> city

I get the following response:

"6924"

When I execute the following code however: $order -> City

I get the whole collection:

App\Cities {#3046
       id: 6924,
       name: "Argeșelu",
     },

Why do I need to uppercase the first letter of property to get the collection instance? In documentation it states I should use the dynamic property name directly: $order -> city however in my case this returns the raw string ID not the collection instance. Am I missing something? I am concerned about performance and good practice reasons. I apologize if it's a bad question or if it has been explained somewhere else already.


问:
Background not appearing for some webpages
The background is appearing for some of my webpages and not for some.

This is my main.css:

html {
    background: url("../images/bg.png") no-repeat center center fixed;
}
```

I notice webpages with single path eg. localhost:8080/index will have the background but double path eg. localhost:8080/index/register will not have the background.

Thanks in advance.

答:
Relative paths used inside a stylesheet-file are relative to the path of the stylesheet itself. So if the stylesheet-file is working on one page it should also work on other pages.

It could be that your html-files are not loading the stylesheet at all. You should check the dev-tools (network-tab) and see if there are any 404-errors for either the stylesheet or the background-image.

Update:

Refused to apply style from 'path/to/style.css' because its MIME type
  ('application/json') is not a supported stylesheet MIME type.

This Error/Warning can be the result of stylesheet that was not found (404). You should check the network-tab of the dev-tols for any 404-errors and also check path of the link-tags in your html-documents. If the stylesheet is working for one document in your environment but not for other documents, it could be that your referenced path to the stylsheet is not an absolute path.

But there could be other reasons for this error/warning. There are already questions about that topic on stackoverflow. For example: Stylesheet not loaded because of MIME-type.

Body:
The background is appearing for some of my webpages and not for some.

This is my main.css:

html {
    background: url("../images/bg.png") no-repeat center center fixed;
}

I notice webpages with single path eg. localhost:8080/index will have the background but double path eg. localhost:8080/index/register will not have the background.

Thanks in advance.


问:
How to Extract Value of Output in R?
How can you extract the index value of a result in R.

data.frame(sort(table(df$col1),decreasing=TRUE))

This results in an output of the col1 value and its count.
The output is the following:

```<code>          Var1   |    freq
   ---------------------------
    1     ABC    |      10
    2     DEF    |       9
   ...
</code>```

I'm basically trying to extract 'ABC'.

UPDATED ANSWER:

The following options will output the greatest reoccuring value in a column (col1) while retaining the original datatype:

```<code>subset(df,!is.na(df$col1),) %>% count(col1) %>% arrange(desc(n)) %>% c(1)[1][[1]]
OR
data.frame(sort(table(df$col1),decreasing=TRUE))[1,1]
OR
sqldf("SELECT COUNT(*) as count, col1 FROM df WHERE col1 IS NOT NULL GROUP BY col1 ORDER BY count DESC")$col1[1]

</code>```

答:
Since the result of data.frame() is a data frame, one can immediately use the extract operator on it.

```<code># generate the data
x <- c(rep("ABC",10),rep("DEF",9))

# extract string with highest frequency from table
data.frame(sort(table(x),decreasing=TRUE))[1,1]
</code>```

... and the result:

```<code>> data.frame(sort(table(x),decreasing=TRUE))[1,1]
[1] ABC
Levels: ABC DEF
>
</code>```

One can use as.character() to remove the factor levels from the result.

Based on the comments there is a need to obtain counts for numeric variables, and then use the original numeric value to subset the original data frame.

Here is a solution that handles the additional requirement, using the sqldf package.

```<code># SQLDF solution
library(sqldf)
x <- data.frame(V1=c(rep(1,10),rep(2,8)),stringsAsFactors=FALSE)
sqlStmt <- "select V1, count(*) as count from x group by V1"
y <- sqldf(sqlStmt)

z <- y[y$count == max(y$count),1]
class(z)
</code>```

...and the output.

```<code>> z <- y[y$count == max(y$count),1]
> class(z)
[1] "numeric"
</code>```

Notice how the class of the final result is still numeric, rather than being converted to a factor or character value.

Title: How to Extract Value of Output in R?

Body:
How can you extract the index value of a result in R.

data.frame(sort(table(df$col1),decreasing=TRUE))

This results in an output of the col1 value and its count.
The output is the following:

          Var1   |    freq
   ---------------------------
    1     ABC    |      10
    2     DEF    |       9
   ...

I'm basically trying to extract 'ABC'.

UPDATED ANSWER:

The following options will output the greatest reoccuring value in a column (col1) while retaining the original datatype:

subset(df,!is.na(df$col1),) %>% count(col1) %>% arrange(desc(n)) %>% c(1)[1][[1]]
OR
data.frame(sort(table(df$col1),decreasing=TRUE))[1,1]
OR
sqldf("SELECT COUNT(*) as count, col1 FROM df WHERE col1 IS NOT NULL GROUP BY col1 ORDER BY count DESC")$col1[1]

Body:
Since the result of data.frame() is a data frame, one can immediately use the extract operator on it.

# generate the data
x <- c(rep("ABC",10),rep("DEF",9))

# extract string with highest frequency from table
data.frame(sort(table(x),decreasing=TRUE))[1,1]

... and the result:

> data.frame(sort(table(x),decreasing=TRUE))[1,1]
[1] ABC
Levels: ABC DEF
>

One can use as.character() to remove the factor levels from the result.

Based on the comments there is a need to obtain counts for numeric variables, and then use the original numeric value to subset the original data frame.

Here is a solution that handles the additional requirement, using the sqldf package.

# SQLDF solution
library(sqldf)
x <- data.frame(V1=c(rep(1,10),rep(2,8)),stringsAsFactors=FALSE)
sqlStmt <- "select V1, count(*) as count from x group by V1"
y <- sqldf(sqlStmt)

z <- y[y$count == max(y$count),1]
class(z)

...and the output.

> z <- y[y$count == max(y$count),1]
> class(z)
[1] "numeric"

Notice how the class of the final result is still numeric, rather than being converted to a factor or character value.


问:
jqGrid: is there an event for when columns are reordered?
I'm using the column reordering feature in jqGrid

```<code>$grid = jQuery("#list").jqGrid({
    sortable:true,
    ...
});
</code>```

Is there an event that fires after columns are re-ordered? If there is, I can't see it!

Thanks in advance

答:
There is a call in grid.jqueryui.js (jqGrid v3.8.2) in update() to ts.p.sortable.update() as discussed on the jqGrid message board, so:

```<code>jQuery('#gridId').jqGrid({
    ...,
    sortable: { update: function(permutation) {
        alert('save permutation somewhere');
    },
    ...
});
</code>```

However, please note that the array passed to your callback will be relative to the current column order. In other words, saving the array as is after moving multiple columns will not produce the desired results.

I had to do something like this:

```<code>var defaultColNames = [ 'Alpha', 'Beta', 'Gamma' ];
var defaultColModel = [
    { name: 'alpha', index: 'alpha' },
    { name: 'beta', index: 'beta' },
    { name: 'gamma', index: 'gamma' }
];

jQuery('#gridId').jqGrid({
    ...,
    colNames: defaultColNames,
    colModel: defaultColModel,
    sortable: { update: function(relativeColumnOrder) {
        var grid = jQuery('#gridId');

        var defaultColIndicies = [];
        for( var i=0; i<defaultColModel.length; i++ ) {
            defaultColIndicies.push(defaultColModel[i].name);
        }

        if( grid.getGridParam('treeGrid') ) {
            // tree grid mode adds 5 extra columns
            defaultColIndicies = defaultColIndicies.concat(['level','parent','isLeaf','expanded','loaded']);
        }

        var columnOrder = [];
        var currentColModel = grid.getGridParam('colModel');
        for( var j=0; j<relativeColumnOrder.length; j++ ) {
            columnOrder.push(defaultColIndicies.indexOf(currentColModel[j].name));
        }

        // columnOrder now contains exactly what's necessary to pass to to remapColumns
        // now save columnOrder somewhere
        globalColumnOrder = columnOrder;
    },
    ...
});

// grab saved column order from cookie or something
var globalColumnOrder = [0,1,2];

// append to array if tree grid enabled
if( jQuery('#gridId').getGridParam('treeGrid') ) {
    // tree grid mode adds 5 extra columns
    for( var k=defaultColNames.length; k<(defaultColNames.length+5); k++ ) {
        globalColumnOrder.push(k);
    }
}

// restore column order
jQuery('#gridId').jqGrid('remapColumns', globalColumnOrder, true, false);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm using the column reordering feature in jqGrid

$grid = jQuery("#list").jqGrid({
    sortable:true,
    ...
});

Is there an event that fires after columns are re-ordered? If there is, I can't see it!

Thanks in advance

Body:
There is a call in grid.jqueryui.js (jqGrid v3.8.2) in update() to ts.p.sortable.update() as discussed on the jqGrid message board, so:

jQuery('#gridId').jqGrid({
    ...,
    sortable: { update: function(permutation) {
        alert('save permutation somewhere');
    },
    ...
});

However, please note that the array passed to your callback will be relative to the current column order. In other words, saving the array as is after moving multiple columns will not produce the desired results.

I had to do something like this:

var defaultColNames = [ 'Alpha', 'Beta', 'Gamma' ];
var defaultColModel = [
    { name: 'alpha', index: 'alpha' },
    { name: 'beta', index: 'beta' },
    { name: 'gamma', index: 'gamma' }
];

jQuery('#gridId').jqGrid({
    ...,
    colNames: defaultColNames,
    colModel: defaultColModel,
    sortable: { update: function(relativeColumnOrder) {
        var grid = jQuery('#gridId');

        var defaultColIndicies = [];
        for( var i=0; i<defaultColModel.length; i++ ) {
            defaultColIndicies.push(defaultColModel[i].name);
        }

        if( grid.getGridParam('treeGrid') ) {
            // tree grid mode adds 5 extra columns
            defaultColIndicies = defaultColIndicies.concat(['level','parent','isLeaf','expanded','loaded']);
        }

        var columnOrder = [];
        var currentColModel = grid.getGridParam('colModel');
        for( var j=0; j<relativeColumnOrder.length; j++ ) {
            columnOrder.push(defaultColIndicies.indexOf(currentColModel[j].name));
        }

        // columnOrder now contains exactly what's necessary to pass to to remapColumns
        // now save columnOrder somewhere
        globalColumnOrder = columnOrder;
    },
    ...
});

// grab saved column order from cookie or something
var globalColumnOrder = [0,1,2];

// append to array if tree grid enabled
if( jQuery('#gridId').getGridParam('treeGrid') ) {
    // tree grid mode adds 5 extra columns
    for( var k=defaultColNames.length; k<(defaultColNames.length+5); k++ ) {
        globalColumnOrder.push(k);
    }
}

// restore column order
jQuery('#gridId').jqGrid('remapColumns', globalColumnOrder, true, false);


问:
How to pass variable to dynamic SQL statement's SELECT list within a DB2 stored procedure?
I created DB2-400 stored procedure with a declared variables EFFDT Varchar(10). The value for this variable is supposed to be passed to a SQL statement within the same stored procedure.  The procedure compiles fine, but when I execute the procedure, I get

SQL-0206 error "Column or global variable @EFFDT not found".

Here is the code:

```<code>BEGIN
-- Variable used to replace effective in SQL below with 1st
-- day of current month as text in 'MM/DD/YYYY' format

DECLARE     EFFDT VARCHAR(10);

SET EFFDT = VARCHAR_FORMAT(MONTH(CURRENT DATE) || '/01/' || YEAR(CURRENT DATE),'MM/DD/YYYY') ;  -- First day of current month

    ...

--SQL STATEMENT
CREATE TABLE INFOMATICS.TEMP_CHGS_2_ADDS AS
  (SELECT FNAME, MI, LNAME, MAILING_ZIP,
          SPECLTY, SPECLTY_DESC, @EFFDT AS EFF_DATE
     FROM INFOMATICS.TEMP_CHGS) WITH DATA;

    ...
End;
</code>```

I expect to see

```<code>John M Smith 1111 GD General Dentist 05/01/2019
</code>```

答:
I ended up not using the variable. Instead I wrote an SQL UPDATE statement to modify the effective date (EFF_DATE) to the 1st day of the current month.  Here’s the SQL UPDATE statement:
UPDATE INFOMATICS.TEMP_CHGS SET EFF_DATE = VARCHAR_FORMAT(MONTH(CURRENT DATE) || ‘/01/‘ || YEAR(CURRENT DATE),’MM/DD/YYYY’);

The EFF_DATE value returned was as expected ‘05/01/2019’.

Body:
I created DB2-400 stored procedure with a declared variables EFFDT Varchar(10). The value for this variable is supposed to be passed to a SQL statement within the same stored procedure.  The procedure compiles fine, but when I execute the procedure, I get

SQL-0206 error "Column or global variable @EFFDT not found".

Here is the code:

BEGIN
-- Variable used to replace effective in SQL below with 1st
-- day of current month as text in 'MM/DD/YYYY' format

DECLARE     EFFDT VARCHAR(10);

SET EFFDT = VARCHAR_FORMAT(MONTH(CURRENT DATE) || '/01/' || YEAR(CURRENT DATE),'MM/DD/YYYY') ;  -- First day of current month

    ...

--SQL STATEMENT
CREATE TABLE INFOMATICS.TEMP_CHGS_2_ADDS AS
  (SELECT FNAME, MI, LNAME, MAILING_ZIP,
          SPECLTY, SPECLTY_DESC, @EFFDT AS EFF_DATE
     FROM INFOMATICS.TEMP_CHGS) WITH DATA;

    ...
End;

I expect to see

John M Smith 1111 GD General Dentist 05/01/2019


问:
How to override a constructor?
In my code I want to create a class called programmer which extends from the employee class.

The employee class constructor should take 4 parameters, and the programmer class constructor should take 5 parameters, 4 from the employee class and the other one from programmer class.

How can I do this?

```<code>class employee {

     private id: string;
     private name: string;
     private department: string;
     private salary: number;

    constructor(id: string , name: string , department: string , salary: number) {

        this.id = id;
        this.name = name;
        this.department = department;
        this.salary = salary;

    }

    speak() {
        console.log(`ID = ${this.id} , Name = ${this.name} , Department = ${this.department} , Salary = ${this.salary}`);
    }
}

class programmer extends employee {

    private programmingLang: string;

    constructor() {
        super();
    }

    speak() {
        super.speak() , console.log(` , Programming Language = ${this.programmingLang}`);
    }
}
</code>```

答:
i think your child class constructor should look like this.

```<code>Constructor(id: string , name: string , department: string , salary:
number,programmingLang: string) {
super(id,name,department,salary);
this.programmingLang = programmingLang;
}
</code>```

child class has all the properties of it's parent and also has it's specific properties such that child class constructor must take all these properties as parameter and call parent class constructor with those properties it inherts as argument and also initialize it's specific properties using this keyword.

I am not java script programmer but this is how inheritence works generaly in all OOP supported languages. Hope it helps.

Title: How to override a constructor?

Body:
In my code I want to create a class called programmer which extends from the employee class.

The employee class constructor should take 4 parameters, and the programmer class constructor should take 5 parameters, 4 from the employee class and the other one from programmer class.

How can I do this?

class employee {

     private id: string;
     private name: string;
     private department: string;
     private salary: number;

    constructor(id: string , name: string , department: string , salary: number) {

        this.id = id;
        this.name = name;
        this.department = department;
        this.salary = salary;

    }

    speak() {
        console.log(`ID = ${this.id} , Name = ${this.name} , Department = ${this.department} , Salary = ${this.salary}`);
    }
}

class programmer extends employee {

    private programmingLang: string;

    constructor() {
        super();
    }

    speak() {
        super.speak() , console.log(` , Programming Language = ${this.programmingLang}`);
    }
}

Body:
i think your child class constructor should look like this.

Constructor(id: string , name: string , department: string , salary:
number,programmingLang: string) {
super(id,name,department,salary);
this.programmingLang = programmingLang;
}

child class has all the properties of it's parent and also has it's specific properties such that child class constructor must take all these properties as parameter and call parent class constructor with those properties it inherts as argument and also initialize it's specific properties using this keyword.

I am not java script programmer but this is how inheritence works generaly in all OOP supported languages. Hope it helps.


问:
owl-carousel - How to Slide By to 3rd slide using every next dot - .owl-dot:Active
I want to slide by 3 so I used slideby:3 but it is sliding in Auto mode only.
When I am clicking sequentially one by one every dot (owl-dot) it is sliding by 1 slid instead of 3. So what property I can add in jquery or my style.css so that in both Autoplay and manual click on dot slide move with the same number of slides (3 slides).

Here is my: jquery

```<code>Doller sign used ('.owl-carousel').owlCarousel({

items:4,
margin:40,
loop:true,

nav:true,`enter code here`
navSpeed:200,

dots:true,
dotsEach:true,

autoplay:true,
autoplaySpeed: 200,

slideBy:3,
})
</code>```

I am looking step by on dot, something like :

```<code>.owl-dot:Active {
slideBy:3;
}
</code>```

I know that the above code won't work but just to express my question clearly I am giving an idea if there is there any property which I can write either in jquery or style.css. or (maybe click every may work for my situation but it is complex for me to understand and associate that code, I am new in jquery)
It is very complex and not at all able to understand :

```<code>Doller sign used ('.own-carousel .dot').hover(function() {
        $(this).click();
        }, function() {});
</code>```

Note : here what code I can write to perform slideBy:3 actions on click on a dot

One more thing I am looking at that is the number of dots under my slides. for example, I have 7 slides and I am stepping by 2 slides to land on 3rd slide but I want 6 dots so even after 2nd dot all slides have been scrolled (as at a time display is "items:4" /slide/one cycle) still from 3rd dot it starts as a loop constant (continue motion in one direction) rather (first reverse all and then start)

I am unable to find on the internet and carousel doc that is why I am posting here, so I need help in my code to achieve this functionality. (I saw same dot stepping by behavior on many websites) I also did chrome-->inspect feature to find what property other websites are using but unable to figure it out.

Note : I used Doller sign before every jquery as while posting this query I am unable to post when using a symbol of doller.

答: It looks like you want to set the dotsEach option to 3.</p>

Body:
I want to slide by 3 so I used slideby:3 but it is sliding in Auto mode only.
When I am clicking sequentially one by one every dot (owl-dot) it is sliding by 1 slid instead of 3. So what property I can add in jquery or my style.css so that in both Autoplay and manual click on dot slide move with the same number of slides (3 slides).

Here is my: jquery

Doller sign used ('.owl-carousel').owlCarousel({

items:4,
margin:40,
loop:true,

nav:true,`enter code here`
navSpeed:200,

dots:true,
dotsEach:true,

autoplay:true,
autoplaySpeed: 200,

slideBy:3,
})

I am looking step by on dot, something like :

.owl-dot:Active {
slideBy:3;
}

I know that the above code won't work but just to express my question clearly I am giving an idea if there is there any property which I can write either in jquery or style.css. or (maybe click every may work for my situation but it is complex for me to understand and associate that code, I am new in jquery)
It is very complex and not at all able to understand :

Doller sign used ('.own-carousel .dot').hover(function() {
        $(this).click();
        }, function() {});

Note : here what code I can write to perform slideBy:3 actions on click on a dot

One more thing I am looking at that is the number of dots under my slides. for example, I have 7 slides and I am stepping by 2 slides to land on 3rd slide but I want 6 dots so even after 2nd dot all slides have been scrolled (as at a time display is "items:4" /slide/one cycle) still from 3rd dot it starts as a loop constant (continue motion in one direction) rather (first reverse all and then start)

I am unable to find on the internet and carousel doc that is why I am posting here, so I need help in my code to achieve this functionality. (I saw same dot stepping by behavior on many websites) I also did chrome-->inspect feature to find what property other websites are using but unable to figure it out.

Note : I used Doller sign before every jquery as while posting this query I am unable to post when using a symbol of doller.


问:
Use AWS Amplify and App Sync with existing Node Server using Mongodb
Currently, I'm developing a native application using React-Native. I've decided to go with AWS Amplify because of it's real time updates as well as its authentication.

I also have a Web Application that runs on a Node.js with Epxress server. This web application connects to a Mongo database.

My big problem is that I would like to have all of my aws amplify queries run to my existing MongoDb instead of a new dynamoDb database which is provided with AWS AppSync, but unfortunately I dont know where to start. This is especially helpful in adding authentication easily in my existing web application as well.

My first idea was to just create all my API endpoints in a new node js server and have app sync call to these API end points, but I'm not sure how to implement calling end points on an existing server (and this seems kind of counter intuitive to the 'serverless' idea)

My other idea came from this: Can AWS App-Sync be used without dynamoDB

This states to use AWS Lambda to 'pipeline' my data to the existing mongodb, but I'm not really sure what that entails.

TL;DR - I would like to be able to query an existing Mongodb instead of using DynamoDb when using AWS Amplify with AppSync.

I hope this is clear enough and doesn't sound like I'm rambling. Thanks in advance!

答:
I would suggest using either an HTTP datasource to connect to your MongoDB backend or a Lambda function. Here are a couple getting started tutorials for both:

https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-http-resolvers.html
https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-lambda-resolvers.html

If you go the Lambda route, then you can leverage the new @function feature of the GraphQL Transformer in the Amplify CLI: https://aws-amplify.github.io/docs/cli/graphql#function


问:
pyenv failed to download a existing version of Python
I recently installed pyenv and attempted to install a version of python, according to a blog post.  I ran some commands, but encountered an error and I am uncertain how to resolve.</p>

```<code>$ pyenv install 3.6.6
python-build: use openssl from homebrew
python-build: use readline from homebrew
Downloading Python-3.6.6.tar.xz...
-> https://www.python.org/ftp/python/3.6.6/Python-3.6.6.tar.xz
error: failed to download Python-3.6.6.tar.xz

BUILD FAILED (OS X 10.12.6 using python-build 20180424)
</code>```

答: appears to have been a network error for me - switched to a faster network after confirming file was still available and it installed without problems</p>

Body:
I recently installed pyenv and attempted to install a version of python, according to a blog post.  I ran some commands, but encountered an error and I am uncertain how to resolve.

$ pyenv install 3.6.6
python-build: use openssl from homebrew
python-build: use readline from homebrew
Downloading Python-3.6.6.tar.xz...
-> https://www.python.org/ftp/python/3.6.6/Python-3.6.6.tar.xz
error: failed to download Python-3.6.6.tar.xz

BUILD FAILED (OS X 10.12.6 using python-build 20180424)


问:
Installation of Tensorflow on aarch64: Error: Could not find a version that satisfies the requirement tensorflow
I would like to install Tensorflow on aarch64 (Ubuntu 16.04; Linux on DeX).

Attempt 1: Following the same procedure as on a classical x86_64 architecture (works there); see here

```<code>sudo apt update
sudo apt install python3-dev python3-pip virtualenv # the latter was required under aarch64, not under x86_64
sudo -H pip3 install --upgrade virtualenv
mkdir /usr/local/tensorflow
virtualenv --system-site-packages -p python3 /usr/local/tensorflow
source /usr/local/tensorflow/bin/activate
pip3 install --upgrade tensorflow # fails with 'Error: Could not find a version that satisfies the requirement tensorflow (from versions: none)' and 'Error: No matching distribution found for tensorflow'
</code>```

A related posts to Attempt 1 but for Windows is this here. One also finds other posts (similar title) but none seems to address ARM architecture.

Attempt 2: Following these instructions

```<code>sudo apt update
sudo apt install python3-dev python3-pip
mkdir /usr/local/tensorflow
cd /usr/local/tensorflow
wget https://github.com/lhelontra/tensorflow-on-arm/releases/download/v1.8.0/tensorflow-1.8.0-cp35-none-linux_aarch64.whl
sudo -H pip3 install tensorflow-1.8.0-cp35-none-linux_aarch64.whl
# => reports 'Failed building wheel for ...'. Still seems to somehow progress
#    but then 'import tensorflow as tf' in a Python 3.5.2 session produces a lot
#    of traceback output and essentially shows that the installation did not work.
</code>```

In a third attempt, I tried to follow these instructions but
couldn't install Bazel as Step 2 from here failed because there is no aarch64 version (even if one downloads the .tar.gz, compilation fails with ERROR: Must specify PROTOC if not bootstrapping from the distribution artifact...

More info: python --version shows 2.7.12 and python3 --version shows 3.5.2

Update

I tried hoefling's suggestion for Attempt 1. Running pip3 install tensorflow --extra-index-url=https://www.piwheels.org/simple right before pip3 install --upgrade tensorflow made the latter work without obvious errors, but starting python3 and using import tensorflow as tf I still obtain a large traceback output:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/usr/lib/python3.5/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/usr/lib/python3.5/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: /usr/lib/aarch64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.22' not found (required by /usr/local/lib/python3.5/dist-packages/tensorflow/python/_pywrap_tensorflow_internal.so)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/usr/lib/python3.5/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/usr/lib/python3.5/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: /usr/lib/aarch64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.22' not found (required by /usr/local/lib/python3.5/dist-packages/tensorflow/python/_pywrap_tensorflow_internal.so)

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
</code>```

答:
I found the issue on https://github.com/lhelontra/tensorflow-on-arm/issues/13. In short, I was missing certain preliminaries under aarch64. Here is the solution:

```<code># Preliminaries
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt update
sudo apt install gcc-4.9
sudo apt install --only-upgrade libstdc++6

# Installation similar to Ubuntu on x86_64
sudo apt update
sudo apt install python3-dev python3-pip virtualenv
sudo -H pip3 install --upgrade virtualenv
mkdir /usr/local/tensorflow
virtualenv --system-site-packages -p python3 /usr/local/tensorflow/
source /usr/local/tensorflow/bin/activate
pip3 install --upgrade tensorflow
deactivate

# Test
source /usr/local/tensorflow/bin/activate
$ python3
>>> import tensorflow as tf
>>> hello = tf.constant("Hello, World!")
>>> sess = tf.Session()
>>> print(sess.run(hello))
</code>```

Body:
I would like to install Tensorflow on aarch64 (Ubuntu 16.04; Linux on DeX).

Attempt 1: Following the same procedure as on a classical x86_64 architecture (works there); see here

sudo apt update
sudo apt install python3-dev python3-pip virtualenv # the latter was required under aarch64, not under x86_64
sudo -H pip3 install --upgrade virtualenv
mkdir /usr/local/tensorflow
virtualenv --system-site-packages -p python3 /usr/local/tensorflow
source /usr/local/tensorflow/bin/activate
pip3 install --upgrade tensorflow # fails with 'Error: Could not find a version that satisfies the requirement tensorflow (from versions: none)' and 'Error: No matching distribution found for tensorflow'

A related posts to Attempt 1 but for Windows is this here. One also finds other posts (similar title) but none seems to address ARM architecture.

Attempt 2: Following these instructions

sudo apt update
sudo apt install python3-dev python3-pip
mkdir /usr/local/tensorflow
cd /usr/local/tensorflow
wget https://github.com/lhelontra/tensorflow-on-arm/releases/download/v1.8.0/tensorflow-1.8.0-cp35-none-linux_aarch64.whl
sudo -H pip3 install tensorflow-1.8.0-cp35-none-linux_aarch64.whl
# => reports 'Failed building wheel for ...'. Still seems to somehow progress
#    but then 'import tensorflow as tf' in a Python 3.5.2 session produces a lot
#    of traceback output and essentially shows that the installation did not work.

In a third attempt, I tried to follow these instructions but
couldn't install Bazel as Step 2 from here failed because there is no aarch64 version (even if one downloads the .tar.gz, compilation fails with ERROR: Must specify PROTOC if not bootstrapping from the distribution artifact...

More info: python --version shows 2.7.12 and python3 --version shows 3.5.2

Update

I tried hoefling's suggestion for Attempt 1. Running pip3 install tensorflow --extra-index-url=https://www.piwheels.org/simple right before pip3 install --upgrade tensorflow made the latter work without obvious errors, but starting python3 and using import tensorflow as tf I still obtain a large traceback output:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/usr/lib/python3.5/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/usr/lib/python3.5/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: /usr/lib/aarch64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.22' not found (required by /usr/local/lib/python3.5/dist-packages/tensorflow/python/_pywrap_tensorflow_internal.so)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/usr/lib/python3.5/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/usr/lib/python3.5/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: /usr/lib/aarch64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.22' not found (required by /usr/local/lib/python3.5/dist-packages/tensorflow/python/_pywrap_tensorflow_internal.so)

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

Body:
I found the issue on https://github.com/lhelontra/tensorflow-on-arm/issues/13. In short, I was missing certain preliminaries under aarch64. Here is the solution:

# Preliminaries
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt update
sudo apt install gcc-4.9
sudo apt install --only-upgrade libstdc++6

# Installation similar to Ubuntu on x86_64
sudo apt update
sudo apt install python3-dev python3-pip virtualenv
sudo -H pip3 install --upgrade virtualenv
mkdir /usr/local/tensorflow
virtualenv --system-site-packages -p python3 /usr/local/tensorflow/
source /usr/local/tensorflow/bin/activate
pip3 install --upgrade tensorflow
deactivate

# Test
source /usr/local/tensorflow/bin/activate
$ python3
>>> import tensorflow as tf
>>> hello = tf.constant("Hello, World!")
>>> sess = tf.Session()
>>> print(sess.run(hello))


问:
Difference Between Cognito User Pool and API Key For API Auth Type
I'm currently setting up AWS Amplify with my react app and adding an API so I can use GraphQL.
I'm currently at a choice to add authorization type and my two options are API key or Amazon cognito user pool.
It's my understanding that the second choice means if a user is signed in, they can interact with the API calls.
What does the first choice (API key) mean?
What is the difference?</p>

答: API key is basically for unauthenticated workflows where the app doesn't need private access for different users. User Pools allows you to apply fine grained access controls. Take a look at the options with @auth in the GraphQL Transformer: https://aws-amplify.github.io/docs/cli/graphql#auth</p>


Title: Trying to change column header names in matrix but getting something strange (in R)

Body:
I have a matrix (which I have called "y") with 30 rows and 4 columns. Right now, the column names are NULL. I am trying to change the individual column names, but it is not quite working.

I have tried renaming each column individually (after creating the matrix, that is, please see below).

y <- t(replicate(30, diff(c(0, sort(runif(3)), 100))))
names(y)[1] <- "very small"
names(y)[2] <- "small"
names(y)[3] <- "medium"
names(y)[4] <- "large"

Here is my matrix, but the headers did not work:

         [,1]       [,2]       [,3]     [,4]
[1,] 0.160791460 0.19036607 0.12580291 99.52304
[2,] 0.494404672 0.37335411 0.12121969 99.01102
[3,] 0.322312759 0.07680743 0.13229986 99.46858
[4,] 0.320615717 0.02913797 0.48735808 99.16289
[5,] 0.250489308 0.20835271 0.49417666 99.04698
[6,] 0.065639576 0.62845967 0.11742292 99.18848
[7,] 0.318023945 0.09396768 0.25217427 99.33583
[8,] 0.109697064 0.26258440 0.43483501 99.19288
[9,] 0.438948497 0.23642842 0.31614101 99.00848
[10,] 0.061270783 0.44413492 0.05874163 99.43585
[11,] 0.587190304 0.07693372 0.07609361 99.25978
[12,] 0.097498817 0.05573392 0.34773439 99.49903
[13,] 0.418862582 0.04924732 0.25642872 99.27546
[14,] 0.313116374 0.02291056 0.43163056 99.23234
[15,] 0.167363657 0.28980591 0.10015846 99.44267
[16,] 0.003417506 0.38710120 0.34930292 99.26018
[17,] 0.232000787 0.30794160 0.06402202 99.39604
[18,] 0.233561779 0.35227333 0.36642543 99.04774
[19,] 0.396694646 0.11903936 0.41165674 99.07261
[20,] 0.147861399 0.13515116 0.59463398 99.12235
[21,] 0.469082454 0.03757156 0.29131755 99.20203
[22,] 0.008113136 0.53687528 0.35030648 99.10471
[23,] 0.097810979 0.24581902 0.07533917 99.58103
[24,] 0.666495166 0.09177066 0.20840372 99.03333
[25,] 0.198825197 0.03246302 0.14705370 99.62166
[26,] 0.460175968 0.17809558 0.34293910 99.01879
[27,] 0.349538516 0.50323914 0.13838036 99.00884
[28,] 0.498382490 0.18309442 0.17280276 99.14572
[29,] 0.817413253 0.08962883 0.02642045 99.06654
[30,] 0.139955595 0.30773060 0.22649081 99.32582

Instead, directly under my matrix, I get something like this:

attr(,"names")
[1] "very small" "small"      "medium"     "large"      NA           NA
NA           NA           NA           NA
[11] NA           NA           NA           NA           NA           NA
NA           NA           NA           NA
[21] NA           NA           NA           NA           NA           NA
NA           NA           NA           NA
[31] NA           NA           NA           NA           NA           NA
NA           NA           NA           NA
[41] NA           NA           NA           NA           NA           NA
NA           NA           NA           NA
[51] NA           NA           NA           NA           NA           NA
NA           NA           NA           NA
[61] NA           NA           NA           NA           NA           NA
NA           NA           NA           NA
[71] NA           NA           NA           NA           NA           NA
NA           NA           NA           NA
[81] NA           NA           NA           NA           NA           NA
NA           NA           NA           NA
[91] NA           NA           NA           NA           NA           NA
NA           NA           NA           NA
[101] NA           NA           NA           NA           NA           NA
NA           NA           NA           NA
[111] NA           NA           NA           NA           NA           NA
NA           NA           NA           NA

Any help would be appreicated. Thanks.

Body:
Try using colnames

y <- t(replicate(30, diff(c(0, sort(runif(3)), 100))))
colnames(y) <- c("very small", "small", "medium", "large")

Which gives the following output:

       very small       small     medium    large
 [1,] 0.596546432 0.115485521 0.09401027 99.19396
 [2,] 0.118521670 0.694866442 0.16535686 99.02126
 [3,] 0.421295392 0.002795051 0.03821284 99.53770
 [4,] 0.202813028 0.269167296 0.21997193 99.30805
 [5,] 0.008274178 0.222862752 0.56131816 99.20754
 [6,] 0.031685216 0.303549471 0.04934352 99.61542
 [7,] 0.319768410 0.022998874 0.25970746 99.39753
 [8,] 0.087382152 0.609509549 0.09651936 99.20659
 [9,] 0.773647428 0.086955708 0.02798129 99.11142
[10,] 0.331411455 0.368387836 0.13918296 99.16102
[11,] 0.131787972 0.463235363 0.22744175 99.17753
[12,] 0.293173234 0.345394548 0.23810145 99.12333
[13,] 0.153707973 0.074851698 0.44902831 99.32241
[14,] 0.153896874 0.017483677 0.05351859 99.77510
[15,] 0.182090415 0.502133689 0.29637249 99.01940
[16,] 0.413675049 0.082363683 0.26351923 99.24044
[17,] 0.006476240 0.001355163 0.39702371 99.59514
[18,] 0.558440146 0.177935100 0.13974163 99.12388
[19,] 0.066856618 0.095454829 0.22950901 99.60818
[20,] 0.050508366 0.202233682 0.41133537 99.33592
[21,] 0.152118187 0.373801691 0.01678485 99.45730
[22,] 0.545999638 0.070524028 0.03855460 99.34492
[23,] 0.216591213 0.171351144 0.41215730 99.19990
[24,] 0.214317867 0.388471707 0.24408460 99.15313
[25,] 0.134022010 0.380754224 0.29407828 99.19115
[26,] 0.071872900 0.127088718 0.39654603 99.40449
[27,] 0.105251258 0.554369684 0.23365911 99.10672
[28,] 0.233648165 0.224023261 0.19177330 99.35056
[29,] 0.649248827 0.139018328 0.14818464 99.06355
[30,] 0.090693591 0.034686614 0.10709328 99.76753

Why do names and colnames behave differently here?

names in this context tries to assign a name to each item within the matrix, rather than each column (as you would find with a dataframe). This is because names assigns a name to each element of the object i.e. as many names as the length of the matrix, in this case 120.

Dataframes, however, are in fact stored as lists, where each element of the list represents a column. Therefore, a similar dataframe would have length of 4, and names would just try to assign 4 names, one per column.

colnames, however assigns as many names as the length of the second dimension i.e. the number of columns. Since dim(y) gives 30 4 whether y is a matrix or a dataframe, either way it'll assign 4 names, one per column.


问:
How do use Javascript Async-Await as an alternative to polling for a statechange?
I'd like to accomplish the following using promises: only execute further once the state of something is ready. I.e. like polling for an external state-change.

I've tried using promises and async-await but am not getting the desired outcome. What am I doing wrong here, and how do I fix it?

The MDN docs have something similar but their settimeout is called within the promise--that's not exactly what I'm looking for though.

I expect the console.log to show "This function is now good to go!" after 5 seconds, but instead execution seems to stop after calling await promiseForState();

var state = false;

function stateReady (){
 state = true;
}

function promiseForState(){
 var msg = "good to go!";
 var promise = new Promise(function (resolve,reject){
        if (state){
            resolve(msg);
        }
    });

  return promise;
}

async function waiting (intro){

    var result = await promiseForState();
    console.log(intro + result)

}
setTimeout(stateReady,5000);
waiting("This function is now ");```

答:
The way I would solve this, is as follows. I am not 100% certain this solves your problem, but the assumption here is that you have control over stateReady().

```<code>let state = false;
let stateResolver;

const statePromise = new Promise( (res, rej) => {

  stateResolver = res;

});

function stateReady(){
 state = true;
 stateResolver();
}

async function promiseForState(){
   await stateResolver();
   const msg = "good to go!";
   return msg;
}

async function waiting (intro){

    const result = await promiseForState();
    console.log(intro + result)

}
setTimeout(stateReady,5000);
waiting("This function is now ");
</code>```

Some key points:

The way this is written currently is that the 'state' can only transition to true once. If you want to allow this to be fired many times, some of those const will need to be let and the promise needs to be re-created.

I created the promise once, globally and always return the same one because it's really just one event that every caller subscribes to.

I needed a stateResolver variable to lift the res argument out of the promise constructor into the global scope.

Body:
The way I would solve this, is as follows. I am not 100% certain this solves your problem, but the assumption here is that you have control over stateReady().

let state = false;
let stateResolver;

const statePromise = new Promise( (res, rej) => {

  stateResolver = res;

});

function stateReady(){
 state = true;
 stateResolver();
}

async function promiseForState(){
   await stateResolver();
   const msg = "good to go!";
   return msg;
}

async function waiting (intro){

    const result = await promiseForState();
    console.log(intro + result)

}
setTimeout(stateReady,5000);
waiting("This function is now ");

Some key points:

The way this is written currently is that the 'state' can only transition to true once. If you want to allow this to be fired many times, some of those const will need to be let and the promise needs to be re-created.

I created the promise once, globally and always return the same one because it's really just one event that every caller subscribes to.

I needed a stateResolver variable to lift the res argument out of the promise constructor into the global scope.


问:
Using gitignore to separate development and production environments
So I'm working on learning python with the discord.py library and playing with bots. The bots require an API token, and I would like to separate the functional bot on the server, from the test bot I'm working on.

My environment would be set up with a master branch, and a dev branch. I'd like the master branch's code base to work with Test Bot, and the development branch's code base to work with Test Bot Dev. My idea was to have an API Token variable stored in an untracked file, and place that file on the server. Then have a local file on my PC that has the same file, but with a different token set as the variable.

It feels a little bit hacky though. I'm just wondering if there is a better standard practice for situations where you want to use one repository for your code base, but need to have a specific variable differ for your dev and prod environments. It's sort of a convoluted question, so I'm struggling to have much success in finding suggestions for this situation through searches.

答:
Put the application with a the required profile under configuration management (git) and ignore any (local) overriding file.

For example, put a file named .env.dist under version control, while the file .env is in the .gitignore file of the same project (in that same path):

```<code># dot env
/.env
</code>```

Make your utility/bot load any .env.dist file by default and .env file overriding that .env.dist file. This allows you to document, plan and define required environment variables while allowing a user to keep a local copy with all the production credentials (if needed).

Then give your bot another parameter to load a different name environment (dot env) file taking the lead. This allows you to run the bot with any different configuration.

If you follow the syntax of environment files as used by the Docker CLI utility, you are most likely pretty inter-operable and can reach far by so w/o giving up much of your freedoms.

So take this as a suggestion.

Another one: If you would like to use diff-utilities to quickly compare between environment files, one tip I can provide is that if you create sections (as otherwise you should order the environment parameter (variable) names by name), give each section a header with (if not on top of the file) an empty line, a singe # comment, another comment with the section name # name of section and another single # line. This gives text-base diff tools enough food to keep sections apart of each other (and apart from other single-line comments).

```<code>#
# DISCORD API
#
DISCORD_ID
DISCORD_KEY

#
# MYSQL DATABASE
#
MYSQL_HOST
MYSQL_PASS
MYSQL_PORT
MYSQL_USER
</code>```

(exemplary .env.dist file hinting required parameter while not providing any secrets)

```<code>#
# DISCORD API
#
DISCORD_ID=42
DISCORD_KEY=aefdcd8d71d200efaefdcd8d71d200ef

#
# MYSQL DATABASE
#
MYSQL_HOST=example.com
MYSQL_PASS=root
MYSQL_PORT=34732
MYSQL_USER=root
</code>```

(exemplary .env file containing secrets and excluded (do not add!) via .gitinore in the git project directly).

Add more "dot env" files into .git/info/exclude and/or if you adopt this pattern to your whole development system into your global .gitignore. Read the description in the Git gignore Documentation how the (multilevel) gitignore is used and when it does not ignore any of the files even if specified.

Body:
Put the application with a the required profile under configuration management (git) and ignore any (local) overriding file.

For example, put a file named .env.dist under version control, while the file .env is in the .gitignore file of the same project (in that same path):

# dot env
/.env

Make your utility/bot load any .env.dist file by default and .env file overriding that .env.dist file. This allows you to document, plan and define required environment variables while allowing a user to keep a local copy with all the production credentials (if needed).

Then give your bot another parameter to load a different name environment (dot env) file taking the lead. This allows you to run the bot with any different configuration.

If you follow the syntax of environment files as used by the Docker CLI utility, you are most likely pretty inter-operable and can reach far by so w/o giving up much of your freedoms.

So take this as a suggestion.

Another one: If you would like to use diff-utilities to quickly compare between environment files, one tip I can provide is that if you create sections (as otherwise you should order the environment parameter (variable) names by name), give each section a header with (if not on top of the file) an empty line, a singe # comment, another comment with the section name # name of section and another single # line. This gives text-base diff tools enough food to keep sections apart of each other (and apart from other single-line comments).

#
# DISCORD API
#
DISCORD_ID
DISCORD_KEY

#
# MYSQL DATABASE
#
MYSQL_HOST
MYSQL_PASS
MYSQL_PORT
MYSQL_USER

(exemplary .env.dist file hinting required parameter while not providing any secrets)

#
# DISCORD API
#
DISCORD_ID=42
DISCORD_KEY=aefdcd8d71d200efaefdcd8d71d200ef

#
# MYSQL DATABASE
#
MYSQL_HOST=example.com
MYSQL_PASS=root
MYSQL_PORT=34732
MYSQL_USER=root

(exemplary .env file containing secrets and excluded (do not add!) via .gitinore in the git project directly).

Add more "dot env" files into .git/info/exclude and/or if you adopt this pattern to your whole development system into your global .gitignore. Read the description in the Git gignore Documentation how the (multilevel) gitignore is used and when it does not ignore any of the files even if specified.


问:
What is the correct way of interop'ing with C flexible array members from C++?
I know that flexible array member is not part of the C++11 standard.

So what is the correct way of interoperating with C code that return, or accept as argument, structs with flexible array member, from C++11?

Should I write a shim that maps the flexible array member from the C struct to a pointer in C++?

答:
There's a trick used by Windows by setting the flexible array member to have size 1 (because the Win32 API has been developed long before the feature ever went into C99, let alone C++)

```<code>struct foo {
    int count;
    my_type fam[1];
};
</code>```

If you're allowed to change the C version then use the same struct in both C and C++. In case you can't change the C version then you'll need to redefine the struct in C++. You still have to change the C++ code when the C struct was modified, but at least it'll compile fine

See also

Are flexible array members valid in C++?

Why do some structures end with an array of size 1?

Body:
There's a trick used by Windows by setting the flexible array member to have size 1 (because the Win32 API has been developed long before the feature ever went into C99, let alone C++)

struct foo {
    int count;
    my_type fam[1];
};

If you're allowed to change the C version then use the same struct in both C and C++. In case you can't change the C version then you'll need to redefine the struct in C++. You still have to change the C++ code when the C struct was modified, but at least it'll compile fine

See also

Are flexible array members valid in C++?

Why do some structures end with an array of size 1?


问:
Paste String Indexing For Vector
This is my example code attempt

```<code>  paste(1:2,"x",0:1)
</code>```

This is the output

```<code>[1] "1x0" "2x1"
</code>```

But this is my Desired output:

```<code>[1] "1x0" "1x1" "2x0" "2x1"
</code>```

答:
Using expand.grid

```<code>apply(expand.grid(1:2,"x",0:1),1,paste,collapse="")
[1] "1x0" "2x0" "1x1" "2x1"
</code>```

Title: Paste String Indexing For Vector

Body:
This is my example code attempt

  paste(1:2,"x",0:1)

This is the output

[1] "1x0" "2x1"

But this is my Desired output:

[1] "1x0" "1x1" "2x0" "2x1"

Body:
Using expand.grid

apply(expand.grid(1:2,"x",0:1),1,paste,collapse="")
[1] "1x0" "2x0" "1x1" "2x1"


问:
How can I isolate the username of an email address using JavaScript?
I have an email list, but in order to assign the username to a new variable, I need to delete all the characters after the @ symbol.
Is there a way to do this via regex in javascript?</p>

```<code>var input = "john@email.com" //this is my input
var result = "john" //this is what I need after stripping all characters after the @ symbol

function strip(input){
this.result =  //how can I strip everything after the @ ??
}
</code>```

答:
You can split() the string by @ and get the first element.

var input = "john@email.com";
let res =input.split('@')[0]
console.log(res)```

Body:
I have an email list, but in order to assign the username to a new variable, I need to delete all the characters after the @ symbol.
Is there a way to do this via regex in javascript?

var input = "john@email.com" //this is my input
var result = "john" //this is what I need after stripping all characters after the @ symbol

function strip(input){
this.result =  //how can I strip everything after the @ ??
}


问:
How can I display a TextView in the ListView formatted like this "12:30 PM"?
I want to convert that string to DateFormat. In my ListView appears a little bit strange.

Here is the code

        String nameb= jo.getString("name");
        String dateb= jo.getString("date");
        String hourb= jo.getString("hour");

        HashMap<String, String> item = new HashMap<>();
        item.put("name", nameb);
        item.put("date", dateb);
        item.put("hour",hourb);

        list.add(item);
    }
} catch (JSONException e) {
    e.printStackTrace();
}

adapter = new SimpleAdapter(this,list,R.layout.activity_randevular,
new String[]{"name","date","hour"},new int[]{R.id.name,R.id.date,R.id.hour});

listView.setAdapter(adapter);
loading.dismiss();
```

first I have some strings on GoogleSheet and one of them indicates a hour like "14:00". On GoogleSheet it look perfect but in the ListView looks like this "2001-07-04T12:08:56.235-07:00" and so on.
I want it to consist of Hour and Minute.

答:
You have to convert the timestamp to date to be able to get the time. The input format is the format your timestamp is on your data source. The output format is how it will be shown to the user.

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
SimpleDateFormat outputFormat = new SimpleDateFormat("h:mm a");

try {
    String nameb= jo.getString("name");
    String dateb= jo.getString("date");
    String hourb= jo.getString("hour");

    Date date = inputFormat.parse(hourb);

    HashMap<String, String> item = new HashMap<>();
    item.put("name", nameb);
    item.put("date", dateb);
    item.put("hour", outputFormat.format(date));

    list.add(item);
} catch (ParseException e) {
    e.printStackTrace();
} catch (JSONException e) {
    e.printStackTrace();
}
```

Body:
I want to convert that string to DateFormat. In my ListView appears a little bit strange.

Here is the code

        String nameb= jo.getString("name");
        String dateb= jo.getString("date");
        String hourb= jo.getString("hour");

        HashMap<String, String> item = new HashMap<>();
        item.put("name", nameb);
        item.put("date", dateb);
        item.put("hour",hourb);

        list.add(item);
    }
} catch (JSONException e) {
    e.printStackTrace();
}

adapter = new SimpleAdapter(this,list,R.layout.activity_randevular,
new String[]{"name","date","hour"},new int[]{R.id.name,R.id.date,R.id.hour});

listView.setAdapter(adapter);
loading.dismiss();

first I have some strings on GoogleSheet and one of them indicates a hour like "14:00". On GoogleSheet it look perfect but in the ListView looks like this "2001-07-04T12:08:56.235-07:00" and so on.
I want it to consist of Hour and Minute.


问:
How can I get two different events with "querySelectorAll" for each element?
I have a probleme with my code. Now if I click the first element, all elements will become red, if I click second time they will become green. I would like have two independent events for each element with class fa-heart. I will explain better: If I click the first time the first element DOM, only this element will become red, and if I click it second time, it will become green, and so for all the others. I apologize if my request is not clear. Thank you so much for your help.</p>

```<code><script src="https://kit.fontawesome.com/a1d70a0cda.js"></script>
<a onclick="change()"><i class="fas fa-heart"></i></a>
<a onclick="change()"><i class="fas fa-heart"></i></a>
<a onclick="change()"><i class="fas fa-heart"></i></a>

<script>
 function change(){
      var a = document.querySelectorAll('.fa-heart');
      var qty = a.length;
      var i = 0;

      for(i; i<qty; i++){
         if(a[i].style.color !== 'red'){
             a[i].style.color = 'red';
         }else{
             a[i].style.color='green';
           }
     }
}
</script>
</code>```

答:
Here you go. This will change the clicked one to green and others to red.

function change(clicked) {
  document.querySelectorAll('a').forEach(el => el.setAttribute("style", "color:red"));
  clicked.style.cssText ="color:green;";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://kit.fontawesome.com/a1d70a0cda.js"></script>
<i class="fas fa-heart"></i>
<i class="fas fa-heart"></i>
<i class="fas fa-heart"></i></code>```

Body:
Here you go. This will change the clicked one to green and others to red.

function change(clicked) {
  document.querySelectorAll('a').forEach(el => el.setAttribute("style", "color:red"));
  clicked.style.cssText ="color:green;";
}

<script src="https://kit.fontawesome.com/a1d70a0cda.js"></script>
<a onclick="change(this)"><i class="fas fa-heart"></i></a>
<a onclick="change(this)"><i class="fas fa-heart"></i></a>
<a onclick="change(this)"><i class="fas fa-heart"></i></a>


问:
What is correct "source path directory" for AWS Amplify for Angular?
During amplify init there is a question: "Source path directory". Default is "/". Project is Angular. Should it be set to "/" or should it be set to "src"?</p>

答: For a standard project with the Angular CLI it will be src if you created your project with ng new app.


问:
Javascript loading CSV file into an array
I am developing a web page in Wordpress. The webpage needs to have a combobox with all counties. I have a dataset in csv format which has some 10k rows for all these counties.
When the user selects a county in the dropdown, I want only the selected county data displayed in the web page. This is my requirement.

In wordpress, my web page I am adding the js file using

```<code><script type="text/javascript" src="http://xxx/wp     content/uploads/2014/05/countyList1.js"></script>
</code>```

and the code for webpage dropdown is

```<code><select name="county" id="county" onload="setCounties();" onchange="getSelectedCountyData();"></select>
</code>```

In countyList1.js file I have the setCounties() and getSelectedCountyData() functions.

So far I can see the dropdown with counties list. I don't know how to read the CSV file and apply the selected county filter to this list.

I tried the FileReader object and I can load the CSV contents on the web page but I don't want the user to select the CSV. I have the dataset already.

I am trying to use this jquery.csv-0.71 library from this SO post How to read data From *.CSV file using javascript? but I need help.

Here's the code which gets called when a county is selected

```<code>function getSelectedCountyData() {
        cntrySel = document.getElementById('county');
        //selCty = countyList[cntrySel.value];
        handleFiles();
}

function handleFiles() {

    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "D:\Docs\Desktop\csvfile.csv",
            dataType: "csv",
            success: function (data) { processData(data); }
        });
    });
}

function processData(allText) {
    var allTextLines = allText.split(/\r\n|\n/);
    var headers = allTextLines[0].split(',');
    var lines = [];

    for (var i = 1; i < allTextLines.length; i++) {
        var data = allTextLines[i].split(',');
        if (data.length == headers.length) {

            var tarr = [];
            for (var j = 0; j < headers.length; j++) {
                tarr.push(headers[j] + ":" + data[j]);
            }
            lines.push(tarr);
        }
    }
    console.log(lines);
    drawOutput(lines);
}

function drawOutput(lines) {
    //Clear previous data
    document.getElementById("output").innerHTML = "";
    var table = document.createElement("table");
    for (var i = 0; i < lines.length; i++) {
        var row = table.insertRow(-1);
        for (var j = 0; j < lines[i].length; j++) {
            var firstNameCell = row.insertCell(-1);
            firstNameCell.appendChild(document.createTextNode(lines[i][j]));
        }
    }
    document.getElementById("output").appendChild(table);
}
</code>```

答: The original code works fine for reading and separating the csv file data but you need to change the data type from csv to text.</p>

Body:
I am developing a web page in Wordpress. The webpage needs to have a combobox with all counties. I have a dataset in csv format which has some 10k rows for all these counties.
When the user selects a county in the dropdown, I want only the selected county data displayed in the web page. This is my requirement.

In wordpress, my web page I am adding the js file using

and the code for webpage dropdown is

<select name="county" id="county" onload="setCounties();" onchange="getSelectedCountyData();"></select>

In countyList1.js file I have the setCounties() and getSelectedCountyData() functions.

So far I can see the dropdown with counties list. I don't know how to read the CSV file and apply the selected county filter to this list.

I tried the FileReader object and I can load the CSV contents on the web page but I don't want the user to select the CSV. I have the dataset already.

I am trying to use this jquery.csv-0.71 library from this SO post How to read data From *.CSV file using javascript? but I need help.

Here's the code which gets called when a county is selected

function getSelectedCountyData() {
        cntrySel = document.getElementById('county');
        //selCty = countyList[cntrySel.value];
        handleFiles();
}

function handleFiles() {

    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "D:\Docs\Desktop\csvfile.csv",
            dataType: "csv",
            success: function (data) { processData(data); }
        });
    });
}

function processData(allText) {
    var allTextLines = allText.split(/\r\n|\n/);
    var headers = allTextLines[0].split(',');
    var lines = [];

    for (var i = 1; i < allTextLines.length; i++) {
        var data = allTextLines[i].split(',');
        if (data.length == headers.length) {

            var tarr = [];
            for (var j = 0; j < headers.length; j++) {
                tarr.push(headers[j] + ":" + data[j]);
            }
            lines.push(tarr);
        }
    }
    console.log(lines);
    drawOutput(lines);
}

function drawOutput(lines) {
    //Clear previous data
    document.getElementById("output").innerHTML = "";
    var table = document.createElement("table");
    for (var i = 0; i < lines.length; i++) {
        var row = table.insertRow(-1);
        for (var j = 0; j < lines[i].length; j++) {
            var firstNameCell = row.insertCell(-1);
            firstNameCell.appendChild(document.createTextNode(lines[i][j]));
        }
    }
    document.getElementById("output").appendChild(table);
}


问:
Generating class datamembers from a Vector
Please consider this C++ question:

```<code>#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;

class ParseURL{
    private:
        int qualify; // 0 means we qualify
    public:
        string node;
        string service;
        bool primary;
        bool health;
        string epoch;
        // methods
        ParseURL(string URL);
        ~ParseURL();
};

ParseURL::ParseURL(string URL){
    vector<string> g2 = {"node", "service", "primary", "health", "epoch"};

    for (string tag : g2){
        auto found = URL.find(tag);
        if ( found != string::npos ){
            auto cut_from = found + 1 + tag.size() ;
            auto meh = URL.substr(cut_from, URL.substr(cut_from).find("&") );
            // is there a way we can avoid these lines below?
            if (tag.find("node",0) == 0){
                this->node = meh;
            } else if (tag.find("service",0) == 0 ){
                this->service = meh;
            } else if (tag.find("epoch",0) == 0) {
                this->epoch = meh;
            } else if (tag.find("health",0) == 0){
                this->health = (meh == "OK");
            } else if (tag.find("primary",0) == 0 ){
                this->primary == (this->node == meh);
            }
        }
    }

}

ParseURL::~ParseURL(){
    cout << "Tearing Down the class\n";
}
int main(){
    char req[] = "GET /register?node=hostrpi3&service=potatoservice&primary=node1&health=OK&epoch=1559345106 HTTP";
    string Request = req;
    Request = Request.substr(Request.find_first_of(" ") );
    Request = Request.substr(0, Request.find(" HTTP"));
    ParseURL *a = new ParseURL(Request);

    cout.width(12);
    cout << "a->node: " << a->node << endl;
    cout.width(12);
    cout << "a->service: " << a->service << endl;
    cout.width(12);
    cout << "a->epoch: " << a->epoch << endl;
    cout.width(12);
    cout << "a->health: " << a->health << endl;
    cout.width(12);
    cout << "a->primary: " << a->primary << endl;

    delete(a);

    return 0;
}
</code>```

I need to represent a object based on URL Query Strings, the tags I need are represented in vector g2, and as you can see, I make datamembers for ParseURL out of those tags.

The o/p looks like:

```<code>   a->node: hostrpi3
a->service: potatoservice
  a->epoch: 1559345106
 a->health: 1
a->primary: 0
Tearing Down the class
</code>```

Although this version works, it feels this can be improved much. Despite having it all in the Vector, I am repeatedly doing tag.find for each of those attributes. There must be a better way, I hope. Could you please point in the right direction? Thanks!

Edit 1

Thanks, I updated the constructor following the suggestions:

```<code>ParseURL::ParseURL(string URL){
    char tags[10][100] = {"node", "service", "primary", "health", "epoch"};

    int i = 0;
    for (auto tag : tags){
        auto found = URL.find(tag);
        if ( found != string::npos ){
            auto cut_from = found + 1 + strlen(tag);
            auto tag_info = URL.substr(cut_from, URL.substr(cut_from).find("&") );
            switch (i){
                case 0:
                    this->node = tag_info;
                    break;
                case 1:
                    this->service = tag_info;
                    break;
                case 2:
                    this->primary = (this->node == tag_info);
                    break;
                case 3:
                    this->health = (tag_info == "OK");
                    break;
                case 4:
                    this->epoch = tag_info;
                    break;
            }
        }
    i++;
    }
}
</code>```

bash for example, offers indirect reference of variables - that is, one variable may contain the name of another variable:

```<code>$ cat indirect.sh
#!/bin/bash

values="value1 value2"
value1="this is value1"
value2="this is value2"

for i in $values; do
    echo "$i has value ${!i}"
done

$ ./indirect.sh
value1 has value this is value1
value2 has value this is value2
</code>```

I was hoping something similar exists for cases like this, nevertheless, I learned valuable lessons here. thank you!

答:
Assuming that you want to keep the distinct class members (rather than one key-value store), you can use a static table of strings and pointers to members:

```<code>vector<pair<string,string ParseURL::*>> keys={{"node",&ParseURL::node},…};
</code>```

But that doesn’t work here because the types are different and because the processing isn’t identical for each.  Instead, for this sort of almost-parallelism, the syntactically optimal choice is often a lambda:

```<code>const auto get=[&URL](const string &tag) {
  auto found = URL.find(tag);
  if(found == string::npos) return "";
  auto cut_from = found + 1 + tag.size() ;
  return URL.substr(cut_from, URL.substr(cut_from).find("&") );
};
node=get("node");
service=get("service");
epoch=get("epoch");
health=get("health")=="OK";
primary=get("primary")==node;
</code>```

This style has the advantage of definitely initializing health and primary.  With sufficient contortions with a private constructor, it can be put into a member initializer list, which is even better practice.

Body:
Please consider this C++ question:

#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;

class ParseURL{
    private:
        int qualify; // 0 means we qualify
    public:
        string node;
        string service;
        bool primary;
        bool health;
        string epoch;
        // methods
        ParseURL(string URL);
        ~ParseURL();
};

ParseURL::ParseURL(string URL){
    vector<string> g2 = {"node", "service", "primary", "health", "epoch"};

    for (string tag : g2){
        auto found = URL.find(tag);
        if ( found != string::npos ){
            auto cut_from = found + 1 + tag.size() ;
            auto meh = URL.substr(cut_from, URL.substr(cut_from).find("&") );
            // is there a way we can avoid these lines below?
            if (tag.find("node",0) == 0){
                this->node = meh;
            } else if (tag.find("service",0) == 0 ){
                this->service = meh;
            } else if (tag.find("epoch",0) == 0) {
                this->epoch = meh;
            } else if (tag.find("health",0) == 0){
                this->health = (meh == "OK");
            } else if (tag.find("primary",0) == 0 ){
                this->primary == (this->node == meh);
            }
        }
    }

}

ParseURL::~ParseURL(){
    cout << "Tearing Down the class\n";
}
int main(){
    char req[] = "GET /register?node=hostrpi3&service=potatoservice&primary=node1&health=OK&epoch=1559345106 HTTP";
    string Request = req;
    Request = Request.substr(Request.find_first_of(" ") );
    Request = Request.substr(0, Request.find(" HTTP"));
    ParseURL *a = new ParseURL(Request);

    cout.width(12);
    cout << "a->node: " <node << endl;
    cout.width(12);
    cout << "a->service: " <service << endl;
    cout.width(12);
    cout << "a->epoch: " <epoch << endl;
    cout.width(12);
    cout << "a->health: " <health << endl;
    cout.width(12);
    cout << "a->primary: " <primary << endl;

    delete(a);

    return 0;
}

I need to represent a object based on URL Query Strings, the tags I need are represented in vector g2, and as you can see, I make datamembers for ParseURL out of those tags.

The o/p looks like:

   a->node: hostrpi3
a->service: potatoservice
  a->epoch: 1559345106
 a->health: 1
a->primary: 0
Tearing Down the class

Although this version works, it feels this can be improved much. Despite having it all in the Vector, I am repeatedly doing tag.find for each of those attributes. There must be a better way, I hope. Could you please point in the right direction? Thanks!

Edit 1

Thanks, I updated the constructor following the suggestions:

ParseURL::ParseURL(string URL){
    char tags[10][100] = {"node", "service", "primary", "health", "epoch"};

    int i = 0;
    for (auto tag : tags){
        auto found = URL.find(tag);
        if ( found != string::npos ){
            auto cut_from = found + 1 + strlen(tag);
            auto tag_info = URL.substr(cut_from, URL.substr(cut_from).find("&") );
            switch (i){
                case 0:
                    this->node = tag_info;
                    break;
                case 1:
                    this->service = tag_info;
                    break;
                case 2:
                    this->primary = (this->node == tag_info);
                    break;
                case 3:
                    this->health = (tag_info == "OK");
                    break;
                case 4:
                    this->epoch = tag_info;
                    break;
            }
        }
    i++;
    }
}

bash for example, offers indirect reference of variables - that is, one variable may contain the name of another variable:

$ cat indirect.sh
#!/bin/bash

values="value1 value2"
value1="this is value1"
value2="this is value2"

for i in $values; do
    echo "$i has value ${!i}"
done

$ ./indirect.sh
value1 has value this is value1
value2 has value this is value2

I was hoping something similar exists for cases like this, nevertheless, I learned valuable lessons here. thank you!

Body:
Assuming that you want to keep the distinct class members (rather than one key-value store), you can use a static table of strings and pointers to members:

vector<pair<string,string ParseURL::*>> keys={{"node",&ParseURL::node},…};

But that doesn’t work here because the types are different and because the processing isn’t identical for each.  Instead, for this sort of almost-parallelism, the syntactically optimal choice is often a lambda:

const auto get=[&URL](const string &tag) {
  auto found = URL.find(tag);
  if(found == string::npos) return "";
  auto cut_from = found + 1 + tag.size() ;
  return URL.substr(cut_from, URL.substr(cut_from).find("&") );
};
node=get("node");
service=get("service");
epoch=get("epoch");
health=get("health")=="OK";
primary=get("primary")==node;

This style has the advantage of definitely initializing health and primary.  With sufficient contortions with a private constructor, it can be put into a member initializer list, which is even better practice.


问:
Ampliy withAuthenticator v/s with withOAuth
AWS Amplify withAuthenticator v/s with OAuth

I want to implement an authentication mechanism for react app. I am using AWS Amplify framework, It provides 3 methods either use custom UI or with the authenticator and with OAuth components. I see with OAuth component provides Cognito hosted UI while withAuthenticator component provides AWS Amplify Custom UI.

What are the pros and cons of both except the UI

答: withAuthenticator is email & password against Cognito User Pools where the user is created in that directory. withOAuth and Auth.federatedSignIn use the OAuth endpoint of Cognito User Pools for OAuth flows, which performs redirects for you to authenticate users against a social provider such as Login With Amazon, Facebook, Google Sign-In, etc. A corresponding user account will be created in Cognito User Pools directory after this process takes place. More info can be found here: https://aws-amplify.github.io/docs/js/authentication#concepts


问:
I want to increase brightness and contrast of images in dynamic way so that the program is applicable for any new images
I have few images where I need to increase or decrease the contrast and brightness of the image in a dynamic way so that it is visible clearly. And the program needs to be dynamic so that it even works for new images also. I also want character should be dark.

I was able to increase brightness and contrast but it is not working properly for each image.

```<code>import cv2

import numpy as np

img = cv2.imread('D:\Bright.png')

image = cv2.GaussianBlur(img, (5, 5), 0)

#image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY)[1]

#kernel = np.ones((2,1),np.uint8)

#dilation = cv2.dilate(img,kernel)

cv2.imshow('test', image)

cv2.waitKey(0)

cv2.destroyAllWindows()

imghsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

imghsv[:,:,2] = [[max(pixel - 25, 0) if pixel < 190 else min(pixel + 25, 255) for pixel in row] for row in imghsv[:,:,2]]

cv2.imshow('contrast', cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))

#cv2.imwrite('D:\\112.png',cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))

cv2.waitKey(0)

cv2.destroyAllWindows()

#raw_input()
</code>```

I want a program which works fine for every image and words are a little darker so that they are easily visible.

答:
It is a very few lines of code to do it in Python Wand (which is based upon ImageMagick). Here is a script.

```<code>#!/bin/python3.7

from wand.image import Image

with Image(filename='task4.jpg') as img:
    img.contrast_stretch(black_point=0.02, white_point=0.99)
    img.save(filename='task4_stretch2_99.jpg')
</code>```

Input:

Result:

Increase the black point value to make the text darker and/or decrease the white point value to make the lighter parts brighter.

Thanks to Eric McConville (the Wand developer) for correcting my arguments to make the code work.

Body:
I have few images where I need to increase or decrease the contrast and brightness of the image in a dynamic way so that it is visible clearly. And the program needs to be dynamic so that it even works for new images also. I also want character should be dark.

I was able to increase brightness and contrast but it is not working properly for each image.

import cv2

import numpy as np

img = cv2.imread('D:\Bright.png')

image = cv2.GaussianBlur(img, (5, 5), 0)

#image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY)[1]

#kernel = np.ones((2,1),np.uint8)

#dilation = cv2.dilate(img,kernel)

cv2.imshow('test', image)

cv2.waitKey(0)

cv2.destroyAllWindows()

imghsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

imghsv[:,:,2] = [[max(pixel - 25, 0) if pixel < 190 else min(pixel + 25, 255) for pixel in row] for row in imghsv[:,:,2]]

cv2.imshow('contrast', cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))

#cv2.imwrite('D:\\112.png',cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))

cv2.waitKey(0)

cv2.destroyAllWindows()

#raw_input()

I want a program which works fine for every image and words are a little darker so that they are easily visible.

Body:
It is a very few lines of code to do it in Python Wand (which is based upon ImageMagick). Here is a script.

#!/bin/python3.7

from wand.image import Image

with Image(filename='task4.jpg') as img:
    img.contrast_stretch(black_point=0.02, white_point=0.99)
    img.save(filename='task4_stretch2_99.jpg')

Input:

Result:

Increase the black point value to make the text darker and/or decrease the white point value to make the lighter parts brighter.

Thanks to Eric McConville (the Wand developer) for correcting my arguments to make the code work.