问:
New variable that connects year and quarter
Hi i am a stata user and i am trying to pass my codes to Pandas. I have a panel data as shown below, and i am looking for a command that can create a constant variable according to which year and quarter the row is located. In stata such command would be reproduced by gen new_variable = yq(year, quarter)

My dataframe look like this

```<code>id     year    quarter
 1    2007          1
 1    2007          2
 1    2007          3
 1    2007          4
 1    2008          1
 1    2008          2
 1    2008          3
 1    2008          4
 1    2009          1
 1    2009          2
 1    2009          3
 1    2009          4
 2    2007          1
 2    2007          2
 2    2007          3
 2    2007          4
 2    2008          1
 2    2008          2
 2    2008          3
 2    2008          4
 3    2009          2
 3    2009          3
 3    2010          2
 3    2010          3
</code>```

I my expected output should look like this: (Values inside new_variable are arbitrary, just looking for a constant value the would be always the same for each year and quarter and consecutives)

```<code>id     year    quarter   new_variable
 1    2007          1     220
 1    2007          2     221
 1    2007          3     222
 1    2007          4     223
 1    2008          1     224
 1    2008          2     225
 1    2008          3     226
 1    2008          4     227
 1    2009          1     228
 1    2009          2     229
 1    2009          3     230
 1    2009          4     231
 2    2007          1     220
 2    2007          2     221
 2    2007          3     222
 2    2007          4     223
 2    2008          1     224
 2    2008          2     225
 2    2008          3     226
 2    2008          4     227
 3    2009          2     229
 3    2009          3     230
 3    2010          2     233
 3    2010          3     234
</code>```

Body:
Hi i am a stata user and i am trying to pass my codes to Pandas. I have a panel data as shown below, and i am looking for a command that can create a constant variable according to which year and quarter the row is located. In stata such command would be reproduced by gen new_variable = yq(year, quarter)

My dataframe look like this

id     year    quarter
 1    2007          1
 1    2007          2
 1    2007          3
 1    2007          4
 1    2008          1
 1    2008          2
 1    2008          3
 1    2008          4
 1    2009          1
 1    2009          2
 1    2009          3
 1    2009          4
 2    2007          1
 2    2007          2
 2    2007          3
 2    2007          4
 2    2008          1
 2    2008          2
 2    2008          3
 2    2008          4
 3    2009          2
 3    2009          3
 3    2010          2
 3    2010          3

I my expected output should look like this: (Values inside new_variable are arbitrary, just looking for a constant value the would be always the same for each year and quarter and consecutives)

id     year    quarter   new_variable
 1    2007          1     220
 1    2007          2     221
 1    2007          3     222
 1    2007          4     223
 1    2008          1     224
 1    2008          2     225
 1    2008          3     226
 1    2008          4     227
 1    2009          1     228
 1    2009          2     229
 1    2009          3     230
 1    2009          4     231
 2    2007          1     220
 2    2007          2     221
 2    2007          3     222
 2    2007          4     223
 2    2008          1     224
 2    2008          2     225
 2    2008          3     226
 2    2008          4     227
 3    2009          2     229
 3    2009          3     230
 3    2010          2     233
 3    2010          3     234

Body:
My solution extends the idea of @johnchase: build a dictionary mapping from the Cartesian product of year by quarter that takes the string representation year + quarter to integers.

ys = df['year'].unique()
qs =  df['quarter'].unique()
new_idx = pd.MultiIndex.from_product([ys, qs], names=['year', 'quarter'])

yq = [''.join([str(a), str(b)]) for a, b in new_idx.values]
# yq
# ['20071', '20072', '20073', '20074',
# '20081', '20082', '20083', '20084',
# '20091', '20092', '20093', '20094',
# '20101', '20102', '20103', '20104']

mapper = {k:i+220 for i, k in enumerate(yq)}

df['new_variable'] = df['year'].astype(str) + df['quarter'].astype(str)
df['new_variable'] = df['new_variable'].map(mapper)

df
    id  year  quarter  new_variable
0    1  2007        1           220
1    1  2007        2           221
2    1  2007        3           222
3    1  2007        4           223
4    1  2008        1           224
5    1  2008        2           225
6    1  2008        3           226
7    1  2008        4           227
8    1  2009        1           228
9    1  2009        2           229
10   1  2009        3           230
11   1  2009        4           231
12   2  2007        1           220
13   2  2007        2           221
14   2  2007        3           222
15   2  2007        4           223
16   2  2008        1           224
17   2  2008        2           225
18   2  2008        3           226
19   2  2008        4           227
20   3  2009        2           229
21   3  2009        3           230
22   3  2010        2           233
23   3  2010        3           234


来源: stackexchange

问:
docker share volumes with glusterfs
I want to test docker in Swarm mode.

I've created 3 Ubuntu-server Virtual Machines.

On each VM I've installed docker.

The next step that I would like to accomplish is to share the /var/lib/docker/volumes folder among the 3 docker nodes.

The first solution I tried is to mount /var/lib/docker/volumes as a remote sshfs volume. I failed because when the docker service starts it executes the command chown on the /var/lib/docker/volumes and it fails.

Then I tried to use glusterfs, I succeded to configure gluster to share the same folder on the 3 nodes (now if I create a file in /var/lib/docker/volumes on the first node, I can see the new file also on the others 2 nodes).

Then I started docker on the first node without any problem. But If I try to start docker on the second node I got the error:

Error starting daemon: error while opening volume store metadata database: timeout

I assume that the error is because the first node acquire the lock on the file /var/lib/doceker/meradata.db

How can I solve this problem?
Is there an alternative to use glusterfs to share the docker volumes folder?

Thank you

答: You shouldn't share this directory at all. It will probably lead to data corruption. As you already have glusterfs configured you can mount gluster dir into container with -v /path/to/gluster/mount:/path/in/container flag added to docker run. Then files written to path in container will be shared among gluster nodes. Other option is to use some dedicated volumes driver for that. Try searching for 'docker volumes drivers' in your favorite search engine.

ContentLicense: CC BY-SA 3.0

Title: docker share volumes with glusterfs


问:
Understanding requests versus grequests
I'm working with a process which is basically as follows:

Take some list of urls.

Get a Response object from each.

Create a BeautifulSoup object from the text of each Response.

Pull the text of a certain tag from that BeautifulSoup object.

From my understanding, this seems ideal for grequests:

GRequests allows you to use Requests with Gevent to make asynchronous
  HTTP Requests easily.

But yet, the two processes (one with requests, one with grequests) seem to be getting me different results, with some of the requests in grequests returning None rather than a response.

Using requests

```<code>import requests

tickers = [
    'A', 'AAL', 'AAP', 'AAPL', 'ABBV', 'ABC', 'ABT', 'ACN', 'ADBE', 'ADI',
    'ADM',  'ADP', 'ADS', 'ADSK', 'AEE', 'AEP', 'AES', 'AET', 'AFL', 'AGN',
    'AIG', 'AIV', 'AIZ', 'AJG', 'AKAM', 'ALB', 'ALGN', 'ALK', 'ALL', 'ALLE',
    ]

BASE = 'https://finance.google.com/finance?q={}'

rs = (requests.get(u) for u in [BASE.format(t) for t in tickers])
rs = list(rs)

rs
# [<Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # ...
 # <Response [200]>]

# All are okay (status_code == 200)
</code>```

Using grequests

```<code># Restarted my interpreter and redefined `tickers` and `BASE`
import grequests

rs = (grequests.get(u) for u in [BASE.format(t) for t in tickers])
rs = grequests.map(rs)

rs
# [None,
 # <Response [200]>,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>]
</code>```

Why the difference in results?

Update: I can print the exception type as follows.  Related discussion here but I have no idea what's going on.

```<code>def exception_handler(request, exception):
    print(exception)

rs = grequests.map(rs, exception_handler=exception_handler)

# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
</code>```

System/version info

requests: 2.18.4

grequests: 0.3.0

Python: 3.6.3

urllib3: 1.22

pyopenssl: 17.2.0

All via Anaconda

System: same issue on both Mac OSX HS & Windows 10, build 10.0.16299

答:
I do not know the exact reason for the observed behavior with .map(). However, using the .imap() function with size=1 always returned a 'Response 200' for my few minutes testing. Here is the code snipet:

```<code>rs = (grequests.get(u) for u in [BASE.format(t) for t in tickers])
rsm_iterator = grequests.imap(rs, exception_handler=exception_handler, size=1)
rsm_list = [r for r in rsm_iterator]
print(rsm_list)
</code>```

And if you don't want to wait for all requests to finish before working on their answers, you can do this like so:

```<code>rs = (grequests.get(u) for u in [BASE.format(t) for t in tickers])
rsm_iterator = grequests.imap(rs, exception_handler=exception_handler, size=1)
for r in rsm_iterator:
    print(r)
</code>```

Title: Understanding requests versus grequests

Body:
I'm working with a process which is basically as follows:

Take some list of urls.

Get a Response object from each.

Create a BeautifulSoup object from the text of each Response.

