问:
Getting the size of a groupby operation in Pandas
I've been performing a groupby operation on a dataframe I have that aggregates columns together based on the column 'Name':

```<code>Name | As | Bs | Cs   |  Note
Mark   3     4     7     Good
Luke   2     1     12    Well
Mark   5     6     8     Ok
John   1     18    3     Great
</code>```

So in this case, the rows with 'Mark' are aggregated together on columns A,B, and C using this code:

```<code>temp_df = temp_df.groupby(['Name'], as_index=False).agg({'As': np.sum, 'Bs': np.sum,'Cs': np.sum})
</code>```

A thing I need to add in is to do a count on the number of rows that have the same value in 'Name'. This would give me an output like:

```<code>Name | As | Bs | Cs   |  Note   | Count
Mark   8     10    15    Good      2
Luke   2     1     12    Well      1
John   1     18    3     Great     1
</code>```

How do I modify the above line of code to do what I need?

答:
Create the group and do your aggregations:

```<code>the_group = temp_df.groupby(['Name'], as_index=False)
temp_df = the_group.agg({'As': np.sum, 'Bs': np.sum,'Cs': np.sum})
</code>```

then compute the size from the_group

```<code>temp_df['count'] = the_group.count()['Note']
</code>```

gives:

```<code>   Name  Cs  As  Bs  count
0  John   3   1  18      1
1  Luke  12   2   1      1
2  Mark  15   8  10      2
</code>```

Edit:

As suggested in the comments, it is safer to use size() in case the data include NaN:

```<code>temp_df['count'] = the_group.size().reset_index()[0]
</code>```

Body:
I've been performing a groupby operation on a dataframe I have that aggregates columns together based on the column 'Name':

Name | As | Bs | Cs   |  Note
Mark   3     4     7     Good
Luke   2     1     12    Well
Mark   5     6     8     Ok
John   1     18    3     Great

So in this case, the rows with 'Mark' are aggregated together on columns A,B, and C using this code:

temp_df = temp_df.groupby(['Name'], as_index=False).agg({'As': np.sum, 'Bs': np.sum,'Cs': np.sum})

A thing I need to add in is to do a count on the number of rows that have the same value in 'Name'. This would give me an output like:

Name | As | Bs | Cs   |  Note   | Count
Mark   8     10    15    Good      2
Luke   2     1     12    Well      1
John   1     18    3     Great     1

How do I modify the above line of code to do what I need?

Body:
Create the group and do your aggregations:

the_group = temp_df.groupby(['Name'], as_index=False)
temp_df = the_group.agg({'As': np.sum, 'Bs': np.sum,'Cs': np.sum})

then compute the size from the_group

temp_df['count'] = the_group.count()['Note']

gives:

   Name  Cs  As  Bs  count
0  John   3   1  18      1
1  Luke  12   2   1      1
2  Mark  15   8  10      2

Edit:

As suggested in the comments, it is safer to use size() in case the data include NaN:

temp_df['count'] = the_group.size().reset_index()[0]


来源: stackexchange

问:
Algorithm - How to delete duplicate elements in a Haskell list
I'm having a problem creating an function similar to the nub function.

I need this func to remove duplicated elements form a list.
An element is duplicated when 2 elements have the same email, and it should keep the newer one (is closer to the end of the list).

```<code>type Regist = [name,email,,...,date]
type ListRe = [Regist]

rmDup ListRe -> ListRe
rmDup [] = []
rmDup [a] = [a]
rmDup (h:t) | isDup h (head t) = rmDup t
            | otherwise = h : rmDup t

isDup :: Regist -> Regist -> Bool
isDup (a:b:c:xs) (d:e:f:ts) = b==e
</code>```

The problem is that the function doesn't delete duplicated elements unless they are together in the list.

答:
Just use nubBy, and specify an equality function that compares things the way you want.

And I guess reverse the list a couple of times if you want to keep the last element instead of the first.

ContentLicense: CC BY-SA 3.0

Body:
I'm having a problem creating an function similar to the nub function.

I need this func to remove duplicated elements form a list.
An element is duplicated when 2 elements have the same email, and it should keep the newer one (is closer to the end of the list).

type Regist = [name,email,,...,date]
type ListRe = [Regist]

rmDup ListRe -> ListRe
rmDup [] = []
rmDup [a] = [a]
rmDup (h:t) | isDup h (head t) = rmDup t
            | otherwise = h : rmDup t

isDup :: Regist -> Regist -> Bool
isDup (a:b:c:xs) (d:e:f:ts) = b==e

The problem is that the function doesn't delete duplicated elements unless they are together in the list.

ContentLicense: CC BY-SA 2.5


问:
Handle Exception in ResponsesEntity java
I wonder how to handle exception in ResponsesEntity.
When it receive wrong url, it supposes to go to the catch block and display the log. But I keep getting error message in console. The try-catch not working as it not display log message.

```<code>@GetMapping("abc/{Id}")
    public ResponseEntity info(@PathVariable("Id") String id) {
        HttpEntity httpEntity = new HttpEntity(buildHttpHeaders());
        String theUrl = url + "/xxx/transactions/" +id;
        ResponseEntity<TDto> responseEntity = restTemplate.exchange(theUrl, HttpMethod.GET, httpEntity, TDto.class);
        TDto tdto = responseEntity.getBody();
        Tran tran = new Tran();
        try {
              tran.setDate(new Date());
              tran.saveAndFlush(tran); // save to database
        }catch(Exception e)
        {
            log.info("Log: "+e);
        }
        return responseEntity;
    }
</code>```

Error

```<code>org.springframework.web.client.HttpClientErrorException: 404 Not Found
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
    at com.rh.tranglo.controller.ApiController.retrieveTransactionInfo(ApiController.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
</code>```

Is there a way to handle exception by displaying the log in catch block?

答: Try specifying the exact error you get from the console in the catch, aka-HttpClientErrorException</p>

ContentLicense: CC BY-SA 4.0

Body:
I wonder how to handle exception in ResponsesEntity.
When it receive wrong url, it supposes to go to the catch block and display the log. But I keep getting error message in console. The try-catch not working as it not display log message.

@GetMapping("abc/{Id}")
    public ResponseEntity info(@PathVariable("Id") String id) {
        HttpEntity httpEntity = new HttpEntity(buildHttpHeaders());
        String theUrl = url + "/xxx/transactions/" +id;
        ResponseEntity<TDto> responseEntity = restTemplate.exchange(theUrl, HttpMethod.GET, httpEntity, TDto.class);
        TDto tdto = responseEntity.getBody();
        Tran tran = new Tran();
        try {
              tran.setDate(new Date());
              tran.saveAndFlush(tran); // save to database
        }catch(Exception e)
        {
            log.info("Log: "+e);
        }
        return responseEntity;
    }

Error

org.springframework.web.client.HttpClientErrorException: 404 Not Found
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
    at com.rh.tranglo.controller.ApiController.retrieveTransactionInfo(ApiController.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)

Is there a way to handle exception by displaying the log in catch block?


问:
Can't add type to dictionary
The code is somewhat contrived of course, but here goes. My pretty straight forward dictionary:

```<code>public class ValidatorRepository // BusinessRuleValidator implements IBusinessRuleValidator
{
    public static Dictionary<ValidationAttribute, BusinessRuleValidator> Repo
       = new Dictionary<ValidationAttribute, BusinessRuleValidator>();
}
</code>```

Some custom attribute:

```<code>public class MySuperAttribute : ValidationAttribute
</code>```

Some validator:

```<code>public class MySuperValidator : BusinessRuleValidator
</code>```

However:

```<code>  ValidatorRepository.Repo.Add(MySuperAttribute, typeof(MySuperValidator));
</code>```

Only works for the second object, the first one complains:

MySuperAttribute' is a type, which is not valid in the given context

