问:
Creating <select> with onchange and eventListener
How would I take this:

```<code><select onchange='disable(this)'> //options here  </select>
</code>```

and make it into a createElement and eventListener? I don't know how to add the onchange="disable(this)".

So far I have:

```<code>var optionList = ["default", "yes", "no"];

var td = document.createElement("td");
selectList = document.createElement("select");
selectList.addEventListener("change", lockSelect, false);
td.appendChild(selectList);
newTableRow.appendChild(td);

for (var j = 0; j < optionList.length; j++)
{
   option = document.createElement("option");
   option.value = optionList[j];
   option.text = optionList[j];
   selectList.appendChild(option);
 }
</code>```

This makes the <select> and <options>, but I cant figure out how to make the onchange=disable(this)

答:
You need to create a function for lockSelect. You have not show the function for disable so I have to guess.

lockSelect should call disable passing the event target element to it.

It might be better to just change the disabled function to operate on an event object instead. and pass that directly to the event listener.

```<code>function disable(e) {
  e.target.disabled = true
}
</code>```

var optionList = ["default", "yes", "no"];
var newTableRow = document.querySelector('tr')

function disable(element) {
  element.disabled = true
}

function lockSelect(e) {
  disable(e.target)
}

var td = document.createElement("td");
selectList = document.createElement("select");
selectList.addEventListener("change", lockSelect, false);
td.appendChild(selectList);
newTableRow.appendChild(td);