Pull the text of a certain tag from that BeautifulSoup object.

From my understanding, this seems ideal for grequests:

GRequests allows you to use Requests with Gevent to make asynchronous
  HTTP Requests easily.

But yet, the two processes (one with requests, one with grequests) seem to be getting me different results, with some of the requests in grequests returning None rather than a response.

Using requests

import requests

tickers = [
    'A', 'AAL', 'AAP', 'AAPL', 'ABBV', 'ABC', 'ABT', 'ACN', 'ADBE', 'ADI',
    'ADM',  'ADP', 'ADS', 'ADSK', 'AEE', 'AEP', 'AES', 'AET', 'AFL', 'AGN',
    'AIG', 'AIV', 'AIZ', 'AJG', 'AKAM', 'ALB', 'ALGN', 'ALK', 'ALL', 'ALLE',
    ]

BASE = 'https://finance.google.com/finance?q={}'

rs = (requests.get(u) for u in [BASE.format(t) for t in tickers])
rs = list(rs)

rs
# [<Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # ...
 # <Response [200]>]

# All are okay (status_code == 200)

Using grequests

# Restarted my interpreter and redefined `tickers` and `BASE`
import grequests

rs = (grequests.get(u) for u in [BASE.format(t) for t in tickers])
rs = grequests.map(rs)

rs
# [None,
 # <Response [200]>,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # None,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>,
 # <Response [200]>]

Why the difference in results?

Update: I can print the exception type as follows.  Related discussion here but I have no idea what's going on.

def exception_handler(request, exception):
    print(exception)

rs = grequests.map(rs, exception_handler=exception_handler)

# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
# ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)

System/version info

requests: 2.18.4

grequests: 0.3.0

Python: 3.6.3

urllib3: 1.22

pyopenssl: 17.2.0

All via Anaconda

System: same issue on both Mac OSX HS & Windows 10, build 10.0.16299

Body:
I do not know the exact reason for the observed behavior with .map(). However, using the .imap() function with size=1 always returned a 'Response 200' for my few minutes testing. Here is the code snipet:

rs = (grequests.get(u) for u in [BASE.format(t) for t in tickers])
rsm_iterator = grequests.imap(rs, exception_handler=exception_handler, size=1)
rsm_list = [r for r in rsm_iterator]
print(rsm_list)

And if you don't want to wait for all requests to finish before working on their answers, you can do this like so:

rs = (grequests.get(u) for u in [BASE.format(t) for t in tickers])
rsm_iterator = grequests.imap(rs, exception_handler=exception_handler, size=1)
for r in rsm_iterator:
    print(r)


问:
Html table not taking up full width of window
All of my other tables seem to take up the full width of the window, as I would like them to, and I can't figure out why this one isn't. The html seems to be the same as the other tables. I think the error is occurring within the  element but when looking at it it seems to be set up properly. The code below is the code for the first table on the page in the screenshot.
Screenshot of table</p>

```<code><body>
  <nav class="navbar navbar-expand-md navbar-dark bg-primary">
  </nav>
  <div class="container">
    <div class="row">
      <ul class="nav nav-tabs nav-justified" id="auth-tabs" role="tablist">
          <li class="nav-item"><a href="#users" id="active" class="nav-link  users" role="tab" aria-controls="users" aria-selected="True" data-toggle="tab">
          Users</a></li>
          <li class="nav-item"><a href="#groups" id="" class="nav-link groups" role="tab" aria-controls="groups" aria-selected="false" data-toggle="tab">
          Groups</a></li>
          <li class="nav-item"><a href="#scopes" id="" class="nav-link  scopes" role="tab" aria-controls="scopes" aria-selected="False" data-toggle="tab">
          Scopes</a></li>
          <li class="nav-item"><a href="#navigation" id="" class="nav-link navigation active" role="tab" aria-controls="navigation" aria-selected="true" data-toggle="tab">
          Navigation</a></li>
          <li class="nav-item"><a href="#pages" id="" class="nav-link  pages" role="tab" aria-controls="pages" aria-selected="False" data-toggle="tab">
          Pages</a></li>
          <li class="nav-item"><a href="#permissions" id="" class="nav-link  permissions" role="tab" aria-controls="permissions" aria-selected="False" data-toggle="tab">
          Permissions</a></li>
        </ul>
      </div>
      <div class="tab-content" id="auth-tabs">
        <div id="users" class="tab-pane fade" role="tabpanel" aria-labeledby="users">
          <div class='row'>
            <div class="col-md-12">
                <h4>Authentication
                    <small>Navbar</small>
                    <button class="btn btn-sm btn-primary pull-right" onclick="app.auth.navigation.new_nav()">
                        <i class="fa fa-plus">
                        </i>
                        Add to Navbar
                    </button>
                </h4>
                <hr>
                <div class="row">
                    <table class="table Navbar" id="navbar-table" width="100%">
                       <thead>
                          <tr>
                            <th></th>
                            <th>Id</th>
                            <th>Page id</th>
                            <th>Name</th>
                            <th>Icon</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr id="Navbar-7">
                            <td><button class="btn btn-link table-btn" onclick="app.auth.navigation.form({"primary_key": 7})">
                                Edit
                                </button><button class="btn btn-link table-btn" onclick="app.auth.navigation.confirm_delete({"name": "srjys", "primary_key": 7})">
                                Delete
                                </button>
                            </td>
                            <td>7</td>
                            <td>8</td>
                            <td>srjys</td>
                            <td>il;t7;t</td>
                          </tr>
                          <tr id="Navbar-2">
                            <td><button class="btn btn-link table-btn" onclick="app.auth.navigation.form({"primary_key": 2})">
                                Edit
                                </button><button class="btn btn-link table-btn" onclick="app.auth.navigation.confirm_delete({"name": "Jtyed", "primary_key": 2})">
                                Delete
                                </button>
                              </td>
                              <td>2</td>
                              <td>8</td>
                              <td>Jtyed</td>
                              <td>agrfds</td>
                            </tr>
                          </tbody>
                      </table>
                  </div>
                </div>
            </div>
        </div>
      </div>
  </div>
</body>

body {
  background-color: #F5F5F5;
}

.account-wall {
    margin-top: 75px;
    padding: 20px 20px 20px 20px;
        padding-top: 20px;
    background-color: #fff;
    -moz-box-shadow: 1px 2px 2px rgba(0, 0, 0, 0.3);
    -webkit-box-shadow: 1px 2px 2px rgba(0, 0, 0, 0.3);
    box-shadow: 1px 2px 2px rgba(0, 0, 0, 0.3);
}

.form-control {
    width: 100%;
    height: 34px;
    padding: 6px 12px;
    background-color: #fff;
    border: 1px solid #ccc;
    border-radius: 4px;
        border-bottom-right-radius: 4px;
        border-bottom-left-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
    box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
    -webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
    -o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
    transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
}

.form-signin {
  max-width: 330px;
  padding: 0;
}

.buttons {
  padding-top: 10px;
}

.form-group {
  margin-bottom: 0;
}

.form-signin input[type="text"],
.form-signin input[type="password"],
.form-signin input[type="email"] {
    margin-bottom: -1px;
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
    font-size: 14px;
}

.small-link {
  font-size: 14;
}

.margin-top {
  margin-top: 20px;
}

.bounds-label {
  padding-right: 0;
}

.bounds {
  padding-left: 0;
  padding-right: 0;
}

.table-btn {
  padding-top: 0px;
  padding-bottom: 0px;
}
</code>```

答: The problem is I gave my table a class of 'Navbar' for js reference purposes, but that is also the name of a bootstrap class.</p>

Body:
All of my other tables seem to take up the full width of the window, as I would like them to, and I can't figure out why this one isn't. The html seems to be the same as the other tables. I think the error is occurring within the  element but when looking at it it seems to be set up properly. The code below is the code for the first table on the page in the screenshot.
Screenshot of table

          Users

          Groups

          Scopes

          Navigation

          Pages

          Permissions

Authentication
                    Navbar
                    <button class="btn btn-sm btn-primary pull-right" onclick="app.auth.navigation.new_nav()">

                        Add to Navbar
                    </button>

                            Id
                            Page id
                            Name
                            Icon

                            <button class="btn btn-link table-btn" onclick="app.auth.navigation.form({"primary_key": 7})">
                                Edit
                                </button><button class="btn btn-link table-btn" onclick="app.auth.navigation.confirm_delete({"name": "srjys", "primary_key": 7})">
                                Delete
                                </button>

                            7
                            8
                            srjys
                            il;t7;t

                            <button class="btn btn-link table-btn" onclick="app.auth.navigation.form({"primary_key": 2})">
                                Edit
                                </button><button class="btn btn-link table-btn" onclick="app.auth.navigation.confirm_delete({"name": "Jtyed", "primary_key": 2})">
                                Delete
                                </button>

                              2
                              8
                              Jtyed
                              agrfds

body {
  background-color: #F5F5F5;
}