Tried putting typeof() around it to no success. Now it's been a hellish long day and I'm probably just missing something utterly stupod, but please help. I really can't see what's wrong :(

答:
Dictionary<ValidationAttribute, BusinessRuleValidator>

It's expecting an instance of ValidationAttribute as the key, and an instance of BusinessRuleValidator as the value.

Title: Can't add type to dictionary

Body:
The code is somewhat contrived of course, but here goes. My pretty straight forward dictionary:

public class ValidatorRepository // BusinessRuleValidator implements IBusinessRuleValidator
{
    public static Dictionary<ValidationAttribute, BusinessRuleValidator> Repo
       = new Dictionary<ValidationAttribute, BusinessRuleValidator>();
}

Some custom attribute:

public class MySuperAttribute : ValidationAttribute

Some validator:

public class MySuperValidator : BusinessRuleValidator

However:

  ValidatorRepository.Repo.Add(MySuperAttribute, typeof(MySuperValidator));

Only works for the second object, the first one complains:

MySuperAttribute' is a type, which is not valid in the given context

Tried putting typeof() around it to no success. Now it's been a hellish long day and I'm probably just missing something utterly stupod, but please help. I really can't see what's wrong :(


问:
Centering a View on top of another view in JavaFx
I'm trying to center a view on top of another view essentially in an anchor pane.

Here is my code:

```<code><AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
    <children>
        <ListView fx:id="list" prefHeight="750.0" prefWidth="300.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
        <ProgressIndicator fx:id="bar" />
    </children>
</AnchorPane>
</code>```

This is what it looks like:

This is my goal:

EDIT:

Updated code to include a stackpane

```<code><AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
          <children>
            <StackPane prefHeight="150.0" prefWidth="200.0">
              <children>
                <ListView fx:id="list" />
                <ProgressIndicator fx:id="bar" />
              </children>
            </StackPane>
          </children>
        </AnchorPane>
</code>```

答:
Try this:

The key to filling the StackPane is to set the ListView's maxHeight and maxWidth to Double.MAX_VALUE.

```<code><children>
  <StackPane AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
     <children>
        <ListView maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" />
        <ProgressIndicator maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" progress="0.44">
           <StackPane.margin>
              <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
           </StackPane.margin>
        </ProgressIndicator>
     </children>
  </StackPane>
</code>```

The prefHeight and prefWidth for the StackPane and ListView may not reflect what you have in your original post. You can change these values to suit your needs. I also set Constraints on the StackPane so that it fills its Parent AnchorPane.

SceneBuilder Images:

You may need to set the preferred side of ProgressIndicator

Body:
I'm trying to center a view on top of another view essentially in an anchor pane.

Here is my code:

<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
    <children>
        <ListView fx:id="list" prefHeight="750.0" prefWidth="300.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
        <ProgressIndicator fx:id="bar" />
    </children>
</AnchorPane>

This is what it looks like:

This is my goal:

EDIT:

Updated code to include a stackpane

<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
          <children>
            <StackPane prefHeight="150.0" prefWidth="200.0">
              <children>
                <ListView fx:id="list" />
                <ProgressIndicator fx:id="bar" />
              </children>
            </StackPane>
          </children>
        </AnchorPane>

Body:
Try this:

The key to filling the StackPane is to set the ListView's maxHeight and maxWidth to Double.MAX_VALUE.

<children>
  <StackPane AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
     <children>
        <ListView maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" />
        <ProgressIndicator maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" progress="0.44">
           <StackPane.margin>
              <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
           </StackPane.margin>
        </ProgressIndicator>
     </children>
  </StackPane>

The prefHeight and prefWidth for the StackPane and ListView may not reflect what you have in your original post. You can change these values to suit your needs. I also set Constraints on the StackPane so that it fills its Parent AnchorPane.

SceneBuilder Images:

You may need to set the preferred side of ProgressIndicator


问:
Flexbox ignores padding & width on links
Basically, I have a navigation that uses flexbox and it is all working perfectly fine. However, when going back over it recently I noticed that the 's inside the Li's are not the same size as the Li itself and therefore does not make the whole Li clickable.

I have tried many different ways to get the 's to be the same size, when I add padding to the links they display in inspector as having padding but the padding is not clickable...

.header .navigation {
  display: block;
  width: 100%;
  position: relative;
}

.header .navigation ul {
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: row;
}

.header .navigation ul li {
  float: none;
  display: inline-block;
  background-color: #9dabc0;
  border-right: 1px solid #7e899a;
  border-left: 1px solid #bdc6d4;
  text-align: center;
  flex-grow: 1;
}

.header .navigation ul li:last-child {
  background-color: #b4a042;
  border-right: none;
}

.header .navigation ul li:last-child:hover {
  background-color: #b49242;
}

.header .navigation ul li:last-child a {
  padding: 0 5px;
  text-align: center;
}

.header .navigation ul li:first-child {
  border-left: none;
}

.header .navigation ul li:hover {
  background: #3a495e;
}

.header .navigation ul li a {
  font-size: 16px;
  font-family: "Open Sans";
  color: #fff;
  font-weight: bold;
  line-height: 59px;
  text-shadow: 0.5px 0.866px 0 rgba(1, 1, 1, 0.39);
  padding: 0 5px;
  text-align: center;
  width: 100%;
}

.header .navigation ul li ul {
  left: 0px;
  top: 0px;
  margin-left: 0px;
  display: none;
  /* hide all sub menus from view */
  position: absolute;
  z-index: 100;
  background: #9dabc0;
  top: 59px;
  /* this should be the same height as the top level menu -- height + padding + borders */
  margin-left: 0px;
  width: 100%;
}

.header .navigation ul li ul li {
  border-top: 1px solid #7e899a;
  border-bottom: 1px solid #bdc6d4;
  border-left: none;
  border-right: none;
  background-color: #9dabc0;
  height: 42px;
  display: block;
}

.header .navigation ul li ul li:last-child {
  border-bottom: none;
  background-color: #9dabc0;
}

.header .navigation ul li ul li:last-child a {
  padding: 10px 24px;
}

.header .navigation ul li ul li a {
  font-size: 16px;
  font-family: "Open Sans";
  width: 100%;
  color: #fff;
  font-weight: bold;
  text-shadow: 0.5px 0.866px 0px rgba(1, 1, 1, 0.39);
  display: block;
  line-height: 18px;
  padding: 10px 24px;
}

.header .navigation ul li ul li:hover {
  background: #3a495e;
}

.header .navigation ul li {
  position: relative;
}

.header .navigation ul li:hover>ul {
  display: block;
}

.header .navigation ul li li.has-children>a:after {
  color: green;
  content: ' ►';
  font-size: 10px;
  float: right;
  padding-right: 10px;
  vertical-align: 1px;
}

.header .navigation ul .current-menu-item:after {
  color: green;
  content: '▲';
  position: absolute;
  top: 100%;
  left: 30%;
}

.header .navigation ul .sub-menu .current-menu-item:after {
  content: none;
}

.header .navigation ul li.has-children>a:after {
  color: green;
  content: '▼';
  font-size: 10px;
  padding-left: 5px;
  vertical-align: 1px;
}

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <div class="navigation">
    <ul>
      <li>Home</li>
      <li>Engineering Castings
        <ul>
          <li>Example</li>
          <li>Example</li>
          <li>Example</li>
        </ul>
      </li>
      <li>Architectural Castings
        <ul>
          <li>Example</li>
          <li>Example</li>
        </ul>
      </li>
      <li>Decorative Castings
        <ul>
          <li>Example</li>
          <li>Example</li>
          <li>Example</li>
          <li>Example</li>
        </ul>
      </li>
      <li>
        Downloads</li>
      <li>
        Gallery</li>
      <li>
        Contact</li>
      <li>
        Blog</li>
      <li>
        FREE Castings Guide</li>
    </ul>
  </div>
</div></code>```

Here's the codepen: https://codepen.io/danielvickerssa/pen/ZyjqRr

答:
You can make the links inline-block then you can give them vertical padding/height. display: inline-block; height: 100%; makes them fill the parent li

.header .navigation {
  display: block;
  width: 100%;
  position: relative;
}

.header .navigation ul {
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: row;
}

.header .navigation ul li {
  float: none;
  display: inline-block;
  background-color: #9dabc0;
  border-right: 1px solid #7e899a;
  border-left: 1px solid #bdc6d4;
  text-align: center;
  flex-grow: 1;
}

.header .navigation ul li:last-child {
  background-color: #b4a042;
  border-right: none;
}

.header .navigation ul li:last-child:hover {
  background-color: #b49242;
}

.header .navigation ul li:last-child a {
  padding: 0 5px;
  text-align: center;
}

.header .navigation ul li:first-child {
  border-left: none;
}

.header .navigation ul li:hover {
  background: #3a495e;
}

.header .navigation ul li a {
  font-size: 16px;
  font-family: "Open Sans";
  color: #fff;
  font-weight: bold;
  line-height: 59px;
  text-shadow: 0.5px 0.866px 0 rgba(1, 1, 1, 0.39);
  padding: 0 5px;
  text-align: center;
  width: 100%;
  display: inline-block;
  height: 100%;
}

.header .navigation ul li ul {
  left: 0px;
  top: 0px;
  margin-left: 0px;
  display: none;
  /* hide all sub menus from view */
  position: absolute;
  z-index: 100;
  background: #9dabc0;
  top: 59px;
  /* this should be the same height as the top level menu -- height + padding + borders */
  margin-left: 0px;
  width: 100%;
}

.header .navigation ul li ul li {
  border-top: 1px solid #7e899a;
  border-bottom: 1px solid #bdc6d4;
  border-left: none;
  border-right: none;
  background-color: #9dabc0;
  height: 42px;
  display: block;
}

.header .navigation ul li ul li:last-child {
  border-bottom: none;
  background-color: #9dabc0;
}

.header .navigation ul li ul li:last-child a {
  padding: 10px 24px;
}

.header .navigation ul li ul li a {
  font-size: 16px;
  font-family: "Open Sans";
  width: 100%;
  color: #fff;
  font-weight: bold;
  text-shadow: 0.5px 0.866px 0px rgba(1, 1, 1, 0.39);
  display: block;
  line-height: 18px;
  padding: 10px 24px;
}

.header .navigation ul li ul li:hover {
  background: #3a495e;
}

.header .navigation ul li {
  position: relative;
}

.header .navigation ul li:hover>ul {
  display: block;
}

.header .navigation ul li li.has-children>a:after {
  color: green;
  content: ' ►';
  font-size: 10px;
  float: right;
  padding-right: 10px;
  vertical-align: 1px;
}

.header .navigation ul .current-menu-item:after {
  color: green;
  content: '▲';
  position: absolute;
  top: 100%;
  left: 30%;
}

.header .navigation ul .sub-menu .current-menu-item:after {
  content: none;
}

.header .navigation ul li.has-children>a:after {
  color: green;
  content: '▼';
  font-size: 10px;
  padding-left: 5px;
  vertical-align: 1px;
}

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <div class="navigation">
    <ul>
      <li>Home</li>
      <li>Engineering Castings
        <ul>
          <li>Example</li>
          <li>Example</li>
          <li>Example</li>
        </ul>
      </li>
      <li>Architectural Castings
        <ul>
          <li>Example</li>
          <li>Example</li>
        </ul>
      </li>
      <li>Decorative Castings
        <ul>
          <li>Example</li>
          <li>Example</li>
          <li>Example</li>
          <li>Example</li>
        </ul>
      </li>
      <li>
        Downloads</li>
      <li>
        Gallery</li>
      <li>
        Contact</li>
      <li>
        Blog</li>
      <li>
        FREE Castings Guide</li>
    </ul>
  </div>
</div></code>```

Body:
Basically, I have a navigation that uses flexbox and it is all working perfectly fine. However, when going back over it recently I noticed that the 's inside the Li's are not the same size as the Li itself and therefore does not make the whole Li clickable.

I have tried many different ways to get the 's to be the same size, when I add padding to the links they display in inspector as having padding but the padding is not clickable...

.header .navigation {
  display: block;
  width: 100%;
  position: relative;
}

.header .navigation ul {
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: row;
}

.header .navigation ul li {
  float: none;
  display: inline-block;
  background-color: #9dabc0;
  border-right: 1px solid #7e899a;
  border-left: 1px solid #bdc6d4;
  text-align: center;
  flex-grow: 1;
}

.header .navigation ul li:last-child {
  background-color: #b4a042;
  border-right: none;
}

.header .navigation ul li:last-child:hover {
  background-color: #b49242;
}

.header .navigation ul li:last-child a {
  padding: 0 5px;
  text-align: center;
}

.header .navigation ul li:first-child {
  border-left: none;
}

.header .navigation ul li:hover {
  background: #3a495e;
}

.header .navigation ul li a {
  font-size: 16px;
  font-family: "Open Sans";
  color: #fff;
  font-weight: bold;
  line-height: 59px;
  text-shadow: 0.5px 0.866px 0 rgba(1, 1, 1, 0.39);
  padding: 0 5px;
  text-align: center;
  width: 100%;
}

.header .navigation ul li ul {
  left: 0px;
  top: 0px;
  margin-left: 0px;
  display: none;
  /* hide all sub menus from view */
  position: absolute;
  z-index: 100;
  background: #9dabc0;
  top: 59px;
  /* this should be the same height as the top level menu -- height + padding + borders */
  margin-left: 0px;
  width: 100%;
}

.header .navigation ul li ul li {
  border-top: 1px solid #7e899a;
  border-bottom: 1px solid #bdc6d4;
  border-left: none;
  border-right: none;
  background-color: #9dabc0;
  height: 42px;
  display: block;
}

.header .navigation ul li ul li:last-child {
  border-bottom: none;
  background-color: #9dabc0;
}

.header .navigation ul li ul li:last-child a {
  padding: 10px 24px;
}

.header .navigation ul li ul li a {
  font-size: 16px;
  font-family: "Open Sans";
  width: 100%;
  color: #fff;
  font-weight: bold;
  text-shadow: 0.5px 0.866px 0px rgba(1, 1, 1, 0.39);
  display: block;
  line-height: 18px;
  padding: 10px 24px;
}

.header .navigation ul li ul li:hover {
  background: #3a495e;
}

.header .navigation ul li {
  position: relative;
}

.header .navigation ul li:hover>ul {
  display: block;
}

.header .navigation ul li li.has-children>a:after {
  color: green;
  content: ' ►';
  font-size: 10px;
  float: right;
  padding-right: 10px;
  vertical-align: 1px;
}

.header .navigation ul .current-menu-item:after {
  color: green;
  content: '▲';
  position: absolute;
  top: 100%;
  left: 30%;
}

.header .navigation ul .sub-menu .current-menu-item:after {
  content: none;
}

.header .navigation ul li.has-children>a:after {
  color: green;
  content: '▼';
  font-size: 10px;
  padding-left: 5px;
  vertical-align: 1px;
}

}

Home

Engineering Castings

Example

Example

Example

Architectural Castings

Example

Example

Decorative Castings

Example

Example

Example

Example

        Downloads

        Gallery

        Contact

        Blog

        FREE Castings Guide

Here's the codepen: https://codepen.io/danielvickerssa/pen/ZyjqRr

Body:
You can make the links inline-block then you can give them vertical padding/height. display: inline-block; height: 100%; makes them fill the parent li

.header .navigation {
  display: block;
  width: 100%;
  position: relative;
}

.header .navigation ul {
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: row;
}

.header .navigation ul li {
  float: none;
  display: inline-block;
  background-color: #9dabc0;
  border-right: 1px solid #7e899a;
  border-left: 1px solid #bdc6d4;
  text-align: center;
  flex-grow: 1;
}

.header .navigation ul li:last-child {
  background-color: #b4a042;
  border-right: none;
}

.header .navigation ul li:last-child:hover {
  background-color: #b49242;
}

.header .navigation ul li:last-child a {
  padding: 0 5px;
  text-align: center;
}

.header .navigation ul li:first-child {
  border-left: none;
}

.header .navigation ul li:hover {
  background: #3a495e;
}

.header .navigation ul li a {
  font-size: 16px;
  font-family: "Open Sans";
  color: #fff;
  font-weight: bold;
  line-height: 59px;
  text-shadow: 0.5px 0.866px 0 rgba(1, 1, 1, 0.39);
  padding: 0 5px;
  text-align: center;
  width: 100%;
  display: inline-block;
  height: 100%;
}

.header .navigation ul li ul {
  left: 0px;
  top: 0px;
  margin-left: 0px;
  display: none;
  /* hide all sub menus from view */
  position: absolute;
  z-index: 100;
  background: #9dabc0;
  top: 59px;
  /* this should be the same height as the top level menu -- height + padding + borders */
  margin-left: 0px;
  width: 100%;
}

.header .navigation ul li ul li {
  border-top: 1px solid #7e899a;
  border-bottom: 1px solid #bdc6d4;
  border-left: none;
  border-right: none;
  background-color: #9dabc0;
  height: 42px;
  display: block;
}

.header .navigation ul li ul li:last-child {
  border-bottom: none;
  background-color: #9dabc0;
}

.header .navigation ul li ul li:last-child a {
  padding: 10px 24px;
}

.header .navigation ul li ul li a {
  font-size: 16px;
  font-family: "Open Sans";
  width: 100%;
  color: #fff;
  font-weight: bold;
  text-shadow: 0.5px 0.866px 0px rgba(1, 1, 1, 0.39);
  display: block;
  line-height: 18px;
  padding: 10px 24px;
}

.header .navigation ul li ul li:hover {
  background: #3a495e;
}

.header .navigation ul li {
  position: relative;
}

.header .navigation ul li:hover>ul {
  display: block;
}

.header .navigation ul li li.has-children>a:after {
  color: green;
  content: ' ►';
  font-size: 10px;
  float: right;
  padding-right: 10px;
  vertical-align: 1px;
}

.header .navigation ul .current-menu-item:after {
  color: green;
  content: '▲';
  position: absolute;
  top: 100%;
  left: 30%;
}

.header .navigation ul .sub-menu .current-menu-item:after {
  content: none;
}

.header .navigation ul li.has-children>a:after {
  color: green;
  content: '▼';
  font-size: 10px;
  padding-left: 5px;
  vertical-align: 1px;
}

}