for (var j = 0; j < optionList.length; j++) {
  option = document.createElement("option");
  option.value = optionList[j];
  option.text = optionList[j];
  selectList.appendChild(option);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr></tr>
</table></code>```

Body:
How would I take this:

<select onchange='disable(this)'> //options here  </select>

and make it into a createElement and eventListener? I don't know how to add the onchange="disable(this)".

So far I have:

var optionList = ["default", "yes", "no"];

var td = document.createElement("td");
selectList = document.createElement("select");
selectList.addEventListener("change", lockSelect, false);
td.appendChild(selectList);
newTableRow.appendChild(td);

for (var j = 0; j < optionList.length; j++)
{
   option = document.createElement("option");
   option.value = optionList[j];
   option.text = optionList[j];
   selectList.appendChild(option);
 }

This makes the <select> and <options>, but I cant figure out how to make the onchange=disable(this)

Body:
You need to create a function for lockSelect. You have not show the function for disable so I have to guess.

lockSelect should call disable passing the event target element to it.

It might be better to just change the disabled function to operate on an event object instead. and pass that directly to the event listener.

function disable(e) {
  e.target.disabled = true
}

var optionList = ["default", "yes", "no"];
var newTableRow = document.querySelector('tr')

function disable(element) {
  element.disabled = true
}

function lockSelect(e) {
  disable(e.target)
}

var td = document.createElement("td");
selectList = document.createElement("select");
selectList.addEventListener("change", lockSelect, false);
td.appendChild(selectList);
newTableRow.appendChild(td);

for (var j = 0; j < optionList.length; j++) {
  option = document.createElement("option");
  option.value = optionList[j];
  option.text = optionList[j];
  selectList.appendChild(option);
}

<table>
  <tr></tr>
</table>


来源: stackexchange

问:
AngularJS - Button click contained in grid with ng-click event
.html

```<code><div class="col col-50"
    ng-repeat="col in row"
    ng-click="openProductDetails(col.prod_id);">
    <button
        ng-click="addToCart(col.prod_id);">
        Add to cart
    </button>
</div>
</code>```

As you can see I have a grid or
 here which as openProductDetails() on click event. And inside the grid, I have a button which has an addToCart(). The problem is when I click the button, the openProductDetails() is also triggered. I cannot find a way to prevent the click event of the parent element when the button is clicked.

Thanks in advance.

答:
You can use Use event.stopPropation() .This variable is a reference to JS event object and can be used to call stopPropagation()

```<code> <div class="col col-50"
        ng-repeat="col in row"
        ng-click="openProductDetails(col.prod_id);">
        <button
            ng-click="addToCart(col.prod_id); $event.stopPropagation();">
            Add to cart
        </button>
    </div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
.html

    <button
        ng-click="addToCart(col.prod_id);">
        Add to cart
    </button>

As you can see I have a grid or
 here which as openProductDetails() on click event. And inside the grid, I have a button which has an addToCart(). The problem is when I click the button, the openProductDetails() is also triggered. I cannot find a way to prevent the click event of the parent element when the button is clicked.

Thanks in advance.

Body:
You can use Use event.stopPropation() .This variable is a reference to JS event object and can be used to call stopPropagation()

 <div class="col col-50"
        ng-repeat="col in row"
        ng-click="openProductDetails(col.prod_id);">
        <button
            ng-click="addToCart(col.prod_id); $event.stopPropagation();">
            Add to cart
        </button>
    </div>


问:
How to print string by awk in special format?
it's that able to convert following string

```
3.840527449999989,6A3,06,67,07,DF,0D,63,81,AA
4.306243875,601,02,3E,80,00,00,00,00,00
```

to format string like below

```
3.840527449999989,6A3,06 67 07 DF 0D 63 81 AA
4.306243875000000,601,02 3E 80 00 00 00 00 00
```

Note that:

timestamps should postfix 0 if necessary

data bytes should remove , between them

Body:
it's that able to convert following string

3.840527449999989,6A3,06,67,07,DF,0D,63,81,AA
4.306243875,601,02,3E,80,00,00,00,00,00

to format string like below

3.840527449999989,6A3,06 67 07 DF 0D 63 81 AA
4.306243875000000,601,02 3E 80 00 00 00 00 00

Note that:

timestamps should postfix 0 if necessary

data bytes should remove , between them

Body:
$ awk -F, '{$1=sprintf("%.15f",$1); for(i=1;i<3;i++) sub(OFS,FS)} 1' file
3.840527449999989,6A3,06 67 07 DF 0D 63 81 AA
4.306243875000000,601,02 3E 80 00 00 00 00 00


问:
Can't find bug in hash table copy constructor
when performing a copy of hash tables using my copy constructor such as:

```<code>LPTable<int> hashtableCopy = hashtable;
</code>```

the program crashes and I am unsure why. I have went through the debugger and it seems it knows what values it is receiving in the for loop, so I am confused as to what is happening, if it is a syntax/logical problem or what. Any help would be greatly appreciated, thank you. I will post what i have attempted so far.

hash table with copy ctor

```<code>template <class TYPE>
class LPTable :public Table<TYPE> {

    struct Record {
            TYPE data_;
            string key_;
            bool isDeleted = false;

            Record() {
                    key_ = "";
                    data_ = 0;
                    isDeleted = false;
            }

            Record(const string& key, const TYPE& data) {
                    key_ = key;
                    data_ = data;
                    isDeleted = false;
            }

    };

    Record** records_;   //the table
    int LargerMax;       // *1.35 max_
    int max_;           //capacity of the array
    int size_;          //current number of records held
    int MyHash(string key); // custom hash function
    int numRecords() const { return this.size_; }
    bool isEmpty()         { return size_ = 0; }

public:
    LPTable(int maxExpected);
    LPTable(const LPTable& other);
    LPTable(LPTable&& other);
    virtual bool update(const string& key, const TYPE& value);
    virtual bool remove(const string& key);
    virtual bool find(const string& key, TYPE& value);
    virtual const LPTable& operator=(const LPTable& other);
    virtual const LPTable& operator=(LPTable&& other);
    virtual ~LPTable();
};
/* none of the code in the function definitions below are correct.  You   can replace what you need
*/
template <class TYPE>
LPTable<TYPE>::LPTable(int maxExpected) : Table<TYPE>() {
    LargerMax = maxExpected * 1.35;

    records_ = new Record*[LargerMax];

    for (int i = 0; i < LargerMax; i++)
    {
            records_[i] = nullptr;
    }

    size_ = 0;
}

//copy ctor
template <class TYPE>
LPTable<TYPE>::LPTable(const LPTable<TYPE>& other) {

    records_ = new Record*[other.LargerMax];

    for (int i = 0; i < other.LargerMax; i++)
    {
            while (other.records_[i] != nullptr)
            {
                    records_[i]->key_ = other.records_[i]->key_;
                    records_[i]->data_ = other.records_[i]->data_;
                    records_[i]->isDeleted = other.records_[i]->isDeleted;
            }
    }

}

template <class TYPE>
const LPTable<TYPE>& LPTable<TYPE>::operator=(const LPTable<TYPE>& other)
{

    LPTable temp(other);
    std::swap(temp.records_, records_);
    std::swap(temp.max_, max_);
    std::swap(temp.size_, size_);
    return *this;

}

template <class TYPE>
const LPTable<TYPE>& LPTable<TYPE>::operator=(LPTable<TYPE>&& other) {
    return *this;

}
template <class TYPE>
LPTable<TYPE>::~LPTable() {

     delete[] records_;
}
</code>```

答:
You never set LargerMax, max_, or size_ in your copy constructor.  (You don't set max_ in the constructor taking int, either.)

When you copy other.records_, you're not allocating space for the records you need.  If the pointer in other.records_ is nullptr, just set that as the new pointer value in records_[i], otherwise set that to a new record allocated using the Records copy constructor.  Replace the while loop with

```<code>records_[i] = other.records_[i] == nullptr ? nullptr : new Record(other.records_[i])
</code>```

Body:
when performing a copy of hash tables using my copy constructor such as:

LPTable<int> hashtableCopy = hashtable;

the program crashes and I am unsure why. I have went through the debugger and it seems it knows what values it is receiving in the for loop, so I am confused as to what is happening, if it is a syntax/logical problem or what. Any help would be greatly appreciated, thank you. I will post what i have attempted so far.

hash table with copy ctor

template <class TYPE>
class LPTable :public Table<TYPE> {

    struct Record {
            TYPE data_;
            string key_;
            bool isDeleted = false;

            Record() {
                    key_ = "";
                    data_ = 0;
                    isDeleted = false;
            }

            Record(const string& key, const TYPE& data) {
                    key_ = key;
                    data_ = data;
                    isDeleted = false;
            }

    };

    Record** records_;   //the table
    int LargerMax;       // *1.35 max_
    int max_;           //capacity of the array
    int size_;          //current number of records held
    int MyHash(string key); // custom hash function
    int numRecords() const { return this.size_; }
    bool isEmpty()         { return size_ = 0; }

public:
    LPTable(int maxExpected);
    LPTable(const LPTable& other);
    LPTable(LPTable&& other);
    virtual bool update(const string& key, const TYPE& value);
    virtual bool remove(const string& key);
    virtual bool find(const string& key, TYPE& value);
    virtual const LPTable& operator=(const LPTable& other);
    virtual const LPTable& operator=(LPTable&& other);
    virtual ~LPTable();
};
/* none of the code in the function definitions below are correct.  You   can replace what you need
*/
template <class TYPE>
LPTable<TYPE>::LPTable(int maxExpected) : Table<TYPE>() {
    LargerMax = maxExpected * 1.35;

    records_ = new Record*[LargerMax];

    for (int i = 0; i < LargerMax; i++)
    {
            records_[i] = nullptr;
    }

    size_ = 0;
}

//copy ctor
template <class TYPE>
LPTable<TYPE>::LPTable(const LPTable<TYPE>& other) {

    records_ = new Record*[other.LargerMax];

    for (int i = 0; i < other.LargerMax; i++)
    {
            while (other.records_[i] != nullptr)
            {
                    records_[i]->key_ = other.records_[i]->key_;
                    records_[i]->data_ = other.records_[i]->data_;
                    records_[i]->isDeleted = other.records_[i]->isDeleted;
            }
    }

}

template <class TYPE>
const LPTable<TYPE>& LPTable<TYPE>::operator=(const LPTable<TYPE>& other)
{

    LPTable temp(other);
    std::swap(temp.records_, records_);
    std::swap(temp.max_, max_);
    std::swap(temp.size_, size_);
    return *this;

}

template <class TYPE>
const LPTable<TYPE>& LPTable<TYPE>::operator=(LPTable<TYPE>&& other) {
    return *this;

}
template <class TYPE>
LPTable<TYPE>::~LPTable() {

     delete[] records_;
}

Body:
You never set LargerMax, max_, or size_ in your copy constructor.  (You don't set max_ in the constructor taking int, either.)

When you copy other.records_, you're not allocating space for the records you need.  If the pointer in other.records_ is nullptr, just set that as the new pointer value in records_[i], otherwise set that to a new record allocated using the Records copy constructor.  Replace the while loop with

records_[i] = other.records_[i] == nullptr ? nullptr : new Record(other.records_[i])


问:
Docker How to connect to MongoDB from Web Service inside Container
Currently I want to setup a Linux Server with MongoDB and a WebServer which saves stuff inside this DB. I need them both to run inside Docker containers.

My problem is that my WebServer doesnt seem to "see" the MongoDB from inside its container.

What ive tried so far is:
run MongoDB with

docker run -p 27017:27017 -v... repoimage

it initializes fine and I can access this DB through the mongoshell without any problems.
Also the Webserver can access the DB if it DOESNT run in a container but just on the host as java application.

When I try now to run the server through a container I get a java exception saying "Connection refused" (which is thrown when he cant open the socket)

(Important: the server accesses the mongodb through "localhost")

I thought that container networks are "linked" together. Does anyone have the same problem?

答:
Just try to point the Webserver to the correct container IP. You can get the container IP by using this command

docker inspect <container-uid> | grep IPAddress.

I believe the default IP for the first container that spins up is 172.17.0.2. This way your Webserver will be pointing to container where MongoDB is running instead of the localhost.


问:
Why is my query not using this index?
I have a query I turned into a view that works OK. But the site_phrase sp table seems to be not using a column and goes through all the records in the table. Why is that? Here is the query:

```<code>    EXPLAIN SELECT
             `p`.`id`            AS `id`,
             `p`.`text`          AS `phrase`,
             `p`.`ignored`       AS `ignored_phrase`,
             `p`.`client_id`     AS `client_id`,
             `s`.`id`            AS `site_id`,
             `s`.`sub_domain`    AS `sub_domain`,
             `s`.`competitor`    AS `competitor`,
             `s`.`ignored`       AS `ignored_site`,
             `pc`.`id`           AS `pc_id`,
             `pc`.`name`         AS `pc_name`,
             `psc`.`id`          AS `psc_id`,
             `psc`.`name`        AS `psc_name`,
             `p`.`volume`         AS `volume`,
             MIN(`pos`.`position`) AS `position`,
             `pos`.`id`         AS `pos_id`
  FROM `client` c
  JOIN client_site cs ON cs.client_id = c.id
  JOIN site s ON s.id = cs.site_id
  JOIN site_phrase sp ON sp.site_id = s.id
  JOIN phrase p ON p.id = sp.phrase_id
  JOIN `position` pos ON pos.phrase_id = sp.phrase_id
    AND pos.site_id = sp.site_id
  LEFT JOIN `phrase_sub_category` `psc`
    ON `psc`.`id` = `p`.`phrase_sub_category_id`
  LEFT JOIN `phrase_category` `pc`
    ON `pc`.`id` = `psc`.`phrase_category_id`
  GROUP BY `p`.`id`,`s`.`id`,`serp`.`id`
  ORDER BY `p`.`id`,`pos`.`position`
</code>```

And here is a screenshot of the output the above query gets when I EXPLAIN / DESCRIBE it
http://img827.imageshack.us/img827/3336/indexsql.png

No matter how I alter the order of the tables above and how they are joined, the 1st or 2nd table always seems to be doing some sort of table scan. In the example of the screenshot, the problem table is sp.  These tables are innoDB type, and there is appropriate indexes and foreign keys on all the tables I JOIN on. Any insights would be helpful.

答: MySQL will use a full table scan if it determines that it is faster than a using index.  In the case of your SP table - with only 1300 records the table scan may be just as fast as a index.</p>

ContentLicense: CC BY-SA 2.5

Title: Why is my query not using this index?

Body:
I have a query I turned into a view that works OK. But the site_phrase sp table seems to be not using a column and goes through all the records in the table. Why is that? Here is the query:

    EXPLAIN SELECT
             `p`.`id`            AS `id`,
             `p`.`text`          AS `phrase`,
             `p`.`ignored`       AS `ignored_phrase`,
             `p`.`client_id`     AS `client_id`,
             `s`.`id`            AS `site_id`,
             `s`.`sub_domain`    AS `sub_domain`,
             `s`.`competitor`    AS `competitor`,
             `s`.`ignored`       AS `ignored_site`,
             `pc`.`id`           AS `pc_id`,
             `pc`.`name`         AS `pc_name`,
             `psc`.`id`          AS `psc_id`,
             `psc`.`name`        AS `psc_name`,
             `p`.`volume`         AS `volume`,
             MIN(`pos`.`position`) AS `position`,
             `pos`.`id`         AS `pos_id`
  FROM `client` c
  JOIN client_site cs ON cs.client_id = c.id
  JOIN site s ON s.id = cs.site_id
  JOIN site_phrase sp ON sp.site_id = s.id
  JOIN phrase p ON p.id = sp.phrase_id
  JOIN `position` pos ON pos.phrase_id = sp.phrase_id
    AND pos.site_id = sp.site_id
  LEFT JOIN `phrase_sub_category` `psc`
    ON `psc`.`id` = `p`.`phrase_sub_category_id`
  LEFT JOIN `phrase_category` `pc`
    ON `pc`.`id` = `psc`.`phrase_category_id`
  GROUP BY `p`.`id`,`s`.`id`,`serp`.`id`
  ORDER BY `p`.`id`,`pos`.`position`

And here is a screenshot of the output the above query gets when I EXPLAIN / DESCRIBE it
http://img827.imageshack.us/img827/3336/indexsql.png

No matter how I alter the order of the tables above and how they are joined, the 1st or 2nd table always seems to be doing some sort of table scan. In the example of the screenshot, the problem table is sp.  These tables are innoDB type, and there is appropriate indexes and foreign keys on all the tables I JOIN on. Any insights would be helpful.


问:
Expand list column of data.tables
I have a data.table with a list column, where each element is a data.table:

```<code>dt <- data.table(id = c(1, 1, 2),
                 var = list(data.table(a = c(1, 2), b = c(3, 4)),
                            data.table(a = c(5, 6), b = c(7, 8)),
                            data.table(a = 9, b = 10)))

dt
# id             var
# 1:  1 <data.table>
# 2:  1 <data.table>
# 3:  2 <data.table>
</code>```

Now I want to "unlist" this structure to:

```<code>   a  b id
1: 1  3  1
2: 2  4  1
3: 5  7  1
4: 6  8  1
5: 9 10  2
</code>```

I know how to expand the embedded data.table part with rbindlist, but just have no idea how to bind the flattened data.table with variable "id".

The original dataset is 30 million lines and with dozens of variables, so I would really appreciate if you would propose solution not only workable but also memory efficient.

答:
In this case dt[, var[[1]], by=id] works. However, I use rbindlist as the OP mentioned:

```<code>dt[, r := as.character(.I) ]
res <- dt[, rbindlist(setNames(var, r), id="r")]
</code>```

Then merge on r (rows of dt) if you really need any vars from there:

```<code>res[dt, on=.(r), `:=`(id = i.id)]
</code>```

This is better than dt[, var[[1]], by=id] in a few ways:

rbindlist should be faster than something with a lot of by= groups.

If there are more vars in dt, all of them will have to end up in by=.

Probably, it is not necessary to carry over vars from dt at all, since they can always be grabbed from that table later and they take up a lot less memory there.

Title: Expand list column of data.tables

Body:
I have a data.table with a list column, where each element is a data.table:

dt <- data.table(id = c(1, 1, 2),
                 var = list(data.table(a = c(1, 2), b = c(3, 4)),
                            data.table(a = c(5, 6), b = c(7, 8)),
                            data.table(a = 9, b = 10)))

dt
# id             var
# 1:  1 <data.table>
# 2:  1 <data.table>
# 3:  2 <data.table>

Now I want to "unlist" this structure to:

   a  b id
1: 1  3  1
2: 2  4  1
3: 5  7  1
4: 6  8  1
5: 9 10  2

I know how to expand the embedded data.table part with rbindlist, but just have no idea how to bind the flattened data.table with variable "id".

The original dataset is 30 million lines and with dozens of variables, so I would really appreciate if you would propose solution not only workable but also memory efficient.

Body:
In this case dt[, var[[1]], by=id] works. However, I use rbindlist as the OP mentioned:

dt[, r := as.character(.I) ]
res <- dt[, rbindlist(setNames(var, r), id="r")]

Then merge on r (rows of dt) if you really need any vars from there:

res[dt, on=.(r), `:=`(id = i.id)]

This is better than dt[, var[[1]], by=id] in a few ways:

rbindlist should be faster than something with a lot of by= groups.

If there are more vars in dt, all of them will have to end up in by=.

Probably, it is not necessary to carry over vars from dt at all, since they can always be grabbed from that table later and they take up a lot less memory there.


问:
meteor retrieve true/false value from checkbox switchChange
I have an event handler attached to checkboxes. I am using bootstrap switch http://www.bootstrap-switch.org/

I am trying to get the state value which is either true or false into a variable so I can set it to the session value.

I can get the true or false value when the state changes (as seen in the rendered code). However, I would like to get this value within events. Please check my x variable.

client.js

```<code>Template.myTemplate.rendered = function () {
 $('input[name="questions"]').bootstrapSwitch('state', true, true);
 $('input[name="questions"]').on('switchChange.bootstrapSwitch', function(event, state) {
 console.log(state); // true | false
});
</code>```

html:

```<code><template name="myTemplate">
 <div class="row">
  <input type="checkbox"  name="questions" unchecked> Hobby?
 </div>
 <div class="row">
  <input type="checkbox" name="questions" unchecked> Writer?
 </div>
</code>```

I am trying to get the value which is printed out in console.log(state) within the rendered code into a variable within my event so I can set the session to value to either true or false.

```<code>Template.myTemplate.events({
'click input': function(event) {
  var x = $(this).is(":checked").val();
  Session.set("statevalue", x);
  console.log(Session.get("statevalue")); // this is not printing out anything
 }
});
</code>```

答:
```<code>'click .task_checkbox'(event){

    const target = event.target;
    var isChecked = $("#"+event.target.id).is(":checked").val();
    console.log(isChecked);

},
</code>```

Body:
I have an event handler attached to checkboxes. I am using bootstrap switch http://www.bootstrap-switch.org/

I am trying to get the state value which is either true or false into a variable so I can set it to the session value.

I can get the true or false value when the state changes (as seen in the rendered code). However, I would like to get this value within events. Please check my x variable.

client.js

Template.myTemplate.rendered = function () {
 $('input[name="questions"]').bootstrapSwitch('state', true, true);
 $('input[name="questions"]').on('switchChange.bootstrapSwitch', function(event, state) {
 console.log(state); // true | false
});

html:

<template name="myTemplate">

  <input type="checkbox"  name="questions" unchecked> Hobby?

  <input type="checkbox" name="questions" unchecked> Writer?

I am trying to get the value which is printed out in console.log(state) within the rendered code into a variable within my event so I can set the session to value to either true or false.

Template.myTemplate.events({
'click input': function(event) {
  var x = $(this).is(":checked").val();
  Session.set("statevalue", x);
  console.log(Session.get("statevalue")); // this is not printing out anything
 }
});


问:
Media Query Triggering when it should not?
I have this test page.  Within it there's a .Test_container class that is supposed to have a flex box column layout unless the minimum width is 768 px.  This is the media query rule that is supposed to kick in at 768 px.

```<code>@media (min-width: 768px) index.css:1
 .u-md-flex-row {
     -webkit-box-orient: horizontal!important;
     -webkit-box-direction: normal!important;
      -ms-flex-direction: row!important;
      flex-direction: row!important;
 }
</code>```

If I uncheck `flex-direction: row then the layout renders in a column.  If I view the page on my cell phone or shrink the width below 768 px, then media query is still in effect.  Thoughts?

答:
You have to add the meta tag in your head

```<code><meta name="viewport" content="width=device-width" />
</code>```

Tried and Tested with your test page

Body:
I have this test page.  Within it there's a .Test_container class that is supposed to have a flex box column layout unless the minimum width is 768 px.  This is the media query rule that is supposed to kick in at 768 px.

@media (min-width: 768px) index.css:1
 .u-md-flex-row {
     -webkit-box-orient: horizontal!important;
     -webkit-box-direction: normal!important;
      -ms-flex-direction: row!important;
      flex-direction: row!important;
 }

If I uncheck `flex-direction: row then the layout renders in a column.  If I view the page on my cell phone or shrink the width below 768 px, then media query is still in effect.  Thoughts?

Body:
You have to add the meta tag in your head

<meta name="viewport" content="width=device-width" />

Tried and Tested with your test page


问:
WinForms - DataGridView - no cell selected
Is there a way to make a DataGridView have no cell selected? I notice even when it loses focus() it has a at least one active cell. Is there another mode that allows this? or some other trick? </p>

答:
I spent hours to find the solution for this problem. Do this:

Create a Form Project

Add a DataGridView with the name "DataGridView1"

Add the following code to your class Form1

```<code>Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim dgvRow(17) As DataGridViewRow
Dim i As Integer
For i = 0 To dgvRow.Length - 1
    dgvRow(i) = New DataGridViewRow()
    dgvRow(i).Height = 16
    dgvRow(i).Selected = False
    dgvRow(i).ReadOnly = True
    DataGridView1.Rows.Add(dgvRow(i))
    DataGridView1.CurrentRow.Selected = False
Next
End Sub
</code>```

The importaint line of code is

```<code>    DataGridView1.CurrentRow.Selected = False
</code>```

Good luck!

OwnerDisplayName: Bruno Tyndall

Body:
I spent hours to find the solution for this problem. Do this:

Create a Form Project

Add a DataGridView with the name "DataGridView1"

Add the following code to your class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim dgvRow(17) As DataGridViewRow
Dim i As Integer
For i = 0 To dgvRow.Length - 1
    dgvRow(i) = New DataGridViewRow()
    dgvRow(i).Height = 16
    dgvRow(i).Selected = False
    dgvRow(i).ReadOnly = True
    DataGridView1.Rows.Add(dgvRow(i))
    DataGridView1.CurrentRow.Selected = False
Next
End Sub

The importaint line of code is

    DataGridView1.CurrentRow.Selected = False

Good luck!

OwnerDisplayName: Nikolai


问:
Webservice to add users to SharePoint (like SPWeb.EnsureUser)
I need to add a user to a SharePoint-Website (WSS 3.0) via a Web Service.

Using the API I would use the SPWeb.EnsureUser method, but I can't run my own code on the server.

I was hoping the Users and Groups Web Service could help, but it does not provide a suitable method.

So, is there a Web Service equivalent to SPWeb.EnsureUser?

答:
I stumbled across this question yesterday. As a matter of fact, there is a Web Service equivalent of web.EnsureUser, but it is not in the UserGroup Web service. Use the ResolvePrincipals method of the People web service (_vti_bin/people.asmx) instead.

Here is the Microsoft documentation.

The key is to feed in true for the value of addToUserInfoList. The PrincipalInfo object returned by the service call includes a UserInfoID, which you can use in other membership-related operations on that site.

Here is an example of using the web service from PowerShell 2.0:

```<code>$client = new-webserviceproxy http://mysharepointsite/_vti_bin/people.asmx?wsdl -usedefault
$person = $client.ResolvePrincipals(@('domain\user'), 'User', $true)
# ...
</code>```

Body:
I stumbled across this question yesterday. As a matter of fact, there is a Web Service equivalent of web.EnsureUser, but it is not in the UserGroup Web service. Use the ResolvePrincipals method of the People web service (_vti_bin/people.asmx) instead.

Here is the Microsoft documentation.

The key is to feed in true for the value of addToUserInfoList. The PrincipalInfo object returned by the service call includes a UserInfoID, which you can use in other membership-related operations on that site.

Here is an example of using the web service from PowerShell 2.0:

$client = new-webserviceproxy http://mysharepointsite/_vti_bin/people.asmx?wsdl -usedefault
$person = $client.ResolvePrincipals(@('domain\user'), 'User', $true)
# ...


问:
filtering data frame based on column (item_id) value which have all digits?
following is a sample data frame in R -

```<code>date                  item_id           price
2010-09-15            0034              4546
2010-09-15            ABXC              4325
2010-09-15            12AB              3545
2010-09-15            ZF9C              4354
2010-09-15            Z923              7854
2010-09-15            923F              780
</code>```

desired output-

```<code>date                  item_id           price
2010-09-15            ABXC              4325
2010-09-15            12AB              3545
2010-09-15            ZF9C              4354
2010-09-15            Z923              7854
2010-09-15            923F              780
</code>```

i tried so far -

```<code>outlier_seq<-c('0','1','2','3','4','5','6','7','8','9')
df1<-sample_df[!grepl(paste(outlier_seq, collapse = "|"), sample$item_id),]
</code>```

but this is removing all the item_id consists number. instead of that just I want to filter out those records, whose item_id consist of all number. any help on this?

thanks

Body:
following is a sample data frame in R -

date                  item_id           price
2010-09-15            0034              4546
2010-09-15            ABXC              4325
2010-09-15            12AB              3545
2010-09-15            ZF9C              4354
2010-09-15            Z923              7854
2010-09-15            923F              780

desired output-

date                  item_id           price
2010-09-15            ABXC              4325
2010-09-15            12AB              3545
2010-09-15            ZF9C              4354
2010-09-15            Z923              7854
2010-09-15            923F              780

i tried so far -

outlier_seq<-c('0','1','2','3','4','5','6','7','8','9')
df1<-sample_df[!grepl(paste(outlier_seq, collapse = "|"), sample$item_id),]

but this is removing all the item_id consists number. instead of that just I want to filter out those records, whose item_id consist of all number. any help on this?

thanks

Body:
Assuming you are starting with:

mydf <- structure(list(date = c("2010-09-15", "2010-09-15", "2010-09-15",
    "2010-09-15", "2010-09-15"), item_id = c("0034", "ABXC", "12AB",
    "ZF9C", "ZF9C23"), price = c(4546L, 4325L, 3545L, 4354L, 7854L
    )), .Names = c("date", "item_id", "price"), row.names = c(NA,
    5L), class = "data.frame")

You should be able to just do:

mydf[!grepl("^[0-9]", mydf$item_id), ]
##         date item_id price
## 2 2010-09-15    ABXC  4325
## 4 2010-09-15    ZF9C  4354
## 5 2010-09-15  ZF9C23  7854


问:
Set a certain area of a canvas to be clickable
I need an example of this:
I have a canvas. And it refreshes constantly, I want to make an area of this canvas clickable, like a certain rectangular area of the canvas clickable, but not the whole canvas.</p>

答:
You can use LayerLayout, which you can add components on top of each other

A layered pane is a Swing container that provides a third dimension
  for positioning components: depth, also known as Z order. When adding
  a component to a layered pane, you specify its depth as an integer.
  The higher the number, closer the component is to the "top" position
  within the container. If components overlap, the "closer" components
  are drawn on top of components at a lower depth. The relationship
  between components at the same depth is determined by their positions
  within the depth.


问:
ServiceStack.Swagger.Api supportedSubmitMethods
I have a service set up that uses ServiceStack.Swagger.Api. My service has several endpoints that support OPTIONS requests. Is there a way to configure the SwaggerAPI plugin to add 'options' to the js SwaggerUi.supportedSubmitMethods list in the index.html?

The options requests shows but the 'Try It Out' button does not exists because the supportedSubmitMethods doesn't have options in it.

*Using ServiceStack 4.5.6

答:
ServiceStack Swagger's embedded resource files are overridable using the Virtual File System so you can override Swagger UI's default index.html by taking a copy of index.html and adding it to your Host Project in the /swagger-ui/ folder, e.g:

```<code>/swagger-ui/index.html
</code>```

Then modify your local copy of supportedSubmitMethods to include options, e.g:

```<code>window.swaggerUi = new SwaggerUi({
  url: url,
  dom_id: "swagger-ui-container",
  supportedSubmitMethods:['get', 'post', 'put', 'delete', 'patch', 'options'],
...
</code>```

Note in the latest v4.5.8 Release if you have a lot of OPTIONS Services you can add it to the list of default verbs for Routes that don't explicitly specify an HTTP Verbs with:

```<code>Plugins.Add(new SwaggerFeature
{
     AnyRouteVerbs = { HttpMethods.Options },
});
</code>```

Also if you're able to upgrade to v4.5.8 then you may want to consider switching to use the newer Open API Feature which implements v2.0 of the Open API specification which is the successor to Swagger.

Body:
ServiceStack Swagger's embedded resource files are overridable using the Virtual File System so you can override Swagger UI's default index.html by taking a copy of index.html and adding it to your Host Project in the /swagger-ui/ folder, e.g:

/swagger-ui/index.html

Then modify your local copy of supportedSubmitMethods to include options, e.g:

window.swaggerUi = new SwaggerUi({
  url: url,
  dom_id: "swagger-ui-container",
  supportedSubmitMethods:['get', 'post', 'put', 'delete', 'patch', 'options'],
...

Note in the latest v4.5.8 Release if you have a lot of OPTIONS Services you can add it to the list of default verbs for Routes that don't explicitly specify an HTTP Verbs with:

Plugins.Add(new SwaggerFeature
{
     AnyRouteVerbs = { HttpMethods.Options },
});

Also if you're able to upgrade to v4.5.8 then you may want to consider switching to use the newer Open API Feature which implements v2.0 of the Open API specification which is the successor to Swagger.


问:
Ember link-to not working when not passed a model
I have a template at the level just below the application route in my Ember application which contains a navbar with three tabs that should go to three sub routes. The link tos are set up like so:

```<code>{{#link-to "route.subroute.subroute-1"}}Route name{{/link-to}}
</code>```

If you right click on the links, they work, but left clicking on them does not take you to the page. Nothing happens and no error. If you hard code a model id into the link like so it works:

```<code>{{#link-to "route.subroute.subroute-1" 1}}Route name{{/link-to}}
</code>```

But passing a model name in place of the hard-coded id does not work, it merely adds a # to the end of the URL. How can I make this work?

Router.map(function() {

```<code>  this.route('/');
  this.route('route', function() {
    this.route('subroute', function() {
      this.route('subroute-1', { path: 'subroute-1/:route-1_id' });
      this.route('subroute-2', { path: 'subroute-2/:route-2_id' });
      this.route('subroute-3', { path: 'subroute-3/:route-3_id' });
    });
  });
});
</code>```

I tried changing router to

```<code>this.route('/');
  this.route('route', function() {
    this.route('subroute', { path: 'subroute/:model_id' }, function() {
      this.route('subroute-1');
      this.route('subroute-2');
      this.route('subroute-3');
    });
  });
});
</code>```

but then the findRecord('model', params.model_id) in the route/subroute/{id}/subroute-1 gets "ID passed to findRecord has to be number" error, and params.model_id is undefined.

答:
The reason you are running into problems is because Ember's router expects an id (or model) to be passed as part of the link-to helper, based on what you provide in your Router map:

```<code>this.route('route', function() {
  this.route('subroute', function() {
    // the :route-1_id info here causes problems
    this.route('subroute-1', { path: 'subroute-1/:route-1_id' });
    this.route('subroute-2', { path: 'subroute-2/:route-2_id' });
    this.route('subroute-3', { path: 'subroute-3/:route-3_id' });
  });
});
</code>```

If you don't have an id that you need for your sub route (that you intend to use to retrieve data from somewhere else), then you could do something like this:

```<code>this.route('route', function() {
  this.route('subroute', function() {
    this.route('subroute-1');
    this.route('subroute-2');
    this.route('subroute-3');
  });
});
</code>```

Body:
I have a template at the level just below the application route in my Ember application which contains a navbar with three tabs that should go to three sub routes. The link tos are set up like so:

{{#link-to "route.subroute.subroute-1"}}Route name{{/link-to}}

If you right click on the links, they work, but left clicking on them does not take you to the page. Nothing happens and no error. If you hard code a model id into the link like so it works:

{{#link-to "route.subroute.subroute-1" 1}}Route name{{/link-to}}

But passing a model name in place of the hard-coded id does not work, it merely adds a # to the end of the URL. How can I make this work?

Router.map(function() {

  this.route('/');
  this.route('route', function() {
    this.route('subroute', function() {
      this.route('subroute-1', { path: 'subroute-1/:route-1_id' });
      this.route('subroute-2', { path: 'subroute-2/:route-2_id' });
      this.route('subroute-3', { path: 'subroute-3/:route-3_id' });
    });
  });
});

I tried changing router to

this.route('/');
  this.route('route', function() {
    this.route('subroute', { path: 'subroute/:model_id' }, function() {
      this.route('subroute-1');
      this.route('subroute-2');
      this.route('subroute-3');
    });
  });
});

but then the findRecord('model', params.model_id) in the route/subroute/{id}/subroute-1 gets "ID passed to findRecord has to be number" error, and params.model_id is undefined.

Body:
The reason you are running into problems is because Ember's router expects an id (or model) to be passed as part of the link-to helper, based on what you provide in your Router map:

this.route('route', function() {
  this.route('subroute', function() {
    // the :route-1_id info here causes problems
    this.route('subroute-1', { path: 'subroute-1/:route-1_id' });
    this.route('subroute-2', { path: 'subroute-2/:route-2_id' });
    this.route('subroute-3', { path: 'subroute-3/:route-3_id' });
  });
});

If you don't have an id that you need for your sub route (that you intend to use to retrieve data from somewhere else), then you could do something like this:

this.route('route', function() {
  this.route('subroute', function() {
    this.route('subroute-1');
    this.route('subroute-2');
    this.route('subroute-3');
  });
});


答:
this should work try to understand the media query syntax
 there was problem with your syntax and you do not use important ifyou not required

```<code>@media (min-width:768px) {
.u-md-flex-row {
     -webkit-box-orient: horizontal;
     -webkit-box-direction: normal;
      -ms-flex-direction: row;
      flex-direction: row;
 }
}
</code>```

Title: Media Query Triggering when it should not?

Body:
this should work try to understand the media query syntax
 there was problem with your syntax and you do not use important ifyou not required

@media (min-width:768px) {
.u-md-flex-row {
     -webkit-box-orient: horizontal;
     -webkit-box-direction: normal;
      -ms-flex-direction: row;
      flex-direction: row;
 }
}


问:
Python searching for reversed Tuples in a set
If I have

```<code>Set = {(0,1), (1,1), (1,0)}
</code>```

How can I determine whether or not (a,b) and (b, a) are present in the set?

That is the Set above would return True and this set:

```<code>Set = {(0,1), (1,1), (1,2), (1,0)} #missing (2,1)
</code>```

would return false?

答:
```<code>all(tup[::-1] in Set for tup in Set)
</code>```

For each element of the set, we require that the reversal of that element is in the set. The above code is a pretty literal translation of that problem definition into Python.

Body:
If I have

Set = {(0,1), (1,1), (1,0)}

How can I determine whether or not (a,b) and (b, a) are present in the set?

That is the Set above would return True and this set:

Set = {(0,1), (1,1), (1,2), (1,0)} #missing (2,1)

would return false?

Body:
all(tup[::-1] in Set for tup in Set)

For each element of the set, we require that the reversal of that element is in the set. The above code is a pretty literal translation of that problem definition into Python.


问:
XML parsing error: <unknown>:4:0: not well-formed (invalid token)
I have absolutely no idea why this is returning an error all of a sudden.

XML parsing error:

<unknown>:4:0: not well-formed (invalid token)

XML

```<code><?xml version="1.0" encoding="iso-8859-1"?>
<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0"
<channel>
<title>The Deep(ish) Thoughts Podcast</title>
<link>http://www.deepishthoughts.com</link>
<language>en-us</language>
<copyright>2017</copyright>
<description> The Deep(ish) Thoughts Podcast </description>
<itunes:subtitle>Sports talk with Chris Horwedel and Anshu Khanna of DeepishThoughts.com</itunes:subtitle>
<itunes:author>Deep(ish) Thoughts</itunes:author>
<itunes:summary>Chris Horwedel and Anshu Khanna of Deep(ish) Thoughts talk about the biggest sports stories of the week.</itunes:summary>
<itunes:keywords> NFL, NBA, Sports, College Football, MLB, NHL, News, My Block Radio, Horwedel, Glymph </itunes:keywords>
<itunes:owner>
<itunes:name>Chris Horwedel</itunes:name>
<itunes:email>Hordel44@aol.com</itunes:email>
</itunes:owner>
<itunes:image href="http://www.archive.org/download/DTPitunes/DTPitunes.png"/>
<itunes:category text="Sports & Recreation"/>
<itunes:category text="Professional"/>
</itunes:category>
</code>```

答:
Your XML has several mistakes preventing it from being well-formed:

The opening rss tag is missing a >.

There is an unescaped & in Sports & Recreation.

There is an extraneous close </itunes:category> tag.

Body:
I have absolutely no idea why this is returning an error all of a sudden.

XML parsing error:

<unknown>:4:0: not well-formed (invalid token)

XML

<?xml version="1.0" encoding="iso-8859-1"?>
<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0"
<channel>
<title>The Deep(ish) Thoughts Podcast</title>
<link>http://www.deepishthoughts.com</link>
<language>en-us</language>
<copyright>2017</copyright>
<description> The Deep(ish) Thoughts Podcast </description>
<itunes:subtitle>Sports talk with Chris Horwedel and Anshu Khanna of DeepishThoughts.com</itunes:subtitle>
<itunes:author>Deep(ish) Thoughts</itunes:author>
<itunes:summary>Chris Horwedel and Anshu Khanna of Deep(ish) Thoughts talk about the biggest sports stories of the week.</itunes:summary>
<itunes:keywords> NFL, NBA, Sports, College Football, MLB, NHL, News, My Block Radio, Horwedel, Glymph </itunes:keywords>
<itunes:owner>
<itunes:name>Chris Horwedel</itunes:name>
<itunes:email>Hordel44@aol.com</itunes:email>
</itunes:owner>
<itunes:image href="http://www.archive.org/download/DTPitunes/DTPitunes.png"/>
<itunes:category text="Sports & Recreation"/>
<itunes:category text="Professional"/>
</itunes:category>


问:
Java, PreparedStatement, TransactSQL (MS SQL), last insert id
I insert some values into a database using a PreparedStatement, but it seems, that i cannot retrieve the last insert id in that case.

I try to use the same statement as i use for Statements (below) but it doent work. It says, that .executeQuery() cannot take arguments in this case.

In fact, i don't exactly need the last insert id, the number of affected rows will do, but how do i get that? I thought PreparedStatement's .executeUpdate() method would return the number of affected rows, but it apparently it does not.

Here is the method.

```<code> public static int getLastInsertId(Statement stmt) throws SQLException {
  String sql = "SELECT SCOPE_IDENTITY() AS id";

  ResultSet rs = stmt.executeQuery(sql);
  int id = 0;
  while (rs.next()) {
   id = rs.getInt("id");
  }
  return id;
 }
</code>```

Thank you in advance.

答: A PreparedStatement's executeUpdate method DOES indeed return the number of affected rows...</p>

Body:
I insert some values into a database using a PreparedStatement, but it seems, that i cannot retrieve the last insert id in that case.

I try to use the same statement as i use for Statements (below) but it doent work. It says, that .executeQuery() cannot take arguments in this case.

In fact, i don't exactly need the last insert id, the number of affected rows will do, but how do i get that? I thought PreparedStatement's .executeUpdate() method would return the number of affected rows, but it apparently it does not.

Here is the method.

 public static int getLastInsertId(Statement stmt) throws SQLException {
  String sql = "SELECT SCOPE_IDENTITY() AS id";

  ResultSet rs = stmt.executeQuery(sql);
  int id = 0;
  while (rs.next()) {
   id = rs.getInt("id");
  }
  return id;
 }

Thank you in advance.


问:
How can I write if/else with Boolean in Bash?
How can I write an 'if then' statement to switch between these to variables as in the following?

```<code>if(switch){
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
} else {
  server_var_shortname=$server_vps_shortname
  server_var=$server_vps
  server_var_bare=$server_vps_bare
}
</code>```

I'm not familiar with Bash syntax and basically just need an 'if/else' statement on a Boolean. Also, can I use true / false values as such? Also how do I do the 'else' statement?

```<code>$switch=true;
if $switch
then
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
fi
</code>```

答:
Bash doesn't have any concept of Boolean - there are no true / false values. The construct

```<code>[ $switch ]
</code>```

will be true except when switch variable is not set or is set to an empty string.

```<code>[ ]    && echo yes                      # Nothing is echoed
[ "" ] && echo yes                      # Nothing is echoed
unset switch && [ $switch ] && echo yes # Nothing is echoed
switch=1 && [ $switch ] && echo yes     # 'yes' is echoed
switch=0 && [ $switch ] && echo yes     # 'yes' is echoed - the shell makes no distinction of contents - it is true as long it is not empty
</code>```

See also:

How can I declare and use Boolean variables in a shell script?

ContentLicense: CC BY-SA 4.0

Body:
How can I write an 'if then' statement to switch between these to variables as in the following?

if(switch){
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
} else {
  server_var_shortname=$server_vps_shortname
  server_var=$server_vps
  server_var_bare=$server_vps_bare
}

I'm not familiar with Bash syntax and basically just need an 'if/else' statement on a Boolean. Also, can I use true / false values as such? Also how do I do the 'else' statement?

$switch=true;
if $switch
then
  server_var_shortname=$server_shared_shortname
  server_var=$server_shared
  server_var_bare=$server_shared_bare
fi

Body:
Bash doesn't have any concept of Boolean - there are no true / false values. The construct

[ $switch ]

will be true except when switch variable is not set or is set to an empty string.

[ ]    && echo yes                      # Nothing is echoed
[ "" ] && echo yes                      # Nothing is echoed
unset switch && [ $switch ] && echo yes # Nothing is echoed
switch=1 && [ $switch ] && echo yes     # 'yes' is echoed
switch=0 && [ $switch ] && echo yes     # 'yes' is echoed - the shell makes no distinction of contents - it is true as long it is not empty

See also:

How can I declare and use Boolean variables in a shell script?


问:
Checking if AFP server is already mounted applescript
How to I check if file server is currently connected? (Using AFP to connect) Sorry if Im asking this wrong.</p>

答:
if a server is mounted there is a corresponding volume in /Volumes.

```<code>if "serverVolume" is in do shell script "ls /Volumes" then ... -- server is mounted
</code>```

Replace serverVolume with the name of the volume.

Body:
if a server is mounted there is a corresponding volume in /Volumes.

if "serverVolume" is in do shell script "ls /Volumes" then ... -- server is mounted

Replace serverVolume with the name of the volume.


问:
IndexedDB - How to create and use simple and complex IDBIndex keyPaths?
I want to create and use two IndexedDB indices, one with a simple keyPath and the other with a complex keyPath. Although the creation is successful in every browser I tried, the indices do not seem to be filled correctly in most.

The procedure I'm using (self-contained test case at the end of the question) is:

Creation of an indexedDB with a single store with { keyPath: 'id', autoIncrement: true }.

Creation of two indices: the first index is created with keyPath: 'id' and { unique: false, multiEntry: false }. The second index is created with keyPath: ['id', 'name'] and { unique: false, multiEntry: false }.

Addition of some (19) objects to the store, all with a name attribute present.

Calling IDBIndex.count on both indices.

The expectation was that both calls of IDBIndex.count would return the total number of objects present in the store (19). Depending on the browser, this may or may not happen:

Safari    10.0.3          simple: 19, complex: 19

Chrome    57.0.2987.98    simple: 19, complex: 0

Opera     43.0.2442.1144  simple: 19, complex: 0

IE        11.953.14393.0  simple: 0, complex: 0

Edge      38.14393.0.0    simple: 0, complex: 0

Firefox   54.0a2          simple: 0, complex: 0

If I change the creation of the indices from { unique: false, multiEntry: false } to just { unique: false } the behaviour remains the same in every browser.

If I change the creation of the complex index from ['id', 'name'] to the (according to the spec) equivalent id.name, Safari changes behaviour to simple: 19, complex: 0¹, the others remain the same.

If I change the creation of the complex index from 'id' index to ['id'], Safari still returns simple: 19, complex: 0, every other browser returns simple: 0, complex: 0.

What am I doing wrong? How do I create multi-attribute indices?

(I'm currently using the following self-contained example for testing, which will not work on stackoverflow due to it using indexedDB)

var deleteRequest = indexedDB.deleteDatabase('test-db');
deleteRequest.onerror = deleteRequest.onblocked = deleteRequest.onsuccess = function () {
 console.log('Database deleted', arguments);
 var openRequest = indexedDB.open('test-db');
 openRequest.onerror = function (errorEvent) { console.log('open error', errorEvent); };
 openRequest.onblocked = function (blockedEvent) { console.log('open blocked', blockedEvent); };
 openRequest.onupgradeneeded = function (upgradeEvent) {
  console.log('Database opened');
  var database = upgradeEvent.target.result;
  var store = database.createObjectStore('sochrastic', { keyPath: 'id', autoIncrement: true });
  store.createIndex('index_name', ['id', 'name'], { unique: false, multiEntry: false });
  store.createIndex('index_id', 'id', { unique: false, multiEntry: false });
 };
 openRequest.onsuccess = function (successEvent) {
  console.log('Indices created');
  successEvent.target.result.close();
  var openRequest = indexedDB.open('test-db');
  openRequest.onerror = function (errorEvent) { console.log('open error', errorEvent); };
  openRequest.onblocked = function (blockedEvent) { console.log('open blocked', blockedEvent); };
  openRequest.onsuccess = function (upgradeEvent) {
   console.log('Database opened');
   var database = upgradeEvent.target.result;
   var transaction = database.transaction('sochrastic', 'readwrite');
   var store = transaction.objectStore('sochrastic');
   store.add({ name: 'druk', badjorance: 'animal' });
   store.add({ name: 'druk', badjorance: 'beast' });
   store.add({ name: 'druk', badjorance: 'canal' });
   store.add({ name: 'myke', badjorance: 'dice' });
   store.add({ name: 'myke', badjorance: 'evergreen' });
   store.add({ name: 'myke', badjorance: 'fake' });
   store.add({ name: 'myke', badjorance: 'game' });
   store.add({ name: 'grey', badjorance: 'honor' });
   store.add({ name: 'grey', badjorance: 'incognito' });
   store.add({ name: 'grey', badjorance: 'joke' });
   store.add({ name: 'grey', badjorance: 'key' });
   store.add({ name: 'grey', badjorance: 'lemon' });
   store.add({ name: 'brady', badjorance: 'mast' });
   store.add({ name: 'brady', badjorance: 'nothing' });
   store.add({ name: 'brady', badjorance: 'opera' });
   store.add({ name: 'brady', badjorance: 'pear' });
   store.add({ name: 'brady', badjorance: 'quote' });
   store.add({ name: 'brady', badjorance: 'rodent' });
   store.add({ name: 'brady', badjorance: 'sunk' });

   database.close();
   var openRequest = indexedDB.open('test-db');
   openRequest.onerror = function (errorEvent) { console.log('open error', errorEvent); };
   openRequest.onblocked = function (blockedEvent) { console.log('open blocked', blockedEvent); };
   openRequest.onsuccess = function (successEvent) {
    console.log('Store filled');
    var database = successEvent.target.result;
    var transaction = database.transaction('sochrastic', 'readonly');
    var store = transaction.objectStore('sochrastic');
    var indexName = store.index('index_name');
    var nameCountRequest = indexName.count();
    nameCountRequest.onerror = function (errorEvent) { document.querySelector('#name-id-count').textContent = 'error'; console.log(errorEvent); };
    nameCountRequest.onblocked = function (blockedEvent) { document.querySelector('#name-id-count').textContent = 'blocked'; console.log(blockedEvent); };
    nameCountRequest.onsuccess = function (successEvent) { document.querySelector('#name-id-count').textContent = successEvent.target.result; console.log('name-id', successEvent.target.result); };

    var indexId = store.index('index_id');
    var idCountRequest = indexId.count();
    idCountRequest.onerror = function (errorEvent) { document.querySelector('#id-count').textContent = 'error'; console.log(errorEvent); };
    idCountRequest.onblocked = function (blockedEvent) { document.querySelector('#id-count').textContent = 'blocked'; console.log(blockedEvent); };
    idCountRequest.onsuccess = function (successEvent) { document.querySelector('#id-count').textContent = successEvent.target.result; console.log('id', successEvent.target.result); };
   }
  }
 }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
 <meta charset="utf-8"/>
 <title>IndexedDB Indices</title>
</head>
<body>
 <p>['id', 'name'] index result: <span id="name-id-count"></span></p>
 <p>['id'] index result: <span id="id-count"></span></p>
</body>
</html></code>```

答:
IE and Edge don't support complex indexes at all https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/?q=indexeddb but you can use them in other browsers.

If I change the creation of the complex index from ['id', 'name'] to the (according to the spec) equivalent id.name, Safari changes behaviour to simple: 19, complex: 0, the others remain the same.

Those aren't equivalent. id.name creates an index on a single value like {id: {name: 'value'}}, and ['id', 'name'] creates a compound index on two fields with those names like {id: 1, name: 'value'}.

Your indexes are failing because you're relying on the auto-generated primary key id. If you change id to badjorance, then your counts are as you expected, at least in Firefox and Chrome. (BTW, I didn't see any difference in those even in your original example, both browsers show 0s for both counts).

I guess some browsers evaluate the keyPath before adding the primary key to the object, and others after. As to which behavior is correct... it's too late at night for me to want to read the spec, but unless the spec is ambiguous, you might want to report bugs in the browsers that got it wrong. If I were a betting man, I'd guess that Safari is the one that's wrong.

Body:
I want to create and use two IndexedDB indices, one with a simple keyPath and the other with a complex keyPath. Although the creation is successful in every browser I tried, the indices do not seem to be filled correctly in most.

The procedure I'm using (self-contained test case at the end of the question) is:

Creation of an indexedDB with a single store with { keyPath: 'id', autoIncrement: true }.

Creation of two indices: the first index is created with keyPath: 'id' and { unique: false, multiEntry: false }. The second index is created with keyPath: ['id', 'name'] and { unique: false, multiEntry: false }.

Addition of some (19) objects to the store, all with a name attribute present.

Calling IDBIndex.count on both indices.

The expectation was that both calls of IDBIndex.count would return the total number of objects present in the store (19). Depending on the browser, this may or may not happen:

Safari    10.0.3          simple: 19, complex: 19

Chrome    57.0.2987.98    simple: 19, complex: 0

Opera     43.0.2442.1144  simple: 19, complex: 0

IE        11.953.14393.0  simple: 0, complex: 0

Edge      38.14393.0.0    simple: 0, complex: 0

Firefox   54.0a2          simple: 0, complex: 0

If I change the creation of the indices from { unique: false, multiEntry: false } to just { unique: false } the behaviour remains the same in every browser.

If I change the creation of the complex index from ['id', 'name'] to the (according to the spec) equivalent id.name, Safari changes behaviour to simple: 19, complex: 0¹, the others remain the same.

If I change the creation of the complex index from 'id' index to ['id'], Safari still returns simple: 19, complex: 0, every other browser returns simple: 0, complex: 0.

What am I doing wrong? How do I create multi-attribute indices?

(I'm currently using the following self-contained example for testing, which will not work on stackoverflow due to it using indexedDB)

var deleteRequest = indexedDB.deleteDatabase('test-db');
deleteRequest.onerror = deleteRequest.onblocked = deleteRequest.onsuccess = function () {
 console.log('Database deleted', arguments);
 var openRequest = indexedDB.open('test-db');
 openRequest.onerror = function (errorEvent) { console.log('open error', errorEvent); };
 openRequest.onblocked = function (blockedEvent) { console.log('open blocked', blockedEvent); };
 openRequest.onupgradeneeded = function (upgradeEvent) {
  console.log('Database opened');
  var database = upgradeEvent.target.result;
  var store = database.createObjectStore('sochrastic', { keyPath: 'id', autoIncrement: true });
  store.createIndex('index_name', ['id', 'name'], { unique: false, multiEntry: false });
  store.createIndex('index_id', 'id', { unique: false, multiEntry: false });
 };
 openRequest.onsuccess = function (successEvent) {
  console.log('Indices created');
  successEvent.target.result.close();
  var openRequest = indexedDB.open('test-db');
  openRequest.onerror = function (errorEvent) { console.log('open error', errorEvent); };
  openRequest.onblocked = function (blockedEvent) { console.log('open blocked', blockedEvent); };
  openRequest.onsuccess = function (upgradeEvent) {
   console.log('Database opened');
   var database = upgradeEvent.target.result;
   var transaction = database.transaction('sochrastic', 'readwrite');
   var store = transaction.objectStore('sochrastic');
   store.add({ name: 'druk', badjorance: 'animal' });
   store.add({ name: 'druk', badjorance: 'beast' });
   store.add({ name: 'druk', badjorance: 'canal' });
   store.add({ name: 'myke', badjorance: 'dice' });
   store.add({ name: 'myke', badjorance: 'evergreen' });
   store.add({ name: 'myke', badjorance: 'fake' });
   store.add({ name: 'myke', badjorance: 'game' });
   store.add({ name: 'grey', badjorance: 'honor' });
   store.add({ name: 'grey', badjorance: 'incognito' });
   store.add({ name: 'grey', badjorance: 'joke' });
   store.add({ name: 'grey', badjorance: 'key' });
   store.add({ name: 'grey', badjorance: 'lemon' });
   store.add({ name: 'brady', badjorance: 'mast' });
   store.add({ name: 'brady', badjorance: 'nothing' });
   store.add({ name: 'brady', badjorance: 'opera' });
   store.add({ name: 'brady', badjorance: 'pear' });
   store.add({ name: 'brady', badjorance: 'quote' });
   store.add({ name: 'brady', badjorance: 'rodent' });
   store.add({ name: 'brady', badjorance: 'sunk' });

   database.close();
   var openRequest = indexedDB.open('test-db');
   openRequest.onerror = function (errorEvent) { console.log('open error', errorEvent); };
   openRequest.onblocked = function (blockedEvent) { console.log('open blocked', blockedEvent); };
   openRequest.onsuccess = function (successEvent) {
    console.log('Store filled');
    var database = successEvent.target.result;
    var transaction = database.transaction('sochrastic', 'readonly');
    var store = transaction.objectStore('sochrastic');
    var indexName = store.index('index_name');
    var nameCountRequest = indexName.count();
    nameCountRequest.onerror = function (errorEvent) { document.querySelector('#name-id-count').textContent = 'error'; console.log(errorEvent); };
    nameCountRequest.onblocked = function (blockedEvent) { document.querySelector('#name-id-count').textContent = 'blocked'; console.log(blockedEvent); };
    nameCountRequest.onsuccess = function (successEvent) { document.querySelector('#name-id-count').textContent = successEvent.target.result; console.log('name-id', successEvent.target.result); };

    var indexId = store.index('index_id');
    var idCountRequest = indexId.count();
    idCountRequest.onerror = function (errorEvent) { document.querySelector('#id-count').textContent = 'error'; console.log(errorEvent); };
    idCountRequest.onblocked = function (blockedEvent) { document.querySelector('#id-count').textContent = 'blocked'; console.log(blockedEvent); };
    idCountRequest.onsuccess = function (successEvent) { document.querySelector('#id-count').textContent = successEvent.target.result; console.log('id', successEvent.target.result); };
   }
  }
 }
}

<!doctype html>

 <meta charset="utf-8"/>
 <title>IndexedDB Indices</title>

['id', 'name'] index result:

['id'] index result:


答:
First, shells (including Bash) don't have Booleans; they don't even have integers (although they can sort of fake it). Mostly, they have strings.

Bash also has arrays... of strings. There are a number of ways of faking Booleans; my favorite is to use the strings "true" and "false". These also happen to be the names of commands that always succeed and fail respectively, which comes in handy, because the if statement actually takes a command, and runs the then clause if it succeeds and the else clause if it fails. Thus, you can "run" the Boolean, and it'll succeed if set to "true" and fail if set to "false". Like this:

```<code>switch=true  # This doesn't have quotes around it, but it's a string anyway.
# ...
if $switch; then
    server_var_shortname=$server_shared_shortname
    server_var=$server_shared
    server_var_bare=$server_shared_bare
else
    server_var_shortname=$server_vps_shortname
    server_var=$server_vps
    server_var_bare=$server_vps_bare
fi
</code>```

Note that the more usual format you'll see for if has square-brackets, like if [ something ]; then. In this case, [ is actually a command (not some funny sort of grouping operator) that evaluates its argument as an expression; thus [ "some string" = "some other string" ] is a command that will fail because the strings aren't equal. You could use if [ "$switch" = true ]; then, but I prefer to cheat and use the fake Boolean directly.

Caveat: if you do use the cheat I'm suggesting, make sure your "Boolean" variable is set to either "true" or "false" -- not unset, not set to something else. If it's set to anything else, I take no responsibility for the results.

Some other syntax notes:

Use $ on variables when fetching their values, not when assigning to them. You have $switch=true; up there, which will get you an error.

Also, you have a semicolon at the end of that line. This is unnecessary; semicolons are used to separate multiple commands on the same line (and a few other places), but they aren't needed to end the last (/only) command on a line.

The [ command (which is also known as test) has a kind of weird syntax. Mostly because it's a command, so it goes through the usual command parsing, so e.g. [ 5 > 19 ] is parsed as [ 5 ] with output sent to a file named "19" (and is then true, because "5" is nonblank). [ 5 ">" 19 ] is better, but still evaluates to true because > does string (alphabetical) comparisons, and "5" is alphabetically after "19". [ 5 -gt 19 ] does the expected thing.

There's also [[ ]] (similar, but cleaner syntax and not available in all shells) and (( )) (for math, not strings; also not in all shells). See Bash FAQ #31.

Putting commands in variables is generally a bad idea. See Bash FAQ #50.

shellcheck.net is your friend.

Title: How can I write if/else with Boolean in Bash?

Body:
First, shells (including Bash) don't have Booleans; they don't even have integers (although they can sort of fake it). Mostly, they have strings.

Bash also has arrays... of strings. There are a number of ways of faking Booleans; my favorite is to use the strings "true" and "false". These also happen to be the names of commands that always succeed and fail respectively, which comes in handy, because the if statement actually takes a command, and runs the then clause if it succeeds and the else clause if it fails. Thus, you can "run" the Boolean, and it'll succeed if set to "true" and fail if set to "false". Like this:

switch=true  # This doesn't have quotes around it, but it's a string anyway.
# ...
if $switch; then
    server_var_shortname=$server_shared_shortname
    server_var=$server_shared
    server_var_bare=$server_shared_bare
else
    server_var_shortname=$server_vps_shortname
    server_var=$server_vps
    server_var_bare=$server_vps_bare
fi

Note that the more usual format you'll see for if has square-brackets, like if [ something ]; then. In this case, [ is actually a command (not some funny sort of grouping operator) that evaluates its argument as an expression; thus [ "some string" = "some other string" ] is a command that will fail because the strings aren't equal. You could use if [ "$switch" = true ]; then, but I prefer to cheat and use the fake Boolean directly.

Caveat: if you do use the cheat I'm suggesting, make sure your "Boolean" variable is set to either "true" or "false" -- not unset, not set to something else. If it's set to anything else, I take no responsibility for the results.

Some other syntax notes:

Use $ on variables when fetching their values, not when assigning to them. You have $switch=true; up there, which will get you an error.

Also, you have a semicolon at the end of that line. This is unnecessary; semicolons are used to separate multiple commands on the same line (and a few other places), but they aren't needed to end the last (/only) command on a line.

The [ command (which is also known as test) has a kind of weird syntax. Mostly because it's a command, so it goes through the usual command parsing, so e.g. [ 5 > 19 ] is parsed as [ 5 ] with output sent to a file named "19" (and is then true, because "5" is nonblank). [ 5 ">" 19 ] is better, but still evaluates to true because > does string (alphabetical) comparisons, and "5" is alphabetically after "19". [ 5 -gt 19 ] does the expected thing.

There's also [[ ]] (similar, but cleaner syntax and not available in all shells) and (( )) (for math, not strings; also not in all shells). See Bash FAQ #31.

Putting commands in variables is generally a bad idea. See Bash FAQ #50.

shellcheck.net is your friend.


问:
Very simple C# CSV reader
I'd like to create an array from a CSV file.

This is about as simple as you can imagine, the CSV file will only ever have one line and these values:

```<code>Device, SignalStrength, Location, Time, Age.
</code>```

I'd like to put these values into one dimensional array.

I've tried some examples but they've all been more complicated than required.

答:
First of all need to understand what is CSV and how to write it.

(Most of answers (all of them at the moment) do not use this requirements, that's why they all is wrong!)

Every next string ( /r/n ) is next "table" row.

"Table" cells is separated by some delimiter symbol.

As delimiter can be used ANY symbol. Often this is \t or ,.

Each cell possibly can contain this delimiter symbol inside of the cell (cell must to start with double quotes symbol and to have double quote in the end in this case)

Each cell possibly can contains /r/n symbols inside of the cell  (cell must to start with double quotes symbol and to have double quote in the end in this case)

Some time ago I had wrote simple class for CSV read/write based on standard Microsoft.VisualBasic.FileIO library. Using this simple class you will be able to work with CSV like with 2 dimensions array.

Simple example of using my library:

```<code>Csv csv = new Csv("\t");//delimiter symbol

csv.FileOpen("c:\\file1.csv");

var row1Cell6Value = csv.Rows[0][5];

csv.AddRow("asdf","asdffffff","5")

csv.FileSave("c:\\file2.csv");
</code>```

You can find my class by the following link and investigate how it's written:
https://github.com/ukushu/DataExporter

This library code is really fast in work and source code is really short.

PS: In the same time this solution will not work for unity.

PS2: Another solution is to work with library "LINQ-to-CSV". It must also work well. But it's will be bigger.

Title: Very simple C# CSV reader

Body:
I'd like to create an array from a CSV file.

This is about as simple as you can imagine, the CSV file will only ever have one line and these values:

Device, SignalStrength, Location, Time, Age.

I'd like to put these values into one dimensional array.

I've tried some examples but they've all been more complicated than required.

Body:
First of all need to understand what is CSV and how to write it.

(Most of answers (all of them at the moment) do not use this requirements, that's why they all is wrong!)

Every next string ( /r/n ) is next "table" row.

"Table" cells is separated by some delimiter symbol.

As delimiter can be used ANY symbol. Often this is \t or ,.

Each cell possibly can contain this delimiter symbol inside of the cell (cell must to start with double quotes symbol and to have double quote in the end in this case)

Each cell possibly can contains /r/n symbols inside of the cell  (cell must to start with double quotes symbol and to have double quote in the end in this case)

Some time ago I had wrote simple class for CSV read/write based on standard Microsoft.VisualBasic.FileIO library. Using this simple class you will be able to work with CSV like with 2 dimensions array.

Simple example of using my library:

Csv csv = new Csv("\t");//delimiter symbol

csv.FileOpen("c:\\file1.csv");

var row1Cell6Value = csv.Rows[0][5];

csv.AddRow("asdf","asdffffff","5")

csv.FileSave("c:\\file2.csv");

You can find my class by the following link and investigate how it's written:
https://github.com/ukushu/DataExporter

This library code is really fast in work and source code is really short.

PS: In the same time this solution will not work for unity.

PS2: Another solution is to work with library "LINQ-to-CSV". It must also work well. But it's will be bigger.


问:
Why do we need kernel space?
Why do we need separation between kernel space and user space, when every data structure, every memory resource is managed by the kernel even if we create a process in user space? Why do we need such a big architecture?

All the page tables, context switching etc. are managed by the kernel, then why user space? Can we not use only one space and develop all the things over it?

This question may sound weird, but I want to really understand why is it required? If I have to design a completely new OS and I do not perform such division between kernel space and user space, what would be the problem?

Thanks

答:
Your question is not weird at all -- are absolutely correct in you intuition that the kernel space may represent an unnecessary overhead. Indeed, it is overhead that many operating systems do not have. Your OS most likely won't have it either.

The rationale for the extra complexity goes something like this:

We want process/task separation.
We want to make sure that one task doing bad things does not affect another one. This requires that the tasks execute in their respective isolated spaces.

We want similar protection for shared hardware controllers.

A task cannot set up its own boundaries; if that was the case a misbehaving task could purposely break the rules. So we need a third party with higher privileges than what the tasks have, and there is your kernel (or privileged) space.

If the cost of the extra kernel space and separation is too high, either in size or in computation overhead, the operating system will not have those features. Many real-time or embedded systems run in a single space with a single (same) privilege level (the privilege levels are sometimes referred to as protection rings) exactly as you described it.

Title: Why do we need kernel space?


问:
How to find the number of 1's in a binary representation of a number?
From other searches, I found that this problem is called 'Hamming Weight' or 'Population Count'. There are lot of answers out there given with so many statistics?
I need to find the solution in a simple way? Complexity is not a big deal.
Is there any in-built function in JavaScript like Java's Integer.bitCount?

I'm currently doing this as follows.

```<code>var binary = 3;
var original = binary;
var count = 0;
while(binary>0)
{
    binary = binary >> 1 << 1;
    if(original-binary==1)
        count++;
    original = binary >> 1;
    binary = original;
}
</code>```

Is there a better, more simple as well as elegant way for this?

答:
If you want to count 1 digit in binary representation we can use regular expression like this.

number.toString(2).match(/1/g).length

Body:
From other searches, I found that this problem is called 'Hamming Weight' or 'Population Count'. There are lot of answers out there given with so many statistics?
I need to find the solution in a simple way? Complexity is not a big deal.
Is there any in-built function in JavaScript like Java's Integer.bitCount?

I'm currently doing this as follows.

var binary = 3;
var original = binary;
var count = 0;
while(binary>0)
{
    binary = binary >> 1 << 1;
    if(original-binary==1)
        count++;
    original = binary >> 1;
    binary = original;
}

Is there a better, more simple as well as elegant way for this?


问:
PopupMenu with icons
Of course we are dealing here with SDK 11 and above.

I intend to do something similar to this:

Next to each item in that PopupMenu, I would like to place an icon.

I created an XML file and placed it in /menu:

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_one"
        android:title="Sync"
        android:icon="@android:drawable/ic_popup_sync"
        />

    <item
        android:id="@+id/action_two"
        android:title="About"
        android:icon="@android:drawable/ic_dialog_info"
        />
</menu>
</code>```

As you noticed, in the xml file I am defining the icons I want, however, when the popup menu shows, it is showing them without the icons. What should I do to make those 2 icons appear?

答:
list_item_menu.xml in /res/menu directory

```<code><?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

            <item
                android:id="@+id/locale"
                android:title="Localizar"
                android:icon="@mipmap/ic_en_farmacia_ico"
                app:showAsAction="always">
            </item>

            <item android:id="@+id/delete"
                android:title="Eliminar"
                android:icon="@mipmap/ic_eliminar_ico"
                app:showAsAction="always">
            </item>
    </menu>
</code>```

In my activity

```<code>private void showPopupOption(View v){
    PopupMenu popup = new PopupMenu(getContext(), v);
    popup.getMenuInflater().inflate(R.menu.list_item_menu, popup.getMenu());

    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem menu_item) {
            switch (menu_item.getItemId()) {
                case R.id.locale:
                    break;
                case R.id.delete:
                    break;
            }
            return true;
        }
    });

    MenuPopupHelper menuHelper = new MenuPopupHelper(getContext(), (MenuBuilder) popup.getMenu(), v);
    menuHelper.setForceShowIcon(true);
    menuHelper.setGravity(Gravity.END);
    menuHelper.show();
}
</code>```

result

Title: PopupMenu with icons

Body:
Of course we are dealing here with SDK 11 and above.

I intend to do something similar to this:

Next to each item in that PopupMenu, I would like to place an icon.

I created an XML file and placed it in /menu:

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

    <item
        android:id="@+id/action_one"
        android:title="Sync"
        android:icon="@android:drawable/ic_popup_sync"
        />

    <item
        android:id="@+id/action_two"
        android:title="About"
        android:icon="@android:drawable/ic_dialog_info"
        />
</menu>

As you noticed, in the xml file I am defining the icons I want, however, when the popup menu shows, it is showing them without the icons. What should I do to make those 2 icons appear?

Body:
list_item_menu.xml in /res/menu directory

<?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

            <item
                android:id="@+id/locale"
                android:title="Localizar"
                android:icon="@mipmap/ic_en_farmacia_ico"
                app:showAsAction="always">
            </item>

            <item android:id="@+id/delete"
                android:title="Eliminar"
                android:icon="@mipmap/ic_eliminar_ico"
                app:showAsAction="always">
            </item>
    </menu>

In my activity

private void showPopupOption(View v){
    PopupMenu popup = new PopupMenu(getContext(), v);
    popup.getMenuInflater().inflate(R.menu.list_item_menu, popup.getMenu());

    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem menu_item) {
            switch (menu_item.getItemId()) {
                case R.id.locale:
                    break;
                case R.id.delete:
                    break;
            }
            return true;
        }
    });

    MenuPopupHelper menuHelper = new MenuPopupHelper(getContext(), (MenuBuilder) popup.getMenu(), v);
    menuHelper.setForceShowIcon(true);
    menuHelper.setGravity(Gravity.END);
    menuHelper.show();
}

result


问:
After submit a form, stay same page, show a word in the page

After clicking "submit", stay on the page.

Input data, like "computer number" and "profit", stay inside those blank square.

A word "Submitted", appear in the center of this page.

The following is my code, Please help, thank you!

<title></title>

  <form name="form"
onsubmit="return validateForm()">

    Computer Number:

    <input type="text" name="Computer" required>

How much is your profit?

<input id="id1" name = "id1" required>
  <button  type = "button" onclick="myFunction()">My Answer</button>
    <button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>

  <input type="submit" value="Submit">

</form>

```

答:
Hello you should think abut using AJAX as you are sending a form.

This can be the button:

```<code>    <button type="button"
    onclick="validateForm('ajax_info.php', myFunction)"> Clic to Submit
    </button>
</code>```

And this the AJAX function:

      function validateForm(url, cFunction) {
      var xhttp;
      xhttp=new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          cFunction(this);
        }
      };
      xhttp.open("GET", url, true); //can be POST
      xhttp.send();
    }
    function myFunction(xhttp) {
      document.getElementById("submited").innerHTML =
      xhttp.responseText;
    }
```

Body:
Hello you should think abut using AJAX as you are sending a form.

This can be the button:

    <button type="button"
    onclick="validateForm('ajax_info.php', myFunction)"> Clic to Submit
    </button>

And this the AJAX function:

      function validateForm(url, cFunction) {
      var xhttp;
      xhttp=new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          cFunction(this);
        }
      };
      xhttp.open("GET", url, true); //can be POST
      xhttp.send();
    }
    function myFunction(xhttp) {
      document.getElementById("submited").innerHTML =
      xhttp.responseText;
    }


问:
Integrating Sql Server 2005 Databases into Team Foundation Server 2008
Is it Possible to integrate sql server databases into visual studio team foundation server 2008 as all possible circumstances like build making, version control,publishing etc....
and pls make sure that if we integrate this in to a team project combined both code and db in a single project and i would like know how it is possible....?</p>

答: Look at the Red Gate SQL Source Control product. Thats what we use to version our database in TFS.</p>


问:
Best data type for storing currency values in a MySQL database
What is the best SQL data type for currency values?  I'm using MySQL but would prefer a database independent type.</p>

答:
It depends on the nature of data. You need to contemplate it beforehand.

My case

decimal(13,4) unsigned for recording money transactions

storage efficient (4 bytes for each side of decimal point anyway) 1

GAAP compliant

decimal(19,4) unsigned for aggregates

we need more space for totals of multiple multi-billion transactions

semi-compliance with MS Currency data type won't hurt 2

it will take more space per record (11 bytes - 7 left & 4 right), but this is fine as there are fewer records for aggregates 1

decimal(10,5) for exchange rates

they are normally quoted with 5 digits altogether so you could find values like 1.2345 & 12.345 but not 12345.67890

it is widespread convention, but not a codified standard (at least to my quick search knowledge)

you could make it decimal (18,9) with the same storage, but the datatype restrictions are valuable built-in validation mechanism

Why (M,4)?

there are currencies that split into a thousand pennies

there are money equivalents like "Unidad de Fermento", "CLF" expressed with 4 significant decimal places 3,4

it is GAAP compliant

Tradeoff

lower precision:

less storage cost

quicker calculations

lower calculation error risk

quicker backup & restore

higher precision:

future compatibility (numbers tend to grow)

development time savings (you won't have to rebuild half a system when the limits are met)

lower risk of production failure due to insufficient storage precision

Compatible Extreme

Although MySQL lets you use decimal(65,30), 31 for scale and 30 for precision seem to be our limits if we want to leave transfer option open.

Maximum scale and precision in most common RDBMS:

```
            Precision   Scale
Oracle      31          31
T-SQL       38          38
MySQL       65          30
PostgreSQL  131072      16383
```

6, 7, 8, 9

Reasonable Extreme

Why (27,4)?

you never know when the system needs to store Zimbabwean dollars

September 2015 Zimbabwean government stated it would exchange Zimbabwean dollars for US dollars at a rate of 1 USD to 35 quadrillion Zimbabwean dollars 5

We tend to say "yeah, sure... I won't need that crazy figures". Well, Zimbabweans used to say that too. Not to long ago.

Let's imagine you need to record a transaction of 1 mln USD in Zimbabwean dollars (maybe unlikely today, but who knows how this will look like in 10 years from now?).

(1 mln USD) * (35 Quadrylion ZWL) = ( 10^6 ) * (35 * 10^15) = 35 * 10^21

we need:

2 digits to store "35"

21 digits to store the zeros

4 digits to the right of decimal point

this makes decimal(27,4) which costs us 15 bytes for each entry

we may add one more digit on the left at no expense - we have decimal(28,4) for 15 bytes

Now we can store 10 mln USD transaction expressed in Zimbabwean dollars, or secure from another strike of hiperinflation, which hopefully won't happen

OwnerDisplayName: Brian Fisher

Body:
It depends on the nature of data. You need to contemplate it beforehand.

My case

decimal(13,4) unsigned for recording money transactions

storage efficient (4 bytes for each side of decimal point anyway) 1

GAAP compliant

decimal(19,4) unsigned for aggregates

we need more space for totals of multiple multi-billion transactions

semi-compliance with MS Currency data type won't hurt 2

it will take more space per record (11 bytes - 7 left & 4 right), but this is fine as there are fewer records for aggregates 1

decimal(10,5) for exchange rates

they are normally quoted with 5 digits altogether so you could find values like 1.2345 & 12.345 but not 12345.67890

it is widespread convention, but not a codified standard (at least to my quick search knowledge)

you could make it decimal (18,9) with the same storage, but the datatype restrictions are valuable built-in validation mechanism

Why (M,4)?

there are currencies that split into a thousand pennies

there are money equivalents like "Unidad de Fermento", "CLF" expressed with 4 significant decimal places 3,4

it is GAAP compliant

Tradeoff

lower precision:

less storage cost

quicker calculations

lower calculation error risk

quicker backup & restore

higher precision:

future compatibility (numbers tend to grow)

development time savings (you won't have to rebuild half a system when the limits are met)

lower risk of production failure due to insufficient storage precision

Compatible Extreme

Although MySQL lets you use decimal(65,30), 31 for scale and 30 for precision seem to be our limits if we want to leave transfer option open.

Maximum scale and precision in most common RDBMS:

            Precision   Scale
Oracle      31          31
T-SQL       38          38
MySQL       65          30
PostgreSQL  131072      16383

6, 7, 8, 9

Reasonable Extreme

Why (27,4)?

you never know when the system needs to store Zimbabwean dollars

September 2015 Zimbabwean government stated it would exchange Zimbabwean dollars for US dollars at a rate of 1 USD to 35 quadrillion Zimbabwean dollars 5

We tend to say "yeah, sure... I won't need that crazy figures". Well, Zimbabweans used to say that too. Not to long ago.

Let's imagine you need to record a transaction of 1 mln USD in Zimbabwean dollars (maybe unlikely today, but who knows how this will look like in 10 years from now?).

(1 mln USD) * (35 Quadrylion ZWL) = ( 10^6 ) * (35 * 10^15) = 35 * 10^21

we need:

2 digits to store "35"

21 digits to store the zeros

4 digits to the right of decimal point

this makes decimal(27,4) which costs us 15 bytes for each entry

we may add one more digit on the left at no expense - we have decimal(28,4) for 15 bytes

Now we can store 10 mln USD transaction expressed in Zimbabwean dollars, or secure from another strike of hiperinflation, which hopefully won't happen


问:
Why is my Android Studio Generated Signed APK not working on some brands of Android Device?
Been having trouble with this one for weeks and searched throughout forums for solutions.

I have an Android App that can be installed on some brands of devices but won't install on others. On some devices It keeps getting a package error every time i install it.
And in some devices it even hangs just by looking at the APK file.

But if i plug the device that has a package error on the PC and install the apk through android studio, it will install the app.

Is this some kind of hardware problem? Or some kind of hardware compatibility issue?

The brand that i'm sure it will install is Samsung. Brands that it won't install is LG or ASUS.

I already checked the versions and almost all the devices has the same SDK api.

Min-SDK: 15
Target-SDK: 25

I even updated Android Studio and gradle to latest versions.

答:
I had the same issue. I forgot to add same permissions in manifest. I added these permissions in manifest as well as mike said. Then clean and build and worked like a charm.

Conclusion: If you are giving the permissions programmatically in class then make sure the same permissions you must declare in AndroidManifest.xml file.

make sure you have an icon and that the image is no bigger than 60 by 60 pixels

App icon should be png formtat

remove unused images and large size image in the Media Section Now it will be works.


问:
What environment variables can be used with a Docker image?
I'm just learning Docker. If I want to use a particular image from Docker Hub, such as mysql, how do I know what environment variables can be used with that Docker image? Any way to get a list of the available variables?</p>

答:
Two ways to get the list of env variables:

You can checkout Dockerfile and look for ENV or docker run command and look for -e key value.

You can also check what actual env variables are populated in running container by following command -

docker exec -it <container id> env

This will give you a list of all populated env vars in that container.