.account-wall {
    margin-top: 75px;
    padding: 20px 20px 20px 20px;
        padding-top: 20px;
    background-color: #fff;
    -moz-box-shadow: 1px 2px 2px rgba(0, 0, 0, 0.3);
    -webkit-box-shadow: 1px 2px 2px rgba(0, 0, 0, 0.3);
    box-shadow: 1px 2px 2px rgba(0, 0, 0, 0.3);
}

.form-control {
    width: 100%;
    height: 34px;
    padding: 6px 12px;
    background-color: #fff;
    border: 1px solid #ccc;
    border-radius: 4px;
        border-bottom-right-radius: 4px;
        border-bottom-left-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
    box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
    -webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
    -o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
    transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
}

.form-signin {
  max-width: 330px;
  padding: 0;
}

.buttons {
  padding-top: 10px;
}

.form-group {
  margin-bottom: 0;
}

.form-signin input[type="text"],
.form-signin input[type="password"],
.form-signin input[type="email"] {
    margin-bottom: -1px;
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
    font-size: 14px;
}

.small-link {
  font-size: 14;
}

.margin-top {
  margin-top: 20px;
}

.bounds-label {
  padding-right: 0;
}

.bounds {
  padding-left: 0;
  padding-right: 0;
}

.table-btn {
  padding-top: 0px;
  padding-bottom: 0px;
}


问:
Subsetting a dataset into multiples subsets in R
I have a data that looks something like this:

```<code>structure(list(ID = structure(c(1L, 2L, 2L, 3L, 4L, 5L, 6L, 6L,
6L), .Label = c("a", "b", "c", "d", "e", "f"), class = "factor"),
    Value = c(10L, 13L, 12L, 43L, 23L, 66L, 78L, 42L, 19L)), .Names = c("ID",
"Value"), class = "data.frame", row.names = c(NA, -9L))
</code>```

I would like to divide this dataset into multiple datasets on the basis of the ID values, i.e. one dataset that contains only ID = a, another that contains only ID = b, and so on.

How do I do this subsetting automatically in R? I understand that if the number of values in ID is less, we could just do it manually, but in case there are a lot of values under ID, there has to be a smarter way of doing this.

答:
This should be pretty easy.

```<code>exampleb <- subset(df, ID == 'b')

exampleb
  ID Value
2  b    13
3  b    12
</code>```

Also, take a look at these links.

https://www.r-bloggers.com/5-ways-to-subset-a-data-frame-in-r/

https://www.statmethods.net/management/subset.html

Body:
I have a data that looks something like this:

structure(list(ID = structure(c(1L, 2L, 2L, 3L, 4L, 5L, 6L, 6L,
6L), .Label = c("a", "b", "c", "d", "e", "f"), class = "factor"),
    Value = c(10L, 13L, 12L, 43L, 23L, 66L, 78L, 42L, 19L)), .Names = c("ID",
"Value"), class = "data.frame", row.names = c(NA, -9L))

I would like to divide this dataset into multiple datasets on the basis of the ID values, i.e. one dataset that contains only ID = a, another that contains only ID = b, and so on.

How do I do this subsetting automatically in R? I understand that if the number of values in ID is less, we could just do it manually, but in case there are a lot of values under ID, there has to be a smarter way of doing this.

Body:
This should be pretty easy.

exampleb <- subset(df, ID == 'b')

exampleb
  ID Value
2  b    13
3  b    12

Also, take a look at these links.

https://www.r-bloggers.com/5-ways-to-subset-a-data-frame-in-r/

https://www.statmethods.net/management/subset.html


问:
What Is The Title of This Type of Program
In the same vein that; a graphical program someone uses is called a GUI (Graphical User Interface), a program that talks with machinery and displays statuses to an operator are called an HMI (Human Machine Interface), a program that uses a console is called a console application, what would the appropriate title for a program that runs on computer and boots at startup and only allows users to interact with the program and not whats underneath? Similar to banking software or the checkout software at grocery stores.

It will be on a Raspberry PI with a touchscreen and as soon as the PI powers on, it will load this program that covers the whole screen and doesn't allow the user to interact with the PI through desktop or console.

EDIT

I am wanting to study up on best practices for this type of program, I just don't know WHAT to search for.

答:
For a very general description: What you are looking for is an Input/Output System (IOS) it manages what the computer sees from the users input. All programs are Input/Output Systems, what you are describing is closer to a High Level "Basic Input Output System"(BIOS) that all computers use to start a computer, it starts at launch in all computers before the operating system is run, your program starts after the operating system starts. A fitting definition would be an Advanced Input/Output System or (AIOS)

Side Note: A Graphical User Interface or (GUI) describes the visual portion of software on a given system. It is a device or program enabling a user to communicate with a computer. All software needs to have a GUI, including you Advanced Input/Output System (AIOS)


问:
Html.DropDownListFor set selected value
I create a @Html.DropDownListFor and populate it from the database. How can I set a selected value to the drop down?

My View:

```<code>@Html.DropDownListFor(m => m.Forms, new SelectList(Model.Forms, "FormsCreatorID", "FormName"),
            "Select a Form", new { @class = "form-control" })
</code>```

My Controller:

```<code>var forms = db.formscreators.Where(fp => fp.PropertyID == id || fp.PropertyID == 0)
            .OrderByDescending(x => x.PropertyID).GroupBy(x => x.FormName).Select(x => x.FirstOrDefault()).ToList();
var viewModel = new ListFormsCreator { Forms = forms };
</code>```

My ViewModel:

```<code>public class ListFormsCreator
{
    public List<formscreator> Forms { get; set; }
}
</code>```

My Database Model:

```<code>public partial class formscreator
{
    public int FormsCreatorID { get; set; }
    public string FormName { get; set; }
    public int PropertyID { get; set; }
}
</code>```

Thanks

答:
Conform with C#/.NET naming conventions:

Rename formscreator to FormsCreator