<div class="header">
  <div class="navigation">
    <ul>
      <li><a href="">Home</a></li>
      <li><a href="">Engineering Castings</a>
        <ul>
          <li><a href="">Example</a></li>
          <li><a href="">Example</a></li>
          <li><a href="">Example</a></li>
        </ul>
      </li>
      <li><a href="">Architectural Castings</a>
        <ul>
          <li><a href="">Example</a></li>
          <li><a href="">Example</a></li>
        </ul>
      </li>
      <li><a href="">Decorative Castings</a>
        <ul>
          <li><a href="">Example</a></li>
          <li><a href="">Example</a></li>
          <li><a href="">Example</a></li>
          <li><a href="">Example</a></li>
        </ul>
      </li>
      <li>
        <a href="">Downloads</a></li>
      <li>
        <a href="">Gallery</a></li>
      <li>
        <a href="">Contact</a></li>
      <li>
        <a href="">Blog</a></li>
      <li>
        <a href="">FREE Castings Guide</a></li>
    </ul>
  </div>
</div>


问:
How to use custom packages
I'm trying to create and use a custom package in Go. It's probably something very obvious but I cannot find much information about this. Basically, I have these two files in the same folder:

mylib.go

```<code>package mylib

type SomeType struct {

}
</code>```

main.go

```<code>package main

import (
    "mylib"
)

func main() {

}
</code>```

When I try to go run main.go, I get this error:

```<code>main.go:4:2: import "mylib": cannot find package
</code>```

I've tried to run go build mylib.go first but it doesn't seem to be doing anything (no file generated, no error message). So any idea how I could do this?

答:
For a project hosted on GitHub, here's what people usually do：

```<code>github.com/
  laike9m/
    myproject/
      mylib/
        mylib.go
        ...
      main.go
</code>```

mylib.go

```<code>package mylib

...
</code>```

main.go

```<code>import "github.com/laike9m/myproject/mylib"

...
</code>```

Title: How to use custom packages

Body:
I'm trying to create and use a custom package in Go. It's probably something very obvious but I cannot find much information about this. Basically, I have these two files in the same folder:

mylib.go

package mylib

type SomeType struct {

}

main.go

package main

import (
    "mylib"
)

func main() {

}

When I try to go run main.go, I get this error:

main.go:4:2: import "mylib": cannot find package

I've tried to run go build mylib.go first but it doesn't seem to be doing anything (no file generated, no error message). So any idea how I could do this?

Body:
For a project hosted on GitHub, here's what people usually do：

github.com/
  laike9m/
    myproject/
      mylib/
        mylib.go
        ...
      main.go

mylib.go

package mylib

...

main.go

import "github.com/laike9m/myproject/mylib"

...


问:
Equivalent to CryptoStream .NET in Java?
I have an encrypted string in visual basic. NET 2008, the functions to encrypt and decrypt are the following:

```<code>Imports System.Security.Cryptography

 Public Shared Function Encriptar(ByVal strValor As String) As String
    Dim strEncrKey As String = "key12345"
    Dim byKey() As Byte = {}
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Try
        byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey)
        Dim des As New DESCryptoServiceProvider
        Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(strValor)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Return Convert.ToBase64String(ms.ToArray())
    Catch ex As Exception
        Return ""
    End Try
End Function

Public Shared Function Desencriptar(ByVal strValor As String) As String
    Dim sDecrKey As String = "key12345"
    Dim byKey() As Byte = {}
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Dim inputByteArray(strValor.Length) As Byte
    Try
        byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey)
        Dim des As New DESCryptoServiceProvider
        If Trim(strValor).Length = 0 Then
            Throw New Exception("Password No debe estar en Blanco")
        End If
        inputByteArray = Convert.FromBase64String(strValor)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
        Return encoding.GetString(ms.ToArray(), 0, ms.ToArray.Count)
    Catch ex As Exception
        Return ""
    End Try
End Function
</code>```

for example the word "android" encrypted with this function gives me the result "B3xogi/Qfsc="

now I need to decrypt the string "B3xogi/Qfsc=" it from java, by the same key, which is "key12345", and the result should be "android"...anyone know how to do this?

Thanks in advance.

答: The closest Java classes to .NET's CryptoStream class are the CipherInputStream and CipherOutputStream classes.

Body:
I have an encrypted string in visual basic. NET 2008, the functions to encrypt and decrypt are the following:

Imports System.Security.Cryptography

 Public Shared Function Encriptar(ByVal strValor As String) As String
    Dim strEncrKey As String = "key12345"
    Dim byKey() As Byte = {}
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Try
        byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey)
        Dim des As New DESCryptoServiceProvider
        Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(strValor)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Return Convert.ToBase64String(ms.ToArray())
    Catch ex As Exception
        Return ""
    End Try
End Function

Public Shared Function Desencriptar(ByVal strValor As String) As String
    Dim sDecrKey As String = "key12345"
    Dim byKey() As Byte = {}
    Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
    Dim inputByteArray(strValor.Length) As Byte
    Try
        byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey)
        Dim des As New DESCryptoServiceProvider
        If Trim(strValor).Length = 0 Then
            Throw New Exception("Password No debe estar en Blanco")
        End If
        inputByteArray = Convert.FromBase64String(strValor)
        Dim ms As New MemoryStream
        Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
        Return encoding.GetString(ms.ToArray(), 0, ms.ToArray.Count)
    Catch ex As Exception
        Return ""
    End Try
End Function

for example the word "android" encrypted with this function gives me the result "B3xogi/Qfsc="

now I need to decrypt the string "B3xogi/Qfsc=" it from java, by the same key, which is "key12345", and the result should be "android"...anyone know how to do this?

Thanks in advance.


问:
Using fullpage.js with React
I'm trying to make a React Component that uses fullpage.js. However, I'm having issues trying to integrate the javascript files from the fullpage.js library. This is what I have (abbreviated):

```<code>import React from 'react';

let $ = require('jquery')(require('jsdom').jsdom().defaultView);
import 'fullpage.js';

class FullPage extends Component {

  componentDidMount() {
    $('#fullpage').fullpage();
  }

  render() {
    return (
      <div id="fullpage">
        <div className="section">Some section</div>
        <div className="section">Some section</div>
        <div className="section">Some section</div>
        <div className="section">Some section</div>
      </div>
    )
  }
}
</code>```

However, using this component gives an error:

```<code>Error: jQuery requires a window with a document
</code>```

Even if I have defined a window using JSDOM.

Beyond fullpage.js, how should I go about using libraries that require jQuery into React components?

答:
```<code>window.$ = require('jquery')(window);
</code>```

Could you please try with above code?

Title: Using fullpage.js with React

Body:
I'm trying to make a React Component that uses fullpage.js. However, I'm having issues trying to integrate the javascript files from the fullpage.js library. This is what I have (abbreviated):

import React from 'react';

let $ = require('jquery')(require('jsdom').jsdom().defaultView);
import 'fullpage.js';

class FullPage extends Component {

  componentDidMount() {
    $('#fullpage').fullpage();
  }

  render() {
    return (

Some section

Some section

Some section

Some section

    )
  }
}

However, using this component gives an error:

Error: jQuery requires a window with a document

Even if I have defined a window using JSDOM.

Beyond fullpage.js, how should I go about using libraries that require jQuery into React components?

Body:
window.$ = require('jquery')(window);

Could you please try with above code?


问:
access data volume of node modules outside docker container
I have docker setup for a node.js web service which creates a data volume for node modules like this:

```<code>  volumes:
       - ./service:/usr/src/service
       - /usr/src/service/node_modules
</code>```

The solution with data volume works fine. But using a data volume, the node_modules are not accessible or visible in my host (not container) which creates other restrictions. For example: I can not run tests in web-storm as they expect node_modules to be present.

Is there any alternative solution other than using data volume to mount node modules which also allows to access them on host?

The docker file looks like:

```<code>FROM node:6.3.1-slim

ARG NPM_TOKEN
ARG service
ENV NODE_ENV development

RUN apt-get update && apt-get -y install build-essential git-core python-dev vim

# use nodemon for development
RUN npm install --global nodemon

COPY .npmrc /root/.npmrc

RUN mkdir -p /usr/src/$service
RUN mkdir -p /modules/$service/
COPY sources/$service/package.json /modules/$service/package.json
RUN cd /modules/$service/ && npm install && rm -f /root/.npmrc && mv /modules/$service/node_modules /usr/src/$service/node_modules

WORKDIR /usr/src/$service
COPY sources/$service /usr/src/$service

ENV service=${service}

COPY start_services.sh /root/start_services.sh
COPY .env /root/.env
COPY services.sh /root/services.sh

RUN ["chmod", "+x", "/root/start_services.sh"]
RUN ["chmod", "+x", "/root/services.sh"]
CMD /root/start_services.sh
</code>```

答:
Specify node_modules as follows:</p>

```<code>volumes:
  - .:/usr/src/service/
  - /usr/src/service/node_modules
</code>```

Body:
I have docker setup for a node.js web service which creates a data volume for node modules like this:

  volumes:
       - ./service:/usr/src/service
       - /usr/src/service/node_modules

The solution with data volume works fine. But using a data volume, the node_modules are not accessible or visible in my host (not container) which creates other restrictions. For example: I can not run tests in web-storm as they expect node_modules to be present.

Is there any alternative solution other than using data volume to mount node modules which also allows to access them on host?

The docker file looks like:

FROM node:6.3.1-slim

ARG NPM_TOKEN
ARG service
ENV NODE_ENV development

RUN apt-get update && apt-get -y install build-essential git-core python-dev vim

# use nodemon for development
RUN npm install --global nodemon

COPY .npmrc /root/.npmrc

RUN mkdir -p /usr/src/$service
RUN mkdir -p /modules/$service/
COPY sources/$service/package.json /modules/$service/package.json
RUN cd /modules/$service/ && npm install && rm -f /root/.npmrc && mv /modules/$service/node_modules /usr/src/$service/node_modules

WORKDIR /usr/src/$service
COPY sources/$service /usr/src/$service

ENV service=${service}

COPY start_services.sh /root/start_services.sh
COPY .env /root/.env
COPY services.sh /root/services.sh

RUN ["chmod", "+x", "/root/start_services.sh"]
RUN ["chmod", "+x", "/root/services.sh"]
CMD /root/start_services.sh

Body:
Specify node_modules as follows:

volumes:
  - .:/usr/src/service/
  - /usr/src/service/node_modules


问:
Documentation event listeners
I have a question concerning this code down here:

```<code>on.("click", () => {...})
</code>```

Currently I try to figure out Electron. In a code example I saw the use of the usual event listener function. In the fat-arrow function the developer used different kinds of properties. For example:

```<code>on.("click", () => {event, bounds})
</code>```

I am interested in the amount of properties you can use... there are probably more than just those two. I could not find any documentation on this.
That did not help me at all: https://developer.mozilla.org/en/docs/Web/Events/click

Maybe someone can help me out on this.

答:
I am interested in the amount of properties you can use...

There are no other properties besides the ones embedded into the event object.

event refers to the global variable window.event which is a reference to the currently handled event.

```<code>.on('click', () => { console.log(event) })
</code>```

and

```<code>.on('click', (e) => { console.log(e) })
</code>```

will output the same event (exept in Firefox, where the first example will not output anything)

I highly suspect that bounds is a variable defined by the author of your tutorial, because the click-event doesn't have a direct bounds property (as you've already seen in the MDN documentation). We'd have to see the full example to explain it where it actually comes from.

Title: Documentation event listeners

Body:
I have a question concerning this code down here:

on.("click", () => {...})

Currently I try to figure out Electron. In a code example I saw the use of the usual event listener function. In the fat-arrow function the developer used different kinds of properties. For example:

on.("click", () => {event, bounds})

I am interested in the amount of properties you can use... there are probably more than just those two. I could not find any documentation on this.
That did not help me at all: https://developer.mozilla.org/en/docs/Web/Events/click

Maybe someone can help me out on this.

Body:
I am interested in the amount of properties you can use...

There are no other properties besides the ones embedded into the event object.

event refers to the global variable window.event which is a reference to the currently handled event.

.on('click', () => { console.log(event) })

and

.on('click', (e) => { console.log(e) })

will output the same event (exept in Firefox, where the first example will not output anything)

I highly suspect that bounds is a variable defined by the author of your tutorial, because the click-event doesn't have a direct bounds property (as you've already seen in the MDN documentation). We'd have to see the full example to explain it where it actually comes from.


问:
regex capture text then add another before and after captured
For the input string:

```<code>"test.com/dfafsf--fasfgf--fefegf-12345678+test (first text)"
</code>```

I want to apply regex to check if the input string contains: 12345678+test

if found then want to convert it into this:

```<code>sample.com/klklklklkl-klklkl-'CAPTURED12345678'+fefgreg-dgferg
</code>```

I have trid this regex:

```<code>\d+(?=+test)
</code>```

Has anyone an idea?

答:
your pattern is correct. But if you have your string is a file:

you can use Perl to match and substitute in one step:

for the input:

```<code>"test.com/dfafsf--fasfgf--fefegf-12345678+test (first text)"
</code>```

you can apply:

```<code>perl -lpe '/\d+(?=\+test)/g && ($m = $&) && s/^.+$/sample.com\/klklklklkl-klklkl-'CAPTURED'$m+fefgreg-dgferg/g' file
</code>```

check if the line has match: /\d+(?=\+test)/g

then save the result: ($m = $&)

lastly substitution the entire line: s/^.+$/sample.com\/klklklklkl-klklkl-'CAPTURED'$m+fefgreg-dgferg/g

And the output is:

```<code>sample.com/klklklklkl-klklkl-CAPTURED12345678+fefgreg-dgferg
</code>```

And as you can see there is no single ' quote around CAPTURED12345678 since I used [teg:bash] and it cannot handle that and for that you use '"'"'CAPTURED$m'"'"' instead.

But if you want: my question is, how can I add text before and after my captured digits

you need to know where is your pattern stored or in fact which variable or method takes care of the sub-match.  For example if Perl the $& takes care of it and I used this as well. Or in C++ the .str() method of class match_results

So with Perl you can use s/^.+$/Before-Match $& After-Match/g  and if you apply it to the file:

```<code>perl -lpe '/\d+(?=\+test)/g && ($m = $&) && s/^.+$/Before-Match=> $m <=After-Match/g' file
</code>```

the output will be:

```<code>Before-Match=> 12345678 <=After-Match
</code>```

Body:
For the input string:

"test.com/dfafsf--fasfgf--fefegf-12345678+test (first text)"

I want to apply regex to check if the input string contains: 12345678+test

if found then want to convert it into this:

sample.com/klklklklkl-klklkl-'CAPTURED12345678'+fefgreg-dgferg

I have trid this regex:

\d+(?=+test)

Has anyone an idea?

Body:
your pattern is correct. But if you have your string is a file:

you can use Perl to match and substitute in one step:

for the input:

"test.com/dfafsf--fasfgf--fefegf-12345678+test (first text)"

you can apply:

perl -lpe '/\d+(?=\+test)/g && ($m = $&) && s/^.+$/sample.com\/klklklklkl-klklkl-'CAPTURED'$m+fefgreg-dgferg/g' file

check if the line has match: /\d+(?=\+test)/g

then save the result: ($m = $&)

lastly substitution the entire line: s/^.+$/sample.com\/klklklklkl-klklkl-'CAPTURED'$m+fefgreg-dgferg/g

And the output is:

sample.com/klklklklkl-klklkl-CAPTURED12345678+fefgreg-dgferg

And as you can see there is no single ' quote around CAPTURED12345678 since I used [teg:bash] and it cannot handle that and for that you use '"'"'CAPTURED$m'"'"' instead.

But if you want: my question is, how can I add text before and after my captured digits

you need to know where is your pattern stored or in fact which variable or method takes care of the sub-match.  For example if Perl the $& takes care of it and I used this as well. Or in C++ the .str() method of class match_results

So with Perl you can use s/^.+$/Before-Match $& After-Match/g  and if you apply it to the file:

perl -lpe '/\d+(?=\+test)/g && ($m = $&) && s/^.+$/Before-Match=> $m <=After-Match/g' file

the output will be:

Before-Match=> 12345678 <=After-Match


问:
ansible reboot 2.1.1.0 fails
I've been trying to create a really simple Ansible playbook that will reboot a server and wait for it to come back.

I've had one in the past on Ansible 1.9 that worked, but i've recently upgraded to 2.1.1.0 and it fails.

The host i'm rebooting is called idm and has an IP of 192.168.200.23.

the playbook is being run from my host 192.168.200.1 with the command

```<code>$ ansible-playbook reboot.yml  -vvvv
</code>```

This is the playbook i'm using

```<code>---
- hosts: idm

  tasks:
    - name: Restart server
      become: yes
      shell: sleep 2 && /sbin/shutdown -r now "Ansible system package upgraded"

    - name: waiting 60 secs for server to come back
      local_action: wait_for host=192.168.200.23 port=22 delay=60 connect_timeout=200
      become: false
</code>```

It reboots the machine fine, but almost immediately fails with

```<code><192.168.200.23> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.200.23> SSH: EXEC ssh -C -vvv -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=10 -o ControlPath=/home/myork/.ansible/cp/ansible-ssh-%h-%p-%r -tt 192.168.200.23 '/bin/sh -c '"'"'LANG=en_GB.UTF-8 LC_ALL=en_GB.UTF-8 LC_MESSAGES=en_GB.UTF-8 /usr/bin/python /root/.ansible/tmp/ansible-tmp-1472242630.58-176546106960362/command; rm -rf "/root/.ansible/tmp/ansible-tmp-1472242630.58-176546106960362/" > /dev/null 2>&1 && sleep 0'"'"''
fatal: [idm]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh.", "unreachable": true}
</code>```

Any idea what i've missed here ?

Thanks!

答:
UPDATE with the comment of @Konstantin Suvorov.

Here a better solution to avoid hard IP

```<code>- name: Restart server
  shell: /sbin/shutdown -r now "Ansible system package upgraded"
  async: 1
  poll: 0
- set_fact: wait_host="{{ ansible_host }}"
- name: Wait for server to come back
  local_action: wait_for host={{wait_host}} delay=20 port=22 state=started
  become: false
</code>```

Eric

Title: ansible reboot 2.1.1.0 fails

Body:
I've been trying to create a really simple Ansible playbook that will reboot a server and wait for it to come back.

I've had one in the past on Ansible 1.9 that worked, but i've recently upgraded to 2.1.1.0 and it fails.

The host i'm rebooting is called idm and has an IP of 192.168.200.23.

the playbook is being run from my host 192.168.200.1 with the command

$ ansible-playbook reboot.yml  -vvvv

This is the playbook i'm using

---
- hosts: idm

  tasks:
    - name: Restart server
      become: yes
      shell: sleep 2 && /sbin/shutdown -r now "Ansible system package upgraded"

    - name: waiting 60 secs for server to come back
      local_action: wait_for host=192.168.200.23 port=22 delay=60 connect_timeout=200
      become: false

It reboots the machine fine, but almost immediately fails with

<192.168.200.23> ESTABLISH SSH CONNECTION FOR USER: root
<192.168.200.23> SSH: EXEC ssh -C -vvv -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=root -o ConnectTimeout=10 -o ControlPath=/home/myork/.ansible/cp/ansible-ssh-%h-%p-%r -tt 192.168.200.23 '/bin/sh -c '"'"'LANG=en_GB.UTF-8 LC_ALL=en_GB.UTF-8 LC_MESSAGES=en_GB.UTF-8 /usr/bin/python /root/.ansible/tmp/ansible-tmp-1472242630.58-176546106960362/command; rm -rf "/root/.ansible/tmp/ansible-tmp-1472242630.58-176546106960362/" > /dev/null 2>&1 && sleep 0'"'"''
fatal: [idm]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh.", "unreachable": true}