Replace ID with Id (as it's an abbreviation, not an initialism)

Rename ListFormsCreator to something like ListFormsCreatorViewModel so it's obvious it's a ViewModel type and not a Model/Entity type.

Modify your ViewModel to add a property to store the selected FormsCreatorId value:

```<code>public class ListFormsCreatorViewModel
{
    [Required] // add or remove the 'Required' attribute as necessary
    public int? SelectedFormsCreatorId { get; set; }

    ...
}
</code>```

Set the SelectedFormsCreatorId property value in your controller action if necessary if you know what the value should be.

In your POST handler, ensure the SelectedFormsCreatorId value is maintained, either by directly passing-through the model action parameter back through the View(Object viewModel) method or manually repopulating it.

The view-model property in DropDownListFor should be the SelectedFormsCreatorId property. You do not need new SelectList(...)

```<code>@Html.DropDownListFor( m => m.SelectedFormsCreatorId, this.Model.Forms );
</code>```

Title: Html.DropDownListFor set selected value

Body:
I create a @Html.DropDownListFor and populate it from the database. How can I set a selected value to the drop down?

My View:

@Html.DropDownListFor(m => m.Forms, new SelectList(Model.Forms, "FormsCreatorID", "FormName"),
            "Select a Form", new { @class = "form-control" })

My Controller:

var forms = db.formscreators.Where(fp => fp.PropertyID == id || fp.PropertyID == 0)
            .OrderByDescending(x => x.PropertyID).GroupBy(x => x.FormName).Select(x => x.FirstOrDefault()).ToList();
var viewModel = new ListFormsCreator { Forms = forms };

My ViewModel:

public class ListFormsCreator
{
    public List<formscreator> Forms { get; set; }
}

My Database Model:

public partial class formscreator
{
    public int FormsCreatorID { get; set; }
    public string FormName { get; set; }
    public int PropertyID { get; set; }
}

Thanks

Body:
Conform with C#/.NET naming conventions:

Rename formscreator to FormsCreator

Replace ID with Id (as it's an abbreviation, not an initialism)

Rename ListFormsCreator to something like ListFormsCreatorViewModel so it's obvious it's a ViewModel type and not a Model/Entity type.

Modify your ViewModel to add a property to store the selected FormsCreatorId value:

public class ListFormsCreatorViewModel
{
    [Required] // add or remove the 'Required' attribute as necessary
    public int? SelectedFormsCreatorId { get; set; }

    ...
}

Set the SelectedFormsCreatorId property value in your controller action if necessary if you know what the value should be.

In your POST handler, ensure the SelectedFormsCreatorId value is maintained, either by directly passing-through the model action parameter back through the View(Object viewModel) method or manually repopulating it.

The view-model property in DropDownListFor should be the SelectedFormsCreatorId property. You do not need new SelectList(...)

@Html.DropDownListFor( m => m.SelectedFormsCreatorId, this.Model.Forms );


问:
local MAMP Pro redirect to https
I have installed Mamp Pro to run my local host and it has been working great for a year or so but recently when I start it up and go to one of my hosts it redirects to a https connection and throws an error:

"Safari Can't Open Page.  Safari can't open page because Safari can't establish a secure connection to the server."

It works fine in Chrome but Safari is giving me issues.  I've restarted my computer, restarted MAMP and nothing has worked so far.  Any help would be greatly appreciated.

答: Do you have installed the update to MacOS 10.13.2? After upgrading to this version no website on localhost can be started. Every host redirects to a https connection.</p>

Title: local MAMP Pro redirect to https


问:
HTTP Status 404 - Not Found - Servlet and JSP
I'm working on one web app. I have problem when I want to test my servlet.
When I run my servlet error pops up -

HTTP Status 404 - Not Found.

I search another similar problems but i can't find solution. I think that there is no connection between my servlet and jsp file. Below my code:

GetServletController

```<code>    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Adam
 */
public class GetServletController extends HttpServlet {

//    private HandsDBUtil handsDBUtil;
//
//    private ServletConfig config = getServletConfig();
//    private ServletContext context = config.getServletContext();
//
//    private String user = null;
//    private String pass = null;
//    private String c_name = null;
//    private String url = null;
//    @Override
//    public void init() throws ServletException {
//        super.init();
//        Enumeration enumeration = context.getInitParameterNames();
//        while (enumeration.hasMoreElements()) {
//            String name = (String) enumeration.nextElement();
//            switch (name) {
//                case "url":
//                    url = context.getInitParameter(name);
//                    break;
//                case "pass":
//                    pass = context.getInitParameter(name);
//                    break;
//                case "user":
//                    user = context.getInitParameter(name);
//                    break;
//                case "c_name":
//                    c_name = context.getInitParameter(name);
//                    break;
//            }
//        }
//
//        handsDBUtil = new HandsDBUtil(user, pass, c_name, url);
//
//    }
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/plain; charset=ISO-8859-2");

        PrintWriter out = response.getWriter();

        out.println("WOW");

        HandsDBUtil handsDBUtil;

        ServletConfig config = getServletConfig();
        ServletContext context = config.getServletContext();

        String user = null;
        String pass = null;
        String c_name = null;
        String url = null;

        Enumeration enumeration = context.getInitParameterNames();
        while (enumeration.hasMoreElements()) {
            String name = (String) enumeration.nextElement();
            switch (name) {
                case "url":
                    url = context.getInitParameter(name);
                    break;
                case "pass":
                    pass = context.getInitParameter(name);
                    break;
                case "user":
                    user = context.getInitParameter(name);
                    break;
                case "c_name":
                    c_name = context.getInitParameter(name);
                    break;
            }
        }

        handsDBUtil = new HandsDBUtil(user, pass, c_name, url);

        out.println("wow");
        out.println(user);
        try {
            //listHands(request, response);
            List<Hand> hands = handsDBUtil.getHands();
            System.out.println(hands);
            request.setAttribute("HAND_LIST", hands);

            RequestDispatcher dispatcher = request.getRequestDispatcher("getHands");
            dispatcher.forward(request, response);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }
    }

//    private void listHands(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, Exception {
//
//        List<Hand> hands = handsDBUtil.getHands();
//
//        request.setAttribute("HAND_LIST", hands);
//
//        RequestDispatcher dispatcher = request.getRequestDispatcher("getHands");
//        dispatcher.forward(request, response);
//
//    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
</code>```

jsp

```<code><%@page import="java.util.*, Servlets.GetServletController, Servlets.Hand" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Poker Hands List</title>
    </head>

    <form action="GetServletController"/>

    <%

        List<Hand> theHands = (List<Hand>) request.getAttribute("HAND_LIST");
        %>

    <body>

        <%= theHands %>

        <div id="wrapper">
            <div id="header">
                <h2>
                    Poker Hands List
                </h2>
            </div>
        </div>

        <div id="container">
            <div id="content">

            </div>
        </div>
    </body>
</html>
</code>```

web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:derby://localhost:1527/lab</param-value>
    </context-param>
    <context-param>
        <param-name>c_name</param-name>
        <param-value>org.apache.derby.jdbc.ClientDriver</param-value>
    </context-param>
    <context-param>
        <param-name>user</param-name>
        <param-value>lab</param-value>
    </context-param>
    <context-param>
        <param-name>pass</param-name>
        <param-value>lab</param-value>
    </context-param>
    <servlet>
        <servlet-name>ServletTest</servlet-name>
        <servlet-class>Servlets.ServletTest</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>GetServletController</servlet-name>
        <servlet-class>Servlets.GetServletController</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletTest</servlet-name>
        <url-pattern>/ServletTest</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>GetServletController</servlet-name>
        <url-pattern>/GetServletController</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>getHands.jsp</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>mainMenu.jsp</welcome-file>
    </welcome-file-list>
</web-app>
</code>```

答:
Request dispatcher is used to dispatch request to any resources,such as HTML, Image, JSP, Servlet on the server. If you want to forward your request to a jsp you need to define like below

```<code> RequestDispatcher dispatcher = request.getRequestDispatcher("getHands.jsp");
</code>```

In your case you are forwarding the request to a servlet.

```<code>RequestDispatcher dispatcher = request.getRequestDispatcher("getHands");
</code>```

There is no such servlet defined in your web.xml

That's why you are getting 404 error

Body:
I'm working on one web app. I have problem when I want to test my servlet.
When I run my servlet error pops up -

HTTP Status 404 - Not Found.

I search another similar problems but i can't find solution. I think that there is no connection between my servlet and jsp file. Below my code:

GetServletController

    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Adam
 */
public class GetServletController extends HttpServlet {

//    private HandsDBUtil handsDBUtil;
//
//    private ServletConfig config = getServletConfig();
//    private ServletContext context = config.getServletContext();
//
//    private String user = null;
//    private String pass = null;
//    private String c_name = null;
//    private String url = null;
//    @Override
//    public void init() throws ServletException {
//        super.init();
//        Enumeration enumeration = context.getInitParameterNames();
//        while (enumeration.hasMoreElements()) {
//            String name = (String) enumeration.nextElement();
//            switch (name) {
//                case "url":
//                    url = context.getInitParameter(name);
//                    break;
//                case "pass":
//                    pass = context.getInitParameter(name);
//                    break;
//                case "user":
//                    user = context.getInitParameter(name);
//                    break;
//                case "c_name":
//                    c_name = context.getInitParameter(name);
//                    break;
//            }
//        }
//
//        handsDBUtil = new HandsDBUtil(user, pass, c_name, url);
//
//    }
    /**
     * Processes requests for both HTTP GET and POST
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/plain; charset=ISO-8859-2");

        PrintWriter out = response.getWriter();

        out.println("WOW");

        HandsDBUtil handsDBUtil;

        ServletConfig config = getServletConfig();
        ServletContext context = config.getServletContext();

        String user = null;
        String pass = null;
        String c_name = null;
        String url = null;

        Enumeration enumeration = context.getInitParameterNames();
        while (enumeration.hasMoreElements()) {
            String name = (String) enumeration.nextElement();
            switch (name) {
                case "url":
                    url = context.getInitParameter(name);
                    break;
                case "pass":
                    pass = context.getInitParameter(name);
                    break;
                case "user":
                    user = context.getInitParameter(name);
                    break;
                case "c_name":
                    c_name = context.getInitParameter(name);
                    break;
            }
        }

        handsDBUtil = new HandsDBUtil(user, pass, c_name, url);

        out.println("wow");
        out.println(user);
        try {
            //listHands(request, response);
            List<Hand> hands = handsDBUtil.getHands();
            System.out.println(hands);
            request.setAttribute("HAND_LIST", hands);

            RequestDispatcher dispatcher = request.getRequestDispatcher("getHands");
            dispatcher.forward(request, response);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }
    }

//    private void listHands(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, Exception {
//
//        List<Hand> hands = handsDBUtil.getHands();
//
//        request.setAttribute("HAND_LIST", hands);
//
//        RequestDispatcher dispatcher = request.getRequestDispatcher("getHands");
//        dispatcher.forward(request, response);
//
//    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

jsp

<%@page import="java.util.*, Servlets.GetServletController, Servlets.Hand" %>
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Poker Hands List</title>

    <form action="GetServletController"/>

    <%

        List<Hand> theHands = (List<Hand>) request.getAttribute("HAND_LIST");
        %>

        <%= theHands %>

                    Poker Hands List

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:derby://localhost:1527/lab</param-value>
    </context-param>
    <context-param>
        <param-name>c_name</param-name>
        <param-value>org.apache.derby.jdbc.ClientDriver</param-value>
    </context-param>
    <context-param>
        <param-name>user</param-name>
        <param-value>lab</param-value>
    </context-param>
    <context-param>
        <param-name>pass</param-name>
        <param-value>lab</param-value>
    </context-param>
    <servlet>
        <servlet-name>ServletTest</servlet-name>
        <servlet-class>Servlets.ServletTest</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>GetServletController</servlet-name>
        <servlet-class>Servlets.GetServletController</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletTest</servlet-name>
        <url-pattern>/ServletTest</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>GetServletController</servlet-name>
        <url-pattern>/GetServletController</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>getHands.jsp</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>mainMenu.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Body:
Request dispatcher is used to dispatch request to any resources,such as HTML, Image, JSP, Servlet on the server. If you want to forward your request to a jsp you need to define like below

 RequestDispatcher dispatcher = request.getRequestDispatcher("getHands.jsp");

In your case you are forwarding the request to a servlet.

RequestDispatcher dispatcher = request.getRequestDispatcher("getHands");

There is no such servlet defined in your web.xml

That's why you are getting 404 error


问:
Keeping all libraries in the Arduino sketch directory
I know that you are supposed to place any external libraries under the "libraries" folder of the arduino install directory, but I have a project that uses several libraries that I have created for the project and mainly to keep all that code self contained and out of the main pde file.  However, I have tried to place the libraries in the same directory as the main PDE file so that I can more easily keep everything synced up in subversion (I work on this on multiple computers) and I don't want to have to keep going back and syncing up the libraries separately.  Also, just for the sake of being able to easily zip of the sketch folder and know that it contains everything it needs.

I've tried adding the header files to the sketch as a new tab, but that doesn't seem to work at all... don't even care if they should up in the arduino IDE.

I've also tried adding the libraries to the sketch directory in subdirectories (what I would greatly prefer) and then linking to them as:

```<code>#include "mylib/mylib.h"
</code>```

and

```<code>#include <mylib/mylib.h>
</code>```

But both of these result in file not found errors.

Is this possible? And, if so, how do I include them in the main file for building? Preferably in their own subdirectories.

答: For the sketches I have, the "*.h" and "*.cpp" library files actually reside in the same folder as the sketch, and I call them like "someheader.h". I also noticed that if I go into sketch menu and add file... that the file doesn't appear until I close and reopen the sketch.

ContentLicense: CC BY-SA 2.5

Body:
I know that you are supposed to place any external libraries under the "libraries" folder of the arduino install directory, but I have a project that uses several libraries that I have created for the project and mainly to keep all that code self contained and out of the main pde file.  However, I have tried to place the libraries in the same directory as the main PDE file so that I can more easily keep everything synced up in subversion (I work on this on multiple computers) and I don't want to have to keep going back and syncing up the libraries separately.  Also, just for the sake of being able to easily zip of the sketch folder and know that it contains everything it needs.

I've tried adding the header files to the sketch as a new tab, but that doesn't seem to work at all... don't even care if they should up in the arduino IDE.

I've also tried adding the libraries to the sketch directory in subdirectories (what I would greatly prefer) and then linking to them as:

#include "mylib/mylib.h"

and

#include <mylib/mylib.h>

But both of these result in file not found errors.

Is this possible? And, if so, how do I include them in the main file for building? Preferably in their own subdirectories.


问:
How do I identify a string using a wildcard using R?
I'd like to count the duration of some words containing the number "0" after a string, as shown in the picture (I inserted a red dot under the words with the character I'd like to work with).
Is there anything like a wildcard so that I can work only with the words containing this string?

[Picture]

答:
The code below does work and it is basically what I need.

```<code>resultado2[grep('0',resultado2$TextGridLabel),]
</code>```

However, I would like to avoid data such as S10XXXXXXX in TextGridLabel. I have just edited the original post so that the new picture illustrates better what I'd like to consider.

ContentLicense: CC BY-SA 4.0

Body:
The code below does work and it is basically what I need.

resultado2[grep('0',resultado2$TextGridLabel),]

However, I would like to avoid data such as S10XXXXXXX in TextGridLabel. I have just edited the original post so that the new picture illustrates better what I'd like to consider.


答:
You should add another property to your view model for the store/pass the selected option.

```<code>public class ListFormsCreator
{
    public int SelectedFormId  { set;get;}
    public List<formscreator> Forms { get; set; }
}
</code>```

Now in your GET action, you can set that value

```<code>var viewModel = new ListFormsCreator() { Forms = forms };
viewModel.SelectedFormId  = 2 ; // This will select the option with 2 as FormsCreatorID
return View(viewModel);
</code>```

And in the view use the lambda expression with that property as the first parameter of the DropDownListFor helper method.

```<code>@model ListFormsCreator

@Html.DropDownListFor(m => m.SelectedFormId  ,
                         new SelectList(Model.Forms, "FormsCreatorID", "FormName"),
                        "Select a Form", new { @class = "form-control" })
</code>```

The DropDownListFor helper method will use the value of SelectedFormId property and select the option which has the same value attribute value from the list of options of that SELECT element.

You can also remove the dependency on formscreator class from the view model, by replacing it with a list of SelectListItem

```<code>public class ListFormsCreator
{
    public int SelectedFormId  { set;get;}
    public List<SelectListItem> Forms { get; set; }
}
</code>```

Now in your GET action, you can use the Select method to generate the lsit of SelectListItem from your other collection.

```<code>var viewModel = new ListFormsCreator();
viewModel.Forms = someCollection.Select(a=>new SelectListItem {
                                           Value=a.FormsCreatorId.ToString(),
                                           Text=a.FormName})
                 .ToList();
viewModel.SelectedFormId  = 2 ; // This will select the option with 2 as FormsCreatorID
return View(viewModel);
</code>```

Assuming someCollection is a collection of formscreator objects
Now in the view code is much simpler

```<code>@Html.DropDownListFor(m => m.SelectedFormId, Model.Forms ,"Select a Form")
</code>```

Title: Html.DropDownListFor set selected value

Body:
You should add another property to your view model for the store/pass the selected option.

public class ListFormsCreator
{
    public int SelectedFormId  { set;get;}
    public List<formscreator> Forms { get; set; }
}

Now in your GET action, you can set that value

var viewModel = new ListFormsCreator() { Forms = forms };
viewModel.SelectedFormId  = 2 ; // This will select the option with 2 as FormsCreatorID
return View(viewModel);

And in the view use the lambda expression with that property as the first parameter of the DropDownListFor helper method.

@model ListFormsCreator

@Html.DropDownListFor(m => m.SelectedFormId  ,
                         new SelectList(Model.Forms, "FormsCreatorID", "FormName"),
                        "Select a Form", new { @class = "form-control" })

The DropDownListFor helper method will use the value of SelectedFormId property and select the option which has the same value attribute value from the list of options of that SELECT element.

You can also remove the dependency on formscreator class from the view model, by replacing it with a list of SelectListItem

public class ListFormsCreator
{
    public int SelectedFormId  { set;get;}
    public List<SelectListItem> Forms { get; set; }
}

Now in your GET action, you can use the Select method to generate the lsit of SelectListItem from your other collection.

var viewModel = new ListFormsCreator();
viewModel.Forms = someCollection.Select(a=>new SelectListItem {
                                           Value=a.FormsCreatorId.ToString(),
                                           Text=a.FormName})
                 .ToList();
viewModel.SelectedFormId  = 2 ; // This will select the option with 2 as FormsCreatorID
return View(viewModel);

Assuming someCollection is a collection of formscreator objects
Now in the view code is much simpler

@Html.DropDownListFor(m => m.SelectedFormId, Model.Forms ,"Select a Form")


问:
Nested conditional throwing an error
I have a column of integers from three digits to five digits.  I want to output a column of six characters (czCode) with the appropriate number of leading zeros depending on the input integer.

```<code>a <- seq(100, 50000, 1)
df1 <- data.frame(a)
View(df1)

myZero <- '0'
dblZero <- '00'
triZero <- '000'

a <- mutate(a, czCode = as.character(a))

df1$a <- ifelse(df1$a < 1000, paste(triZero, df1$czCode, sep = ""),
                ifelse(df1$a >= 1000 & df1$a < 10000, paste(dblZero, df1$czCode, sep = ""),
                ifelse(df1$a >= 10000, paste(myZero, df1$a, sep = "")),
                ))
</code>```

So 100 would output as "000100"

and 1000 would output as "001000"

and 10000 would output as "010000"

But I keep getting the following error:

Error in ifelse(df1$a >= 1000 & df1$a < 10000, paste(dblZero, df1$czCode,  :

      unused argument ()

答:
I think you are missing last argument of last if-else. I tried something like this, it worked for me:-</p>

```<code>df1$a <- ifelse(df1$a < 1000, paste(triZero, df1$czCode, sep = ""),
            ifelse(df1$a >= 1000 & df1$a < 10000, paste(dblZero, df1$czCode, sep = ""),
                   ifelse(df1$a >= 10000, paste(myZero, df1$a, sep = ""), F)
              ))
</code>```

Title: Nested conditional throwing an error

Body:
I have a column of integers from three digits to five digits.  I want to output a column of six characters (czCode) with the appropriate number of leading zeros depending on the input integer.

a <- seq(100, 50000, 1)
df1 <- data.frame(a)
View(df1)

myZero <- '0'
dblZero <- '00'
triZero <- '000'

a <- mutate(a, czCode = as.character(a))

df1$a <- ifelse(df1$a < 1000, paste(triZero, df1$czCode, sep = ""),
                ifelse(df1$a >= 1000 & df1$a < 10000, paste(dblZero, df1$czCode, sep = ""),
                ifelse(df1$a >= 10000, paste(myZero, df1$a, sep = "")),
                ))

So 100 would output as "000100"

and 1000 would output as "001000"

and 10000 would output as "010000"

But I keep getting the following error:

Error in ifelse(df1$a >= 1000 & df1$a < 10000, paste(dblZero, df1$czCode,  :

      unused argument ()

Body:
I think you are missing last argument of last if-else. I tried something like this, it worked for me:-

df1$a <- ifelse(df1$a < 1000, paste(triZero, df1$czCode, sep = ""),
            ifelse(df1$a >= 1000 & df1$a < 10000, paste(dblZero, df1$czCode, sep = ""),
                   ifelse(df1$a >= 10000, paste(myZero, df1$a, sep = ""), F)
              ))


问:
Checking hgrc file into Mercurial
I have a project using mercurial for version control, SCons to build, and google test to write unit tests. The hgrc file hooks pre-commit and runs SCons to build the project and and run unit tests. Is there a way to "check-in" a portion of the hgrc file so that newly checked out copies, and any merges with my version of the project automatically get an hgrc file that runs SCons when they try to commit?</p>

答:
You can't get people to automatically have entries in their .hg/hgrc when they clone -- doing so would make it possible for someone to put rm -rf ~ in a commit hook, and wouldn't that be a bummer for the erstwhile cloners.

What you can do is include a file named something like mandatory.hgrc outside of the 'hg directory and then tell cloners to put this line in their .hg/hgrc:

```<code>%include ../mandatory.hgrc
</code>```

Though that's still showing an awful lot of trust in you.

If you control the machines, as in many corporate settings, you can have your package/deployment/update tools (we use puppet) put whatever you want in their /etc/mercurial/hgrc file.

Title: Checking hgrc file into Mercurial

Body:
You can't get people to automatically have entries in their .hg/hgrc when they clone -- doing so would make it possible for someone to put rm -rf ~ in a commit hook, and wouldn't that be a bummer for the erstwhile cloners.

What you can do is include a file named something like mandatory.hgrc outside of the 'hg directory and then tell cloners to put this line in their .hg/hgrc:

%include ../mandatory.hgrc

Though that's still showing an awful lot of trust in you.

If you control the machines, as in many corporate settings, you can have your package/deployment/update tools (we use puppet) put whatever you want in their /etc/mercurial/hgrc file.


问:
In R, auto.arima fails to capture seasonality
auto.arima() is giving me no seasonal component for my series, even though I can see that there is one present. The function gives me a non seasonal ARIMA model of order (5,0,0). So, when I try to forecast using that model, it just gives the mean. The time series is of daily minimum temperatures in Melbourne, Australia for ten years.

Click this link to see the data and the auto.arima forecast

`

```<code>library(readr)

temp <- read_csv("~/Downloads/Melbourne Minimum Temp.csv",
                 col_types = cols(Date = col_date(format = "%m/%d/%y"),
                                  Temp = col_number()))

t <- ts(temp$Temp, start = temp$Date\[1], end = temp$Date[nrow(temp)])

auto.arima(t, trace = T)
</code>```

`

Tried using the data as a ts object, as an xts object, and as a vector.

答:
Just reporting a good well explained - as usual - blogpost by Rob Hyndman.

https://robjhyndman.com/hyndsight/dailydata/

The relevant part to your question says (blockquoting exactly the page):

When the time series is long enough to take in more than a year, then
  it may be necessary to allow for annual seasonality as well as weekly
  seasonality. In that case, a multiple seasonal model such as TBATS is
  required.

```<code>y <- msts(x, seasonal.periods=c(7,365.25))
fit <- tbats(y)
fc <- forecast(fit)
plot(fc)
</code>```

This should capture the weekly pattern as well as the longer annual
  pattern. The period 365.25 is the average length of a year allowing
  for leap years. In some countries, alternative or additional year
  lengths may be necessary.

I think it does exactly what you want.

I also tried to simply create the time series with msts

```<code>y <- msts(x[1:1800], seasonal.periods=c(7,365.25))
</code>```

(I cut the time series in half to be quicker)

and then run auto.arima() directly on it, forcing a seasonal component with D=1

```<code>fc = auto.arima(y,D=1,trace=T,stepwise = F)
</code>```

it will take a while.. because I set stepwise = FALSE (if you want it to look at all combinations without shortcuts you can set approximation=FALSE as well)

```<code>Series: y
ARIMA(1,0,3)(0,1,0)[365]

Coefficients:
         ar1      ma1      ma2      ma3
      0.9036  -0.3647  -0.3278  -0.0733
s.e.  0.0500   0.0571   0.0405   0.0310

sigma^2 estimated as 12.63:  log likelihood=-3854.1
AIC=7718.19   AICc=7718.23   BIC=7744.54
</code>```

and then the forecast

```<code>for_fc = forecast(fc)
plot(for_fc)
</code>```

I am adding a figure with the complete time series (red) on top of the output of
    plot(for_fc)
and it seems to work decently - but it was just a quick test.

Body:
auto.arima() is giving me no seasonal component for my series, even though I can see that there is one present. The function gives me a non seasonal ARIMA model of order (5,0,0). So, when I try to forecast using that model, it just gives the mean. The time series is of daily minimum temperatures in Melbourne, Australia for ten years.

Click this link to see the data and the auto.arima forecast

`

library(readr)

temp <- read_csv("~/Downloads/Melbourne Minimum Temp.csv",
                 col_types = cols(Date = col_date(format = "%m/%d/%y"),
                                  Temp = col_number()))

t <- ts(temp$Temp, start = temp$Date\[1], end = temp$Date[nrow(temp)])

auto.arima(t, trace = T)

`

Tried using the data as a ts object, as an xts object, and as a vector.

Body:
Just reporting a good well explained - as usual - blogpost by Rob Hyndman.

https://robjhyndman.com/hyndsight/dailydata/

The relevant part to your question says (blockquoting exactly the page):

When the time series is long enough to take in more than a year, then
  it may be necessary to allow for annual seasonality as well as weekly
  seasonality. In that case, a multiple seasonal model such as TBATS is
  required.

y <- msts(x, seasonal.periods=c(7,365.25))
fit <- tbats(y)
fc <- forecast(fit)
plot(fc)

This should capture the weekly pattern as well as the longer annual
  pattern. The period 365.25 is the average length of a year allowing
  for leap years. In some countries, alternative or additional year
  lengths may be necessary.

I think it does exactly what you want.

I also tried to simply create the time series with msts

y <- msts(x[1:1800], seasonal.periods=c(7,365.25))

(I cut the time series in half to be quicker)

and then run auto.arima() directly on it, forcing a seasonal component with D=1

fc = auto.arima(y,D=1,trace=T,stepwise = F)

it will take a while.. because I set stepwise = FALSE (if you want it to look at all combinations without shortcuts you can set approximation=FALSE as well)

Series: y
ARIMA(1,0,3)(0,1,0)[365]

Coefficients:
         ar1      ma1      ma2      ma3
      0.9036  -0.3647  -0.3278  -0.0733
s.e.  0.0500   0.0571   0.0405   0.0310

sigma^2 estimated as 12.63:  log likelihood=-3854.1
AIC=7718.19   AICc=7718.23   BIC=7744.54

and then the forecast

for_fc = forecast(fc)
plot(for_fc)

I am adding a figure with the complete time series (red) on top of the output of
    plot(for_fc)
and it seems to work decently - but it was just a quick test.


问:
pg_restore clean table psql

I am trying to restore a table I dumped to its current location. The table was dumped using:

```<code>pg_dump -t table db > table.sql -U username
</code>```

Trying to restore, I'm using:

```<code>pg_restore -c --dbname=db --table=table table.sql
</code>```

I am using -c since the table currently exists and has data, however it returns:

```<code>pg_restore: [archiver] input file appears to be a text format dump. Please use psql.
</code>```

I've also tried:

```<code>-bash-4.2$ psql -U username -d db -1 -f table.sql
</code>```

But since the data is there already and there's no --clean option for this psql command (I believe), it returns:

```<code>psql:table.sql:32: ERROR:  relation "table" already exists
</code>```

Is there a way to use pg_restore correctly or use psql with a --clean option?

答:
Bad news for you, friend. You can’t pg_restore from a plan-text dump. It’s in the docs:

“pg_restore is a utility for restoring a PostgreSQL database from an archive created by pg_dump in one of the non-plain-text formats.” https://www.postgresql.org/docs/9.6/static/app-pgrestore.html

If you can re-execute pg_dump, you can do so with the -Fc flag, which will produce an artifact that you can restore with pg_restore. If you are stuck with the table.sql in plain-text format, you do have a few options (I’m calling your target table my_fancy_table in the two examples below):

Option 1:

Drop the table: drop table my_fancy_table;

Now run your psql command: psql <options> -f table.sql

If you have referential integrity where other tables necessitate rows being there, you might not be able to drop the table.

Option 2:
Upsert from a temp table

You can edit the sql file (since it’s in plain text) and change the table name to my_fancy_table_temp (or any table name that does not yet exist). Now you'll have two tables, a temp one from the sql file and the real one that's been there the whole time. You can then write some upsert SQL to insert or update the real table with the rows from the temp table like so:

```<code>insert into my_facy_table (column1, column2)
select column1, column2 from my_fancy_table_temp
on conflict (my_fancy_unique_index)
update my_fancy_table
set column1 = excluded.column1,
 column2 = excluded.column2
</code>```

Title: pg_restore clean table psql

Body:
I am trying to restore a table I dumped to its current location. The table was dumped using:

pg_dump -t table db > table.sql -U username

Trying to restore, I'm using:

pg_restore -c --dbname=db --table=table table.sql

I am using -c since the table currently exists and has data, however it returns:

pg_restore: [archiver] input file appears to be a text format dump. Please use psql.

I've also tried:

-bash-4.2$ psql -U username -d db -1 -f table.sql

But since the data is there already and there's no --clean option for this psql command (I believe), it returns:

psql:table.sql:32: ERROR:  relation "table" already exists

Is there a way to use pg_restore correctly or use psql with a --clean option?

Body:
Bad news for you, friend. You can’t pg_restore from a plan-text dump. It’s in the docs:

“pg_restore is a utility for restoring a PostgreSQL database from an archive created by pg_dump in one of the non-plain-text formats.” https://www.postgresql.org/docs/9.6/static/app-pgrestore.html

If you can re-execute pg_dump, you can do so with the -Fc flag, which will produce an artifact that you can restore with pg_restore. If you are stuck with the table.sql in plain-text format, you do have a few options (I’m calling your target table my_fancy_table in the two examples below):

Option 1:

Drop the table: drop table my_fancy_table;

Now run your psql command: psql <options> -f table.sql

If you have referential integrity where other tables necessitate rows being there, you might not be able to drop the table.

Option 2:
Upsert from a temp table

You can edit the sql file (since it’s in plain text) and change the table name to my_fancy_table_temp (or any table name that does not yet exist). Now you'll have two tables, a temp one from the sql file and the real one that's been there the whole time. You can then write some upsert SQL to insert or update the real table with the rows from the temp table like so:

insert into my_facy_table (column1, column2)
select column1, column2 from my_fancy_table_temp
on conflict (my_fancy_unique_index)
update my_fancy_table
set column1 = excluded.column1,
 column2 = excluded.column2


问:
saving downloads to the browser download rather than system using java
I have a dynamic web project in my eclipse that takes an excel sheet with data and puts in a database.  Then from the database, I created a web app for the users to add, edit, delete and view the data in that database that was once on a spreadsheet.

The web app takes the data that was created, edited, deleted from the user and creates an excel spreadsheet upon the users request.  I created a link that writes the excel spreadsheet, but how would I make the new spreadsheet download to the users computer.

So if they click the link for download, it would go to the browser download, such as the browser they are using(for example in chrome), the file goes to the download bar on the bottom of the screen.  I been researching and I am just lost.  I am using java:

```<code>try{
   File file = new File("C:\\eclipseworkspace\\spreatdsheet.xlsx");

          if(file.delete()){
                    System.out.println(file.getName() + " will be overwritten, created");
                }else{
                    System.out.println(file.getName() + " does not exist.  Newly created.");
                }
        }catch(Exception e){
            e.printStackTrace();
        }

    FileOutputStream out = new FileOutputStream(newFile("C:\\eclipseworkspace\\spreatdsheet.xlsx"));

    workbook.write(out);
    out.close();
    workbook.close();
    System.out.println("spreadsheet .xlsx was created");
</code>```

This is the part of my java code, that imports the Apache POI classes, and writes it to the dynamic web project's directory in eclipse.

What would I have to or where would I need to start so that the spreadsheet in the directory can be downloaded into the users browser download such as chrome://downloads/ in chrome browser

答:
I suppose that you are testing this web app on the same machine as the one where you see the file into your Downloads.

You cannot write anything on the client machine from a web app. The sample code that you provide is to write a file on the server filesystem. Not the client.

What you must do is write the content of your file into the http response. If you are working with servlets it is something like

```<code>public void doGet(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // Instrcut the browser of what he will receive
    response.getOutputStream().write(/* your excel*/);
}
</code>```

That way, the browser will download it in his default folder (that you cannot change)

Body:
I have a dynamic web project in my eclipse that takes an excel sheet with data and puts in a database.  Then from the database, I created a web app for the users to add, edit, delete and view the data in that database that was once on a spreadsheet.

The web app takes the data that was created, edited, deleted from the user and creates an excel spreadsheet upon the users request.  I created a link that writes the excel spreadsheet, but how would I make the new spreadsheet download to the users computer.

So if they click the link for download, it would go to the browser download, such as the browser they are using(for example in chrome), the file goes to the download bar on the bottom of the screen.  I been researching and I am just lost.  I am using java:

try{
   File file = new File("C:\\eclipseworkspace\\spreatdsheet.xlsx");

          if(file.delete()){
                    System.out.println(file.getName() + " will be overwritten, created");
                }else{
                    System.out.println(file.getName() + " does not exist.  Newly created.");
                }
        }catch(Exception e){
            e.printStackTrace();
        }

    FileOutputStream out = new FileOutputStream(newFile("C:\\eclipseworkspace\\spreatdsheet.xlsx"));

    workbook.write(out);
    out.close();
    workbook.close();
    System.out.println("spreadsheet .xlsx was created");

This is the part of my java code, that imports the Apache POI classes, and writes it to the dynamic web project's directory in eclipse.

What would I have to or where would I need to start so that the spreadsheet in the directory can be downloaded into the users browser download such as chrome://downloads/ in chrome browser

Body:
I suppose that you are testing this web app on the same machine as the one where you see the file into your Downloads.

You cannot write anything on the client machine from a web app. The sample code that you provide is to write a file on the server filesystem. Not the client.

What you must do is write the content of your file into the http response. If you are working with servlets it is something like

public void doGet(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // Instrcut the browser of what he will receive
    response.getOutputStream().write(/* your excel*/);
}

That way, the browser will download it in his default folder (that you cannot change)


问:
C++ code gets strangely skipped with no optimizations. Any ideas why?
I looked for an answer for two days to this with no success. I've never come across this problem before so I'll try my best. Please bear with me.

I returned to a C++ project I created over a year ago, which at the time ran without problems. I came across this interesting and incredibly annoying problem the other day as I was trying to get the same program to run. The code was something like:

file.h

```<code>...
short id;
...
</code>```

file.cc

```<code>id = 0;
while (id < some_large_number)
{
   id = foo();
   if (id == 2)
   {
      //do something
   }
   else if (id == 2900)
   {
      //do something
   }
   else if (id == 30000)
   {
      //do something
   }
   else if (id == 40000)
   {
      //do something
   }
   else if (id == 45000)
   {
      //do something
   }
   else
   {
      //do something else
   }
}
</code>```

The constant numbers were macros in hex notation that I expanded for this example. Turns out that this was truly a bug, but the debugger did not make it easy to discover. Heres what happened:

As I was trying to step through the code using GDB (with no optimizations), I noticed that GDB would jump straight to the else statement after reaching if (id == 30000), everytime. Because the numbers were c macros in hex notation, I did not notice at first that 40000 was beyond the limit of a signed short. This was very misleading, and spent hours trying to figure it out: I recompiled external libraries, reinstalled g++, among other things.

Obviously, making id an unsigned short fixed the problem. The other problem seems like a compiler issue. But I still don't understand, why were those sections of code completely skipped during execution, and with no optimizations? Why would it not go through each if statement and that way I could identify the real problem? Any ideas?

Thanks so much. I hope this is okay for a first question.

答: If you enable all the warnings from gcc, it will tell you at compile time that this is going to happen.</p>

Body:
I looked for an answer for two days to this with no success. I've never come across this problem before so I'll try my best. Please bear with me.

I returned to a C++ project I created over a year ago, which at the time ran without problems. I came across this interesting and incredibly annoying problem the other day as I was trying to get the same program to run. The code was something like:

file.h

...
short id;
...

file.cc

id = 0;
while (id < some_large_number)
{
   id = foo();
   if (id == 2)
   {
      //do something
   }
   else if (id == 2900)
   {
      //do something
   }
   else if (id == 30000)
   {
      //do something
   }
   else if (id == 40000)
   {
      //do something
   }
   else if (id == 45000)
   {
      //do something
   }
   else
   {
      //do something else
   }
}

The constant numbers were macros in hex notation that I expanded for this example. Turns out that this was truly a bug, but the debugger did not make it easy to discover. Heres what happened:

As I was trying to step through the code using GDB (with no optimizations), I noticed that GDB would jump straight to the else statement after reaching if (id == 30000), everytime. Because the numbers were c macros in hex notation, I did not notice at first that 40000 was beyond the limit of a signed short. This was very misleading, and spent hours trying to figure it out: I recompiled external libraries, reinstalled g++, among other things.

Obviously, making id an unsigned short fixed the problem. The other problem seems like a compiler issue. But I still don't understand, why were those sections of code completely skipped during execution, and with no optimizations? Why would it not go through each if statement and that way I could identify the real problem? Any ideas?

Thanks so much. I hope this is okay for a first question.


答:
Update your viewModel and add an Int SelectId for the dropdown selected value.

In your controller:

```<code>var viewModel = new ListFormsCreator { SelectId = PropertyId, Forms = FormSelectList(forms, PropertyId.ToString()) };
</code>```

I would create a function passing in a list:

```<code>    public static SelectList FormSelectList(IEnumerable<formscreators> types, string selected = null)
    {
        return new SelectList(from f in forms
                              select new SelectListItem
                              {
                                  Text = f.FormName,
                                  Value = f.FormsCreatorID.ToString()
                              }, "Value", "Text", selected);

    }
</code>```

And in your .cshtml

```<code>@Html.DropDownListFor(m => m.PropertyId, Model.forms, "Select a Form", new { @class = "form-control", required = "required" })
</code>```

Title: Html.DropDownListFor set selected value

Body:
I create a @Html.DropDownListFor and populate it from the database. How can I set a selected value to the drop down?

My View:

@Html.DropDownListFor(m => m.Forms, new SelectList(Model.Forms, "FormsCreatorID", "FormName"),
            "Select a Form", new { @class = "form-control" })

My Controller:

var forms = db.formscreators.Where(fp => fp.PropertyID == id || fp.PropertyID == 0)
            .OrderByDescending(x => x.PropertyID).GroupBy(x => x.FormName).Select(x => x.FirstOrDefault()).ToList();
var viewModel = new ListFormsCreator { Forms = forms };

My ViewModel:

public class ListFormsCreator
{
    public List<formscreator> Forms { get; set; }
}

My Database Model:

public partial class formscreator
{
    public int FormsCreatorID { get; set; }
    public string FormName { get; set; }
    public int PropertyID { get; set; }
}

Thanks

Body:
Update your viewModel and add an Int SelectId for the dropdown selected value.

In your controller:

var viewModel = new ListFormsCreator { SelectId = PropertyId, Forms = FormSelectList(forms, PropertyId.ToString()) };

I would create a function passing in a list:

    public static SelectList FormSelectList(IEnumerable<formscreators> types, string selected = null)
    {
        return new SelectList(from f in forms
                              select new SelectListItem
                              {
                                  Text = f.FormName,
                                  Value = f.FormsCreatorID.ToString()
                              }, "Value", "Text", selected);

    }

And in your .cshtml

@Html.DropDownListFor(m => m.PropertyId, Model.forms, "Select a Form", new { @class = "form-control", required = "required" })


问:
Why imported module function that is used once is called twice?
I'm trying to create a Config module that contains function options(). That function gives the user specific options and allows them to type in which option they have chosen, then stores keyboard input into a variable that is used in other modules I have made. The code for the Config module is this:

def options():
   choices = {'1': 'Graph API Data', '2': 'Comparative Graphs', '3': 'Exit'}
   for choice, option in sorted(choices.items(), key=lambda x: x[0]):
       print(choice, option)
   Choice = eval(input('Select what you want to do'))
   return Choice

    opt_number = options()
```

<p>This module is called by another script:</p>

```import Config as conf

conf.options()
```

I want to assign Choice value to opt_number, but opt_number = options() causes the config module to be called twice when it's being called only once by my other script.

What actions should I take to eliminate calling function options() twice?

答:
You should read more about python modules.

You are importing module, which already calls that function by initializing, if you would remove line

```<code>conf.options()
</code>```

from your another script, this should stop calling your function twice, it only would call that function once. Another way is to remove line

```<code>opt_number = options()
</code>```

from the module Config.py.

Also, many other ways exists, for example using opt_number = options() in another function, so it wouldn't call options() until you would call that function. For example:

```<code>def take_action():
    opt_number = options()
</code>```

inside Config.py module would initialize opt_number and call options() function only when conf.take_action() would be called in another script.

Body:
I'm trying to create a Config module that contains function options(). That function gives the user specific options and allows them to type in which option they have chosen, then stores keyboard input into a variable that is used in other modules I have made. The code for the Config module is this:

def options():
   choices = {'1': 'Graph API Data', '2': 'Comparative Graphs', '3': 'Exit'}
   for choice, option in sorted(choices.items(), key=lambda x: x[0]):
       print(choice, option)
   Choice = eval(input('Select what you want to do'))
   return Choice

    opt_number = options()

This module is called by another script:

import Config as conf

conf.options()

I want to assign Choice value to opt_number, but opt_number = options() causes the config module to be called twice when it's being called only once by my other script.

What actions should I take to eliminate calling function options() twice?

Body:
You should read more about python modules.

You are importing module, which already calls that function by initializing, if you would remove line

conf.options()

from your another script, this should stop calling your function twice, it only would call that function once. Another way is to remove line

opt_number = options()

from the module Config.py.

Also, many other ways exists, for example using opt_number = options() in another function, so it wouldn't call options() until you would call that function. For example:

def take_action():
    opt_number = options()

inside Config.py module would initialize opt_number and call options() function only when conf.take_action() would be called in another script.


问:
Test if a promise is resolved or rejected with Jasmine in Nodejs
I know how to do it in Mocha but want to know how to do it with Jasmine.
I tried this

describe('test promise with jasmine', function() {
    it('expects a rejected promise', function() {
        var promise = getRejectedPromise();

        // return expect(promise).toBe('rejected');
        return expect(promise.inspect().state).toBe('rejected');
    });
});
```

However, the state is always pending and, of course, the test fails. I couldn't find any example online that I could make it work.

Can someone please help me with this?

Thanks.

答:
jasmine 2.7 onwards supports returning promises, and would have its fulfilled state tested.

To test for rejection:

```<code>it('test promise with jasmine', async () => {
    try {
        await getRejectedPromise();
    } catch (err) {
        return;
    }

    throw new Error('Promise should not be resolved');
});
</code>```

or yet:

```<code>it('test promise with jasmine', async () => {
    await getRejectedPromise()
        .then(
            () => Promise.reject(new Error('Promise should not be resolved')),
            () => {});
});
</code>```

To verify the actual message, besides the usual instanceof/toBe(), place inside the catch:

```<code>expect(() => { throw err }).toThrow(new MyCustomError('Custom error message'));
</code>```

The benefit from this approach is to have a nicer fail message on the test output.

Expected function to throw MyCustomError: Custom error message, but it threw Another error message.

Somewhat better than the usual output.

To test for resolved (can't be simpler):

```<code>it('test promise with jasmine', async () => {
    await getRejectedPromise();
});
</code>```

Body:
I know how to do it in Mocha but want to know how to do it with Jasmine.
I tried this

describe('test promise with jasmine', function() {
    it('expects a rejected promise', function() {
        var promise = getRejectedPromise();

        // return expect(promise).toBe('rejected');
        return expect(promise.inspect().state).toBe('rejected');
    });
});

However, the state is always pending and, of course, the test fails. I couldn't find any example online that I could make it work.

Can someone please help me with this?

Thanks.

Body:
jasmine 2.7 onwards supports returning promises, and would have its fulfilled state tested.

To test for rejection:

it('test promise with jasmine', async () => {
    try {
        await getRejectedPromise();
    } catch (err) {
        return;
    }

    throw new Error('Promise should not be resolved');
});

or yet:

it('test promise with jasmine', async () => {
    await getRejectedPromise()
        .then(
            () => Promise.reject(new Error('Promise should not be resolved')),
            () => {});
});

To verify the actual message, besides the usual instanceof/toBe(), place inside the catch:

expect(() => { throw err }).toThrow(new MyCustomError('Custom error message'));

The benefit from this approach is to have a nicer fail message on the test output.

Expected function to throw MyCustomError: Custom error message, but it threw Another error message.

Somewhat better than the usual output.

To test for resolved (can't be simpler):

it('test promise with jasmine', async () => {
    await getRejectedPromise();
});


问:
How to access screen display’s DPI settings via javascript?
Is there a way to access the screen display's DPI settings in a Javascript function?

I am trying to position a HTML panel on the page and when the user's DPI is set to large (120), it throws the position off.  I need to be able to know what the DPI is so I can adjust the position accordingly.

答:
There isn't a way that I know of, however, they may be an alternative solution:

Specify your measurements in 'pt' and 'em', which are screen relative metrics.

http://www.w3schools.com/cssref/css_units.asp

https://css-tricks.com/the-lengths-of-css/

em:

  1em is equal to the current font size. 2em means 2 times the size of the current font. E.g., if an element is displayed with a font of 12 pt, then '2em' is 24 pt. The 'em' is a very useful unit in CSS, since it can adapt automatically to the font that the reader uses

pt:

  point (1 pt is the same as 1/72 inch)

pc:

  pica (1 pc is the same as 12 points)

OwnerDisplayName: Yttrium

OwnerDisplayName: Kent Fredric