Any idea what i've missed here ?

Thanks!

Body:
UPDATE with the comment of @Konstantin Suvorov.

Here a better solution to avoid hard IP

- name: Restart server
  shell: /sbin/shutdown -r now "Ansible system package upgraded"
  async: 1
  poll: 0
- set_fact: wait_host="{{ ansible_host }}"
- name: Wait for server to come back
  local_action: wait_for host={{wait_host}} delay=20 port=22 state=started
  become: false

Eric


问:
Modify a tensor
Suppose I have a tensor like this

```<code>[
    [ 6 -2 -2 -2 -1 -2  -3 -3 -6 -6]
    [ 1 -6 -7 -7 -7 -7  -7 -6 -6 -6]
    [ 5 -3 -3 -4 -4 -4  -4 -3 -3 -3]
 ]
</code>```

I have to perform the following operation on each row.
If first element is the largest(value) element in the row but its value is less than 4, then swap first and second elements of the row. Resulting tensor will be

```<code>[
    [ 6 -2 -2 -2 -1 -2  -3 -3 -6 -6]
    [ -6 1 -7 -7 -7 -7  -7 -6 -6 -6] #elements swapped
    [ 5 -3 -3 -4 -4 -4  -4 -3 -3 -3]
 ]
</code>```

I am working in python using tensorflow module. Please help.

答:
The general recipe for a problem like this is to use tf.map_fn() to create a new tensor with the appropriate value by applying a function to each row. Let's start by how to express the condition for a single row:

```<code>row = tf.placeholder(tf.int32, shape=[10])

condition = tf.logical_and(
    tf.equal(row[0], tf.reduce_max(row)),
    tf.less(row[0], 4))

sess = tf.Session()

print sess.run(condition, feed_dict={row: [6, -2, -2, -2, -1, -2, -3, -3, -6, -6]})
print sess.run(condition, feed_dict={row: [1, -6, -7, -7, -7, -7, -7, -6, -6, -6]})
print sess.run(condition, feed_dict={row: [5, -3, -3, -4, -4, -4, -4, -3, -3, -3]})

# Prints the following:
# False
# True
# False
</code>```

Now the we have a condition, we can use tf.cond() to build a conditional expression that swaps the first two elements if the condition is true:

```<code>def swap_first_two(x):
  swapped_first_two = tf.stack([x[1], x[0]])
  rest = x[2:]
  return tf.concat([swapped_first_two, rest], 0)

maybe_swapped = tf.cond(condition, lambda: swap_first_two(row), lambda: row)

print sess.run(maybe_swapped, feed_dict={row: [6, -2, -2, -2, -1, -2, -3, -3, -6, -6]})
print sess.run(maybe_swapped, feed_dict={row: [1, -6, -7, -7, -7, -7, -7, -6, -6, -6]})
print sess.run(maybe_swapped, feed_dict={row: [5, -3, -3, -4, -4, -4, -4, -3, -3, -3]})

# Prints the following:
# [ 6 -2 -2 -2 -1 -2 -3 -3 -6 -6]
# [-6  1 -7 -7 -7 -7 -7 -6 -6 -6]
# [ 5 -3 -3 -4 -4 -4 -4 -3 -3 -3]
</code>```

Finally, we put it all together by wrapping the computation of maybe_swapped in a function, and passing it to tf.map_fn():

```<code>matrix = tf.constant([
    [6, -2, -2, -2, -1, -2, -3, -3, -6, -6],
    [1, -6, -7, -7, -7, -7, -7, -6, -6, -6],
    [5, -3, -3, -4, -4, -4, -4, -3, -3, -3],
])

def row_function(row):
  condition = tf.logical_and(
      tf.equal(row[0], tf.reduce_max(row)),
      tf.less(row[0], 4))

  def swap_first_two(x):
    swapped_first_two = tf.stack([x[1], x[0]])
    rest = x[2:]
    return tf.concat([swapped_first_two, rest], 0)

  maybe_swapped = tf.cond(condition, lambda: swap_first_two(row), lambda: row)

  return maybe_swapped

result = tf.map_fn(row_function, matrix)

print sess.run(result)

# Prints the following:
# [[ 6 -2 -2 -2 -1 -2 -3 -3 -6 -6]
#  [-6  1 -7 -7 -7 -7 -7 -6 -6 -6]
#  [ 5 -3 -3 -4 -4 -4 -4 -3 -3 -3]]
</code>```

Title: Modify a tensor

Body:
Suppose I have a tensor like this

[
    [ 6 -2 -2 -2 -1 -2  -3 -3 -6 -6]
    [ 1 -6 -7 -7 -7 -7  -7 -6 -6 -6]
    [ 5 -3 -3 -4 -4 -4  -4 -3 -3 -3]
 ]

I have to perform the following operation on each row.
If first element is the largest(value) element in the row but its value is less than 4, then swap first and second elements of the row. Resulting tensor will be

[
    [ 6 -2 -2 -2 -1 -2  -3 -3 -6 -6]
    [ -6 1 -7 -7 -7 -7  -7 -6 -6 -6] #elements swapped
    [ 5 -3 -3 -4 -4 -4  -4 -3 -3 -3]
 ]

I am working in python using tensorflow module. Please help.

Body:
The general recipe for a problem like this is to use tf.map_fn() to create a new tensor with the appropriate value by applying a function to each row. Let's start by how to express the condition for a single row:

row = tf.placeholder(tf.int32, shape=[10])

condition = tf.logical_and(
    tf.equal(row[0], tf.reduce_max(row)),
    tf.less(row[0], 4))

sess = tf.Session()

print sess.run(condition, feed_dict={row: [6, -2, -2, -2, -1, -2, -3, -3, -6, -6]})
print sess.run(condition, feed_dict={row: [1, -6, -7, -7, -7, -7, -7, -6, -6, -6]})
print sess.run(condition, feed_dict={row: [5, -3, -3, -4, -4, -4, -4, -3, -3, -3]})

# Prints the following:
# False
# True
# False

Now the we have a condition, we can use tf.cond() to build a conditional expression that swaps the first two elements if the condition is true:

def swap_first_two(x):
  swapped_first_two = tf.stack([x[1], x[0]])
  rest = x[2:]
  return tf.concat([swapped_first_two, rest], 0)

maybe_swapped = tf.cond(condition, lambda: swap_first_two(row), lambda: row)

print sess.run(maybe_swapped, feed_dict={row: [6, -2, -2, -2, -1, -2, -3, -3, -6, -6]})
print sess.run(maybe_swapped, feed_dict={row: [1, -6, -7, -7, -7, -7, -7, -6, -6, -6]})
print sess.run(maybe_swapped, feed_dict={row: [5, -3, -3, -4, -4, -4, -4, -3, -3, -3]})

# Prints the following:
# [ 6 -2 -2 -2 -1 -2 -3 -3 -6 -6]
# [-6  1 -7 -7 -7 -7 -7 -6 -6 -6]
# [ 5 -3 -3 -4 -4 -4 -4 -3 -3 -3]

Finally, we put it all together by wrapping the computation of maybe_swapped in a function, and passing it to tf.map_fn():

matrix = tf.constant([
    [6, -2, -2, -2, -1, -2, -3, -3, -6, -6],
    [1, -6, -7, -7, -7, -7, -7, -6, -6, -6],
    [5, -3, -3, -4, -4, -4, -4, -3, -3, -3],
])

def row_function(row):
  condition = tf.logical_and(
      tf.equal(row[0], tf.reduce_max(row)),
      tf.less(row[0], 4))

  def swap_first_two(x):
    swapped_first_two = tf.stack([x[1], x[0]])
    rest = x[2:]
    return tf.concat([swapped_first_two, rest], 0)

  maybe_swapped = tf.cond(condition, lambda: swap_first_two(row), lambda: row)

  return maybe_swapped

result = tf.map_fn(row_function, matrix)

print sess.run(result)

# Prints the following:
# [[ 6 -2 -2 -2 -1 -2 -3 -3 -6 -6]
#  [-6  1 -7 -7 -7 -7 -7 -6 -6 -6]
#  [ 5 -3 -3 -4 -4 -4 -4 -3 -3 -3]]


问:
Create multistep buttons
I'm trying to create a multistep form with the following buttons:

But I have no clue on how to begin with this. Can someone help me on my way? Maybe a good resource? I'm also using bootstrap in my application.

For now I have:

My HTML looks like this:

```<code>    <ol class="multi-step">
    <li class="active">
        <a href="http://mydomain/nl/data-analysis/templates">
            <span class="number-circle">1</span>
            Maak een sjabloon        </a>
    </li>
    <li class="">
        <a href="http://mydomain/nl/data-analysis/scheduler">
            <span class="number-circle">2</span>
            Plan je sjabloon        </a>
    </li>
    <li class="">
        <a href="http://mydomain/nl/data-analysis/reports">
            <span class="number-circle">3</span>
            Bekijk de resultaten        </a>
    </li>
</ol>
</code>```

答:
Try this
make use of pseudo elements

CSS

```<code>.multi-step{
  list-style-type:none;
  padding:0;
}
.multi-step > li{
  display:inline-block;
  margin: auto 20px;
}
.multi-step > li > a{
  display:block;
  padding:10px 5px;
  background-color: blue;
  color:#fff;
  position: relative;
}
.multi-step > li > a::after,
.multi-step > li > a::before{
  content:"";
  position: absolute;
  height:0;
  top:0;
  bottom: 0;
  width:0;
  border:19px solid red;
}
.multi-step > li > a::before{
  left:-35px;
  border-left-color:transparent;
}
.multi-step > li > a::after{
  right:-38px;
  border-color:transparent;
  border-left-color:red;
}
</code>```

style accordingly

reference link

hope this helps..

Title: Create multistep buttons

Body:
I'm trying to create a multistep form with the following buttons:

But I have no clue on how to begin with this. Can someone help me on my way? Maybe a good resource? I'm also using bootstrap in my application.

For now I have:

My HTML looks like this:

            1
            Maak een sjabloon

            2
            Plan je sjabloon

            3
            Bekijk de resultaten

Body:
Try this
make use of pseudo elements

CSS

.multi-step{
  list-style-type:none;
  padding:0;
}
.multi-step > li{
  display:inline-block;
  margin: auto 20px;
}
.multi-step > li > a{
  display:block;
  padding:10px 5px;
  background-color: blue;
  color:#fff;
  position: relative;
}
.multi-step > li > a::after,
.multi-step > li > a::before{
  content:"";
  position: absolute;
  height:0;
  top:0;
  bottom: 0;
  width:0;
  border:19px solid red;
}
.multi-step > li > a::before{
  left:-35px;
  border-left-color:transparent;
}
.multi-step > li > a::after{
  right:-38px;
  border-color:transparent;
  border-left-color:red;
}

style accordingly

reference link

hope this helps..


问:
Sequelize Nested Association with Two Tables
I have a scenario where I am trying to query a parent table (document) with two associated tables (reference & user) that do not have a relationship to each other, but do have a relationship with the parent table. In SQL, this query would look like such and correctly outputs the data I am looking for:

select *
from `document`
left join `user`
on `document`.`user_id` = `user`.`user_id`
left join `reference`
on `document`.`reference_id` = `reference`.`reference_id`
where `user`.`organization_id` = 1;
```

<p>However, associations that are nested have to relate in hierarchical order in order for the query to work. Since the nested associations are not related to each other I get an association error. How can I avoid this error? Would <code>required: false</code> have any influence on this?</p>

<pre class="lang-js prettyprint-override"><code>models.Document.findAll({
  order: 'documentDate DESC',
  include: [{
    model: models.User,
    where: { organizationId: req.user.organizationId },
    include: [{
      model: models.Reference,
    }]
  }],
})
</code>```

Error:

Unhandled rejection Error: reference is not associated to user!

Associations:

Document:

associate: function(db) {
  Document.belongsTo(db.User, {foreignKey: 'user_id'}),
    Document.belongsTo(db.Reference, { foreignKey: 'reference_id'});;
}
```

<p><strong><code>Reference</code></strong>:</p>

<pre class="lang-js prettyprint-override"><code>associate: function(db){
  Reference.hasMany(db.Document, { foreignKey: 'reference_id' });
}
</code>```

Should I just chain queries instead?

答:
It seems to me that your problem might be the associations, trying to link back to your primary key on Documents instead of the columns 'user_id' and 'reference_id'. You didn't post the table attributes so I might have understood this wrong.

Association on documents are ok.

Documents

```<code>associate: function(db) {
  Document.belongsTo(db.User, {foreignKey: 'user_id'}),  //key in documents
  Document.belongsTo(db.Reference, { foreignKey: 'reference_id'}); //key in documents
}
</code>```

User

```<code>associate: function(db) {
  User.belongsTo(db.Document, {
    foreignKey: 'id',    //Key in User
    targetKey: 'user_id' //Key in Documents
  }),
}
</code>```

Reference

```<code>associate: function(db) {
  Reference.belongsTo(db.Document, {
      foreignKey: 'id',         //Key in reference
      targetKey: 'reference_id' //Key in Documents
  }),
}
</code>```

Also

For debbuging consider using logging so you can see the queries.

```<code>var sequelize = new Sequelize('database', 'username', 'password', {
    logging: console.log
    logging: function (str) {
        // do your own logging
    }
});
</code>```

Body:
I have a scenario where I am trying to query a parent table (document) with two associated tables (reference & user) that do not have a relationship to each other, but do have a relationship with the parent table. In SQL, this query would look like such and correctly outputs the data I am looking for:

select *
from `document`
left join `user`
on `document`.`user_id` = `user`.`user_id`
left join `reference`
on `document`.`reference_id` = `reference`.`reference_id`
where `user`.`organization_id` = 1;

However, associations that are nested have to relate in hierarchical order in order for the query to work. Since the nested associations are not related to each other I get an association error. How can I avoid this error? Would required: false have any influence on this?

models.Document.findAll({
  order: 'documentDate DESC',
  include: [{
    model: models.User,
    where: { organizationId: req.user.organizationId },
    include: [{
      model: models.Reference,
    }]
  }],
})

Error:

Unhandled rejection Error: reference is not associated to user!

Associations:

Document:

associate: function(db) {
  Document.belongsTo(db.User, {foreignKey: 'user_id'}),
    Document.belongsTo(db.Reference, { foreignKey: 'reference_id'});;
}

Reference:

associate: function(db){
  Reference.hasMany(db.Document, { foreignKey: 'reference_id' });
}

Should I just chain queries instead?

Body:
It seems to me that your problem might be the associations, trying to link back to your primary key on Documents instead of the columns 'user_id' and 'reference_id'. You didn't post the table attributes so I might have understood this wrong.

Association on documents are ok.

Documents

associate: function(db) {
  Document.belongsTo(db.User, {foreignKey: 'user_id'}),  //key in documents
  Document.belongsTo(db.Reference, { foreignKey: 'reference_id'}); //key in documents
}

User

associate: function(db) {
  User.belongsTo(db.Document, {
    foreignKey: 'id',    //Key in User
    targetKey: 'user_id' //Key in Documents
  }),
}

Reference

associate: function(db) {
  Reference.belongsTo(db.Document, {
      foreignKey: 'id',         //Key in reference
      targetKey: 'reference_id' //Key in Documents
  }),
}

Also

For debbuging consider using logging so you can see the queries.

var sequelize = new Sequelize('database', 'username', 'password', {
    logging: console.log
    logging: function (str) {
        // do your own logging
    }
});


问:
Ansible - Fetching a file from a Windows remote share
I'm trying to get a file from a windows DFS share to the localhost (linux) to parse it later.

The path to the file is something like : \\windows_host\folder\file

And I'm trying to use the fetch module with something similar to this:

- name: Test
  hosts: all
  connection: local
  gather_facts: no
tasks:
    - name: Fetching a file from a Windows DFS Share
      fetch:
         src: \\windows_host\folder\file
         dest: local_folder/file
         flat: yes

But when I run it, it does not get the file and if I use the verbose option it says:

"msg": "the remote file does not exist, not transferring, ignored"

Though the file exists at the specific location.. so I think the problem is with the path encoding (I might be wrong) and I have tried a few different formats but so far no luck.

Does anyone know how to do that or what I'm doing wrong?

Alternative ways to get the file are also appreciated considering anyway that
I'm not allowed to mount the share or to have any service (ftp/http/etc..)  returning the file

Thanks in advance

ValerioG

答:
I actually managed to make it work using the command module and smbclient command in linux.
In case someone needs something similar, the playbook below works for me.

---
- name: Test
  hosts: all
  connection: local
  gather_facts: no
  vars_files:
    - vault_with_AD_credentials.yaml

  tasks:
    - name: Getting the Exchange Data file from Windows Share
      run_once: yes
      command: smbclient '\\windows_host\share' -c 'lcd local_folder; cd remote_folder; get filename' -U {{ ad_username }}%{{ ad_password }}
```


问:
html_attr "href" returns NA in rvest
My goal is to extract the urls associated with a specific css elements in a website using rvest. After looking at several other similar questions, I think I will need to use the html_attr function with the 'href' argument. With my present script this only returns NA values, although I would expect it to return urls.

Input to build variables

```<code>library(rvest)

my_url <- "http://www.sherdog.com/events/UFC-Fight-Night-111-Holm-vs-Correia-58241"

my_read_url <- read_html(my_url)

my_nodes <- html_nodes(my_read_url, ".fighter_result_data a span , .right_side a span , .left_side a span")
</code>```

Input to see if my_nodesare coming from the names of the athletes.

```<code>html_text(my_nodes)
</code>```

Output showing my_nodes are selecting the css elements I desire.

```<code>[1] "Holly Holm"          "Bethe Correia"       "Marcin Tybura"
 [4] "Andrei Arlovski"     "Colby Covington"     "Dong Hyun Kim"
 [7] "Rafael dos Anjos"    "Tarec Saffiedine"    "Jon Tuck"
[10] "Takanori Gomi"       "Walt Harris"         "Cyril Asker"
[13] "Alex Caceres"        "Rolando Dy"          "Yuta Sasaki"
[16] "Justin Scoggins"     "Jingliang Li"        "Frank Camacho"
[19] "Russell Doane"       "Kwan Ho Kwak"        "Naoki Inoue"
[22] "Carls John de Tomas" "Lucie Pudilova"      "Ji Yeon Kim"
</code>```

Input to try to get the urls to each of the athletes' unique pages.

```<code>html_attr(my_nodes, "href")
</code>```

Output showing that my attempt only returns a list of NA values

```<code>[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
</code>```

Can anyone help me actually obtain the urls instead of these NA values? Thank you!

答:
You are selecting the span elements, not the a elements in your html_nodes command. The span elements do not have an href= attribute, only the a elements do. Instead use

```<code>my_nodes <- html_nodes(my_read_url, ".fighter_result_data a, .right_side a, .left_side a")
html_text(my_nodes)
html_attr(my_nodes, "href")
</code>```

Title: html_attr "href" returns NA in rvest

Body:
My goal is to extract the urls associated with a specific css elements in a website using rvest. After looking at several other similar questions, I think I will need to use the html_attr function with the 'href' argument. With my present script this only returns NA values, although I would expect it to return urls.

Input to build variables

library(rvest)

my_url <- "http://www.sherdog.com/events/UFC-Fight-Night-111-Holm-vs-Correia-58241"

my_read_url <- read_html(my_url)

my_nodes <- html_nodes(my_read_url, ".fighter_result_data a span , .right_side a span , .left_side a span")

Input to see if my_nodesare coming from the names of the athletes.

html_text(my_nodes)

Output showing my_nodes are selecting the css elements I desire.

[1] "Holly Holm"          "Bethe Correia"       "Marcin Tybura"
 [4] "Andrei Arlovski"     "Colby Covington"     "Dong Hyun Kim"
 [7] "Rafael dos Anjos"    "Tarec Saffiedine"    "Jon Tuck"
[10] "Takanori Gomi"       "Walt Harris"         "Cyril Asker"
[13] "Alex Caceres"        "Rolando Dy"          "Yuta Sasaki"
[16] "Justin Scoggins"     "Jingliang Li"        "Frank Camacho"
[19] "Russell Doane"       "Kwan Ho Kwak"        "Naoki Inoue"
[22] "Carls John de Tomas" "Lucie Pudilova"      "Ji Yeon Kim"

Input to try to get the urls to each of the athletes' unique pages.

html_attr(my_nodes, "href")

Output showing that my attempt only returns a list of NA values

[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

Can anyone help me actually obtain the urls instead of these NA values? Thank you!

Body:
You are selecting the span elements, not the a elements in your html_nodes command. The span elements do not have an href= attribute, only the a elements do. Instead use

my_nodes <- html_nodes(my_read_url, ".fighter_result_data a, .right_side a, .left_side a")
html_text(my_nodes)
html_attr(my_nodes, "href")


问:
Division and remainder of large numbers in JavaScript
I'm trying to get the remainder of a large number, for example:

1551690021432628813 % 64

But I find that the it's a couple of digits too long for JavaScript. i.e. it's getting rounded to zero.

Is there a way around this other than using a 26kb library like BigInteger.js?

答:
You could break the number into chunks of 10 digits (from the right) and do the modular arithmetic on the chunks, combining the result at the end:

```<code>1551690021432628813 = 155169002 * 10**10 + 1432628813
</code>```

Hence

```<code>1551690021432628813 % 64 = (155169002 % 64 * (10**10) % 64  + 1432628813 % 64) % 64
</code>```

(Which equals 13).

You could write a recursive function that implements this idea. The following is in Python (which I am more fluent in) but should be easily translated into JavaScript:

```<code>def remainder(s,m):
    #computes int(s) % m, while just using small numbers
    #s is a string and m is an integer

    n = len(s)
    if n <= 10:
        return int(s) % m
    else:
        first = s[:n-10] #first n-10 digits in s
        second = s[-10:] #last 10 digits
        return (remainder(first,m) * ((10**10) % m) + int(second) % m) % m
</code>```

For the special case that the modulus is 64, there is an exceptionally easy approach: 64 divides 10**6 so, absolutely always

```<code>n % 64 == (last 6 digits of n) % 64
</code>```

For example,

```<code>1551690021432628813 % 64 = 628813 % 64 = 13
</code>```

Similar remarks hold whenever the modulus is a power of 2.

Body:
You could break the number into chunks of 10 digits (from the right) and do the modular arithmetic on the chunks, combining the result at the end:

1551690021432628813 = 155169002 * 10**10 + 1432628813

Hence

1551690021432628813 % 64 = (155169002 % 64 * (10**10) % 64  + 1432628813 % 64) % 64

(Which equals 13).

You could write a recursive function that implements this idea. The following is in Python (which I am more fluent in) but should be easily translated into JavaScript:

def remainder(s,m):
    #computes int(s) % m, while just using small numbers
    #s is a string and m is an integer

    n = len(s)
    if n <= 10:
        return int(s) % m
    else:
        first = s[:n-10] #first n-10 digits in s
        second = s[-10:] #last 10 digits
        return (remainder(first,m) * ((10**10) % m) + int(second) % m) % m

For the special case that the modulus is 64, there is an exceptionally easy approach: 64 divides 10**6 so, absolutely always

n % 64 == (last 6 digits of n) % 64

For example,

1551690021432628813 % 64 = 628813 % 64 = 13

Similar remarks hold whenever the modulus is a power of 2.


问:
MySQL: Number of subsequent occurrences
I have a table with four columns: id, from, to, msg.

The rows can look like this:

```<code>1 - foo - bar - hello
2 - foo - bar - zup?
3 - bar - foo - hi
4 - bar - foo - going okay
5 - bar - foo - you?
</code>```

Now I wanna know how many times "bar" has tried to "talk" to "foo" without response. Like I wanna count the number of occurrences since "foo" was on the sending end.

In this example, before the next entry, it should return 3.

Is this possible in pure (My)SQL?

I'm using php on the server side.

Thanks for any tips and advice! =)

答:
$sql = "SELECT `fieldone` FROM `table` WHERE `fieldone` = 'foo'";

$results = mysql_query($sql);

$FooSendNumber = mysql_num_rows($results);

or

$FooSendNumber = mysql_num_rows(mysql_query($sql));

Oh wait, you want to see pure MySQL too.

Yeah, it's possible:

$sql = "SELECT MYSQL_CALC_FOUND_ROWS `fieldone` FROM `table` WHERE `fieldone` = 'foo';SELECT FOUND_ROWS();"

Should work.

Oh wait, crap, I see, you wanted the number of times without response.

Title: MySQL: Number of subsequent occurrences

Body:
I have a table with four columns: id, from, to, msg.

The rows can look like this:

1 - foo - bar - hello
2 - foo - bar - zup?
3 - bar - foo - hi
4 - bar - foo - going okay
5 - bar - foo - you?

Now I wanna know how many times "bar" has tried to "talk" to "foo" without response. Like I wanna count the number of occurrences since "foo" was on the sending end.

In this example, before the next entry, it should return 3.

Is this possible in pure (My)SQL?

I'm using php on the server side.

Thanks for any tips and advice! =)


问:
How to implement recursive mutex with timeout in the OS X kernel?
I'm porting a windows device driver to Mac OS X.  The windows code uses KMUTEX.  This is a recursive lock that can be acquired multiple times by the same thread.  Other threads must wait to acquire it, but the acquisition will fail if the timeout occurs.

The I/O Kit's IORecursiveLock doesn't do timeouts.  I can use BSD locks or Mach locks.  The BSD part of the kernel offers condition variables with msleep() and wakeup().

I'm not clear if a condition variable will do what I want.

sem_timedwait(3) on BSD is in userspace.

Keith Shortridge provides a userspace set_timedwait implementation.  One thread calls sem_wait() while another thread that sends a signal to the first if a timeout occurs.

I could port Shortridge's code to the kernel but I don't want to risk screwing it up.  Google yields no other insight.  Can you give me a clue?

答:
This link might be helpful, by the documentation this has what you need, maybe the method wait_result_tlck_mtx_sleep_deadline:
https://developer.apple.com/library/content/documentation/Darwin/Conceptual/KernelProgramming/synchronization/synchronization.html#//apple_ref/doc/uid/TP30000905-CH218-BEHJDFCA</p>


问:
Dealing with interface data using mapstructure
I am getting data from the Hashicorp Vault API, and struggling to manipulate it because I have a hazy understanding of interfaces still :(

I am getting a TLS cert response from the PKI backend. Using go-dumper, it outputs this:

```<code>(0xc4203880c0) &Secret {
  RequestID: "271c63ef-d7b6-a084-18a0-966dd6989f03",
  LeaseID: "",
  LeaseDuration: 0 (int),
  Renewable: false,
  Data: map[string]interface {} {
    "serial_number": interface() ,
    "ca_chain": interface() ,
    "certificate": interface() ,
    "issuing_ca": interface() ,
    "private_key": interface() ,
    "private_key_type": interface()
  },
  Warnings: nil ([]string),
  Auth: nil (*api.SecretAuth),
  WrapInfo: nil (*api.SecretWrapInfo)
}
</code>```

What I'd like to do is print the "certficate" field using fmt. So I did this:

Created a struct:

```<code>type TLSCredentialResp struct {
  IssuingCA  string `mapstructure:"issuing_ca"`
  PrivateKey string `mapstructure:"private_key"`
  CAChain    string `mapstructure:"ca_chain"`
  Cert       string `mapstructure:"certificate"`
}
</code>```

and then used mapstructure to decode into it:

```<code>var response TLSCredentialResp
if err := mapstructure.Decode(docker.Data, &response); err != nil {
  log.Fatal("Error parsing vault's credential response: ", err)
}

fmt.Printf("Private Key: %s", response.PrivateKey)
</code>```

However, when I try this, I get the following:

```<code>Error parsing vault's credential response: 1 error(s) decoding:
* 'ca_chain' expected type 'string', got unconvertible type '[]interface {}'
exit status 1
</code>```

Now it's fairly clear to me I've gotten this wrong, as I'm trying to Decode an interface into a string. What isn't clear to me is how I deal with interface() as a type? Simply put, how can I get the plain text cert value out of that?

答:
So I'm an idiot, this was way easier than I expected.

I don't need to use mapstructure it seems, I can just do this:

```<code>fmt.Printf("Private Key: %s", docker.Data["private_key"])
fmt.Printf("Cert: %s", docker.Data["certificate"])
</code>```

Although I don't know why..

Body:
I am getting data from the Hashicorp Vault API, and struggling to manipulate it because I have a hazy understanding of interfaces still :(

I am getting a TLS cert response from the PKI backend. Using go-dumper, it outputs this:

(0xc4203880c0) &Secret {
  RequestID: "271c63ef-d7b6-a084-18a0-966dd6989f03",
  LeaseID: "",
  LeaseDuration: 0 (int),
  Renewable: false,
  Data: map[string]interface {} {
    "serial_number": interface() ,
    "ca_chain": interface() ,
    "certificate": interface() ,
    "issuing_ca": interface() ,
    "private_key": interface() ,
    "private_key_type": interface()
  },
  Warnings: nil ([]string),
  Auth: nil (*api.SecretAuth),
  WrapInfo: nil (*api.SecretWrapInfo)
}

What I'd like to do is print the "certficate" field using fmt. So I did this:

Created a struct:

type TLSCredentialResp struct {
  IssuingCA  string `mapstructure:"issuing_ca"`
  PrivateKey string `mapstructure:"private_key"`
  CAChain    string `mapstructure:"ca_chain"`
  Cert       string `mapstructure:"certificate"`
}

and then used mapstructure to decode into it:

var response TLSCredentialResp
if err := mapstructure.Decode(docker.Data, &response); err != nil {
  log.Fatal("Error parsing vault's credential response: ", err)
}

fmt.Printf("Private Key: %s", response.PrivateKey)

However, when I try this, I get the following:

Error parsing vault's credential response: 1 error(s) decoding:
* 'ca_chain' expected type 'string', got unconvertible type '[]interface {}'
exit status 1

Now it's fairly clear to me I've gotten this wrong, as I'm trying to Decode an interface into a string. What isn't clear to me is how I deal with interface() as a type? Simply put, how can I get the plain text cert value out of that?

Body:
So I'm an idiot, this was way easier than I expected.

I don't need to use mapstructure it seems, I can just do this:

fmt.Printf("Private Key: %s", docker.Data["private_key"])
fmt.Printf("Cert: %s", docker.Data["certificate"])

Although I don't know why..


问:
Fabricjs removed selected object
How can I remove a selected Object in Fabric js

Currently I can remove one selected object like following:

```<code>function removeCurrentObject(canvas) {
    $('#remove-current-object').click(function() {
        canvas.getActiveObject().remove();
    });
}
</code>```

But how can I check wether the user selectes more objects and remove them on an Event(click)

答:
```<code>function removeCurrentObject(canvas) {
$('#remove-current-object').click(function() {
  if(canvas.getActiveGroup()) {
    var objs = canvas.getActiveGroup();
    canvas.discardActiveGroup();
    objs.forEachObject(function(o) {
    canvas.remove(o)
   });
  } else {
   canvas.remove(canvas.getActiveObject());
  }
  });
}
</code>```

check if any active group there, if present remove one by one object from group

Title: Fabricjs removed selected object

Body:
How can I remove a selected Object in Fabric js

Currently I can remove one selected object like following:

function removeCurrentObject(canvas) {
    $('#remove-current-object').click(function() {
        canvas.getActiveObject().remove();
    });
}

But how can I check wether the user selectes more objects and remove them on an Event(click)

Body:
function removeCurrentObject(canvas) {
$('#remove-current-object').click(function() {
  if(canvas.getActiveGroup()) {
    var objs = canvas.getActiveGroup();
    canvas.discardActiveGroup();
    objs.forEachObject(function(o) {
    canvas.remove(o)
   });
  } else {
   canvas.remove(canvas.getActiveObject());
  }
  });
}

check if any active group there, if present remove one by one object from group


问:
Use a factory's sequence to generate unique phone numbers
I'm new to TDD, RSpec and factories, and trying to understand how to test that each User's phone number attribute is unique. To do so, I'm trying to use a sequence in my User factory. I'm not having much luck with the following:

```<code>FactoryGirl.define do
  factory :user do
    number = 123456789
    sequence(:phone_number) {|n| (number + n).to_s }
  end
end
</code>```

Any thoughts on the best way to accomplish this? Also, what kind of test would make sense for something like this where ultimately I would want to add the following validation to the user model to make such a test pass?

```<code>validates :phone_number, :uniqueness => true
</code>```

Thanks!

Body:
I'm new to TDD, RSpec and factories, and trying to understand how to test that each User's phone number attribute is unique. To do so, I'm trying to use a sequence in my User factory. I'm not having much luck with the following:

FactoryGirl.define do
  factory :user do
    number = 123456789
    sequence(:phone_number) {|n| (number + n).to_s }
  end
end

Any thoughts on the best way to accomplish this? Also, what kind of test would make sense for something like this where ultimately I would want to add the following validation to the user model to make such a test pass?

validates :phone_number, :uniqueness => true

Thanks!

Body:
To complete @westonplatter answer, in order to start at 0 000 000 000, you can use String#rjust:

FactoryGirl.define do
  factory :user do
    sequence(:phone_number) {|n| n.to_s.rjust(10, '0') }
  end
end

Example:

> 10.times { |n| puts n.to_s.rjust(10, '0') }
0000000000
0000000001
0000000002
0000000003
0000000004
0000000005
0000000006
0000000007
0000000008
0000000009


问:
program wont sort array after one previous sorting
This is what i have so far:

```<code>import java.util.*;
public class ProcessArray {

    public static void main(String[] args) {

        int[] arr = {3, 8, 1, 9, 2};
        System.out.println(Arrays.toString(arr));
        selectionSort(arr);
        System.out.println(Arrays.toString(arr));
        ProcessArray.oddArray(arr);
        System.out.println(Arrays.toString(arr));
        ProcessArray.evenArray(arr);
        System.out.println(Arrays.toString(arr));

    }

    public static void selectionSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int index = 0;
            for (int k = 0; k < arr.length - i; k++) {
                if (arr[k] > arr[index]) {
                    index = k;
                }
            }
            //swap
            int tmp = arr[index];
            arr[index] = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = tmp;
        }
    }

    public static int[] oddArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 == 0) {
                arr[i] = arr[i];
            }
        }
        return arr;
    }

    public static int[] evenArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 != 0) {
                arr[i] = arr[i];
            }
        }
        return arr;
    }

}
</code>```

For some reason when i go to run it, this is what im outputted with:

```<code>[3, 8, 1, 9, 2]
[1, 2, 3, 8, 9]
[1, 2, 3, 8, 9]
[1, 2, 3, 8, 9]
</code>```

How do i make odd Array and even Array work? Because the logic make sense, at least to me it does, but the program still just prints the output it got from selectionSort. Im sorry if this basic computer science knowledge, we just recently started learning about sorting.

答:
Well, there are few problems with your code.

arr[i] = arr[i]  does not make sense. Since arr is passed by reference to ***Array function it means that arr inside the main and arr inside oddArray are exactly the same array (same size and elements). So when you loop over testing for %2!=0 and do arr[i]=arr[i] you are not really changing the content of arr at all.

odd test should be %2!=0 and even %2==0

Now What I think you want to do is to filter the odd and even numbers from the original array. What you want to do is to count the number of odd numbers first, then create a new array of the size equal to the counter and then put only the elements of arr that are odd inside the new array.

Something as the following should work:

```<code>public static void main(String[] args) {

        int[] arr = {3, 8, 1, 9, 2};
        int[] res;
        System.out.println(Arrays.toString(arr));
        selectionSort(arr);
        System.out.println(Arrays.toString(arr));
        res = Test.oddArray(arr);
        System.out.println(Arrays.toString(res));
        res=Test.evenArray(arr);
        System.out.println(Arrays.toString(res));

    }

    public static int[] oddArray(int[] arr) {
        int c = 0;
        for (int i = 0; i < arr.length; i++)
            if (arr[i] % 2 != 0)
                c++;
         //c contains the number of odd number in arr
        int[] arr_c = new int[c];
        int ins=0;
        for (int i = 0; i < arr.length; i++)
            if (arr[i] % 2 != 0)
                arr_c[ins++]=arr[i];
        return arr_c;
    }

    public static int[] evenArray(int[] arr) {
        int c = 0;
        for (int i = 0; i < arr.length; i++)
            if (arr[i] % 2 == 0)
                c++;

        int[] arr_c = new int[c];
        int ins=0;
        for (int i = 0; i < arr.length; i++)
            if (arr[i] % 2 == 0)
                arr_c[ins++]=arr[i];
        return arr_c;
    }
</code>```

which outputs

```<code>[3, 8, 1, 9, 2]
[1, 2, 3, 8, 9]
[1, 3, 9]
[2, 8]
</code>```

Body:
This is what i have so far:

import java.util.*;
public class ProcessArray {

    public static void main(String[] args) {

        int[] arr = {3, 8, 1, 9, 2};
        System.out.println(Arrays.toString(arr));
        selectionSort(arr);
        System.out.println(Arrays.toString(arr));
        ProcessArray.oddArray(arr);
        System.out.println(Arrays.toString(arr));
        ProcessArray.evenArray(arr);
        System.out.println(Arrays.toString(arr));

    }

    public static void selectionSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int index = 0;
            for (int k = 0; k < arr.length - i; k++) {
                if (arr[k] > arr[index]) {
                    index = k;
                }
            }
            //swap
            int tmp = arr[index];
            arr[index] = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = tmp;
        }
    }

    public static int[] oddArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 == 0) {
                arr[i] = arr[i];
            }
        }
        return arr;
    }

    public static int[] evenArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 != 0) {
                arr[i] = arr[i];
            }
        }
        return arr;
    }

}

For some reason when i go to run it, this is what im outputted with:

[3, 8, 1, 9, 2]
[1, 2, 3, 8, 9]
[1, 2, 3, 8, 9]
[1, 2, 3, 8, 9]

How do i make odd Array and even Array work? Because the logic make sense, at least to me it does, but the program still just prints the output it got from selectionSort. Im sorry if this basic computer science knowledge, we just recently started learning about sorting.

Body:
Well, there are few problems with your code.

arr[i] = arr[i]  does not make sense. Since arr is passed by reference to ***Array function it means that arr inside the main and arr inside oddArray are exactly the same array (same size and elements). So when you loop over testing for %2!=0 and do arr[i]=arr[i] you are not really changing the content of arr at all.

odd test should be %2!=0 and even %2==0

Now What I think you want to do is to filter the odd and even numbers from the original array. What you want to do is to count the number of odd numbers first, then create a new array of the size equal to the counter and then put only the elements of arr that are odd inside the new array.

Something as the following should work:

public static void main(String[] args) {

        int[] arr = {3, 8, 1, 9, 2};
        int[] res;
        System.out.println(Arrays.toString(arr));
        selectionSort(arr);
        System.out.println(Arrays.toString(arr));
        res = Test.oddArray(arr);
        System.out.println(Arrays.toString(res));
        res=Test.evenArray(arr);
        System.out.println(Arrays.toString(res));

    }

    public static int[] oddArray(int[] arr) {
        int c = 0;
        for (int i = 0; i < arr.length; i++)
            if (arr[i] % 2 != 0)
                c++;
         //c contains the number of odd number in arr
        int[] arr_c = new int[c];
        int ins=0;
        for (int i = 0; i < arr.length; i++)
            if (arr[i] % 2 != 0)
                arr_c[ins++]=arr[i];
        return arr_c;
    }

    public static int[] evenArray(int[] arr) {
        int c = 0;
        for (int i = 0; i < arr.length; i++)
            if (arr[i] % 2 == 0)
                c++;

        int[] arr_c = new int[c];
        int ins=0;
        for (int i = 0; i < arr.length; i++)
            if (arr[i] % 2 == 0)
                arr_c[ins++]=arr[i];
        return arr_c;
    }

which outputs

[3, 8, 1, 9, 2]
[1, 2, 3, 8, 9]
[1, 3, 9]
[2, 8]


问:
Set all bits in unsigned to 1 if equal, 0 if not
How can I achieve the following with the minimum number of Intel instructions and without a branch or conditional move:

```<code>unsigned compare(unsigned x
  ,unsigned y) {
    return (x == y)? ~0 : 0;
}
</code>```

This is on hot code path and I need to squeeze out the most.

答:
return -int(x==y) is pretty terse C++. It's of course still up to the compiler to turn that into efficient assembly.

Works because int(true)==1 and unsigned (-1)==~0U.

Body:
How can I achieve the following with the minimum number of Intel instructions and without a branch or conditional move:

unsigned compare(unsigned x
  ,unsigned y) {
    return (x == y)? ~0 : 0;
}

This is on hot code path and I need to squeeze out the most.


问:
Is there any way to show remote references with git log?
```<code>git log --oneline
</code>```

The above command gives me the followed results:

```<code>5485b34 Modify: something
ccaf2c4 Modify: another thing
85a87e8 Bug Fix: the other thing
</code>```

But because I'm using gerrit and usually gerrit has it's change number as refs/changes/... format, I want to collect list framed as follows:

```<code>refs/changes/85/104085/9 Modify: something
refs/changes/33/104033/9 Modify: another thing
refs/changes/83/104183/2 Bug Fix: the other thing
</code>```

I know there is a way to obtain the mapping between commit IDs and remote references by using "git ls-remote". And by using "git ls-remote", I can make a script to obtain the above result. But is there any better and simpler way to obtain the above results?

答:
You can display references in logs with the --decorate option.

But it will only display the local and fetched references so the refs/changes/x/yyyy/zz won't be displayed, you have to fetch them first:

```<code>git config --add remote.origin.fetch refs/changes/*:refs/remotes/gerrit/changes/*
</code>```

Then you will get an output like this:

```<code># You can add '--all' to see other references not in the current history
$ git log --oneline --decorate
5485b34 (HEAD -> master, origin/master, origin/HEAD, gerrit/changes/85/104085/9) Modify: something
ccaf2c4 (gerrit/changes/33/104033/9) Modify: another thing
85a87e8 (gerrit/changes/83/104183/2) Bug Fix: the other thing
</code>```

Body:
git log --oneline

The above command gives me the followed results:

5485b34 Modify: something
ccaf2c4 Modify: another thing
85a87e8 Bug Fix: the other thing

But because I'm using gerrit and usually gerrit has it's change number as refs/changes/... format, I want to collect list framed as follows:

refs/changes/85/104085/9 Modify: something
refs/changes/33/104033/9 Modify: another thing
refs/changes/83/104183/2 Bug Fix: the other thing

I know there is a way to obtain the mapping between commit IDs and remote references by using "git ls-remote". And by using "git ls-remote", I can make a script to obtain the above result. But is there any better and simpler way to obtain the above results?

Body:
You can display references in logs with the --decorate option.

But it will only display the local and fetched references so the refs/changes/x/yyyy/zz won't be displayed, you have to fetch them first:

git config --add remote.origin.fetch refs/changes/*:refs/remotes/gerrit/changes/*

Then you will get an output like this:

# You can add '--all' to see other references not in the current history
$ git log --oneline --decorate
5485b34 (HEAD -> master, origin/master, origin/HEAD, gerrit/changes/85/104085/9) Modify: something
ccaf2c4 (gerrit/changes/33/104033/9) Modify: another thing
85a87e8 (gerrit/changes/83/104183/2) Bug Fix: the other thing


问:
React ProptTypes - object of objects
I have an object, which has dynamic keys(but the values are objects which have same keys):

```<code>menu = {
    dogs: {
        name: 'some name1',
        url: 'google.com'
    },
    cats: {
        name: 'some name2',
        url: 'facebook.com'
    },
    parrots: {
        name: 'some name3',
        url: 'linkedin.com'
    }
}
</code>```

Suppose I have a component:

```<code>const Menu = ({menu}) => (
    <div>
        {
            Object.keys(menu).map(key => (
                <div>{menu.name}</div>
            ))
        }
    </div>
);
</code>```

How to validate the menu prop using PropTypes?

答:
You could do the following using PropTypes.objectOf():

```<code>propTypes: {
  menu: PropTypes.objectOf(
    PropTypes.shape({
      name: PropTypes.string.isRequired,
      url: PropTypes.string.isRequired,
    })
  ).isRequired
}
</code>```

Title: React ProptTypes - object of objects

Body:
I have an object, which has dynamic keys(but the values are objects which have same keys):

menu = {
    dogs: {
        name: 'some name1',
        url: 'google.com'
    },
    cats: {
        name: 'some name2',
        url: 'facebook.com'
    },
    parrots: {
        name: 'some name3',
        url: 'linkedin.com'
    }
}

Suppose I have a component:

const Menu = ({menu}) => (

        {
            Object.keys(menu).map(key => (

{menu.name}

            ))
        }

);

How to validate the menu prop using PropTypes?

Body:
You could do the following using PropTypes.objectOf():

propTypes: {
  menu: PropTypes.objectOf(
    PropTypes.shape({
      name: PropTypes.string.isRequired,
      url: PropTypes.string.isRequired,
    })
  ).isRequired
}