问:
PHP read first item in object array
I have my code in PHP which is returning this Array of data:

```<code>GoCardlessPro\Core\ListResponse Object
(
    [records] => Array
        (
            [0] => GoCardlessPro\Resources\Mandate Object
                (
                    [model_name:protected] => Mandate
                    [created_at:protected] => 2017-04-01T16:49:09.642Z
                    [id:protected] => ID001
                    [links:protected] => stdClass Object
                        (
                            [customer_bank_account] => CB001
                            [creditor] => CR001
                            [customer] => CU001
                        )

                    [metadata:protected] => stdClass Object
                        (
                        )

                    [next_possible_charge_date:protected] => 2017-04-06
                    [payments_require_approval:protected] =>
                    [reference:protected] => RE001
                    [scheme:protected] => bacs
                    [status:protected] => active
                    [data:GoCardlessPro\Resources\BaseResource:private] => stdClass Object
                        (
                            [id] => 123
                            [created_at] => 2017-04-01T16:49:09.642Z
                            [reference] => RE001
                            [status] => active
                            [scheme] => bacs
                            [next_possible_charge_date] => 2017-04-06
                            [payments_require_approval] =>
                            [metadata] => stdClass Object
                                (
                                )

                            [links] => stdClass Object
                                (
                                    [customer_bank_account] => 001
                                    [creditor] => CR001
                                    [customer] => CU001
                                )

                        )

                    [api_response] =>
                )

        )
)
</code>```

I want to be able to read the ID of the first item in therecords array.

This data is contained inside a variable called $GC_Mandate;

I have tried these:

```<code>echo $GC_Mandate->records->{0}->id;

echo $GC_Mandate->records->0->id;

echo $GC_Mandate->records->[0]->id;

$GC_Mandate = $GC_Mandate->records;
echo $GC_Mandate->{0}->id;
</code>```

But none will return the data

答:
it will return all data ..for perticulat data put this in foreach loop</p>

```<code> print_r($GC_Mandate['records']);
</code>```

Title: PHP read first item in object array

Body:
I have my code in PHP which is returning this Array of data:

GoCardlessPro\Core\ListResponse Object
(
    [records] => Array
        (
            [0] => GoCardlessPro\Resources\Mandate Object
                (
                    [model_name:protected] => Mandate
                    [created_at:protected] => 2017-04-01T16:49:09.642Z
                    [id:protected] => ID001
                    [links:protected] => stdClass Object
                        (
                            [customer_bank_account] => CB001
                            [creditor] => CR001
                            [customer] => CU001
                        )

                    [metadata:protected] => stdClass Object
                        (
                        )

                    [next_possible_charge_date:protected] => 2017-04-06
                    [payments_require_approval:protected] =>
                    [reference:protected] => RE001
                    [scheme:protected] => bacs
                    [status:protected] => active
                    [data:GoCardlessPro\Resources\BaseResource:private] => stdClass Object
                        (
                            [id] => 123
                            [created_at] => 2017-04-01T16:49:09.642Z
                            [reference] => RE001
                            [status] => active
                            [scheme] => bacs
                            [next_possible_charge_date] => 2017-04-06
                            [payments_require_approval] =>
                            [metadata] => stdClass Object
                                (
                                )

                            [links] => stdClass Object
                                (
                                    [customer_bank_account] => 001
                                    [creditor] => CR001
                                    [customer] => CU001
                                )

                        )

                    [api_response] =>
                )

        )
)

I want to be able to read the ID of the first item in therecords array.

This data is contained inside a variable called $GC_Mandate;

I have tried these:

echo $GC_Mandate->records->{0}->id;

echo $GC_Mandate->records->0->id;

echo $GC_Mandate->records->[0]->id;

$GC_Mandate = $GC_Mandate->records;
echo $GC_Mandate->{0}->id;

But none will return the data

Body:
it will return all data ..for perticulat data put this in foreach loop

 print_r($GC_Mandate['records']);


来源: stackexchange

问:
Make div appear next to other
I have started a huge revision on my css knowledge.
I am trying to do the following:
I want to create a wrapper div that contains to divs with some text and some content.I want each div with class item-2 inside that div to have a width:50%
and appear next to another item-2.
Here is a snippet of my code:

body{
  background:rgba(10,10,10,.8);
}
.wrapper{
  position:relative;
  width:100%;
  margin:auto;
}
.item-2{
    text-align:center;
    display:inline-block;
    width:50%;
    border:2px solid blue;
 }
.demo{
  margin:auto;
  height:5em;
  width:5em;
  background:yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='wrapper'>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>

</div>  </code>```

As you can see it's div appears below its previous div.However I want them to be next to each other.How can I achieve this? I would like an explanation to your solution sa as to improve my knowledge

答:
aside float and flex, there's also:

display:table;

body{
  background:rgba(10,10,10,.8);
}
.wrapper{
  position:relative;
  width:100%;
  margin:auto;
  display:table;
  table-layout:fixed;/* to even cells and keep within width set */
}
.item-2{
    text-align:center;
    display:table-cell;
    border:2px solid blue;
 }
.demo{
  margin:auto;
  height:5em;
  width:5em;
  background:yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='wrapper'>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>

</div></code>```

display:grid;

body{
  background:rgba(10,10,10,.8);
}
.wrapper{
  position:relative;
  width:100%;
  margin:auto;
  display:grid;
  grid-template-columns:50% 50%;
}
.item-2{
    text-align:center;
    border:2px solid blue;
 }
.demo{
  margin:auto;
  height:5em;
  width:5em;
  background:yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='wrapper'>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>

</div></code>```

ContentLicense: CC BY-SA 3.0

Title: Make div appear next to other

Body:
I have started a huge revision on my css knowledge.
I am trying to do the following:
I want to create a wrapper div that contains to divs with some text and some content.I want each div with class item-2 inside that div to have a width:50%
and appear next to another item-2.
Here is a snippet of my code:

body{
  background:rgba(10,10,10,.8);
}
.wrapper{
  position:relative;
  width:100%;
  margin:auto;
}
.item-2{
    text-align:center;
    display:inline-block;
    width:50%;
    border:2px solid blue;
 }
.demo{
  margin:auto;
  height:5em;
  width:5em;
  background:yellow;
}

Title 1

Title 1

As you can see it's div appears below its previous div.However I want them to be next to each other.How can I achieve this? I would like an explanation to your solution sa as to improve my knowledge

Body:
aside float and flex, there's also:

display:table;

body{
  background:rgba(10,10,10,.8);
}
.wrapper{
  position:relative;
  width:100%;
  margin:auto;
  display:table;
  table-layout:fixed;/* to even cells and keep within width set */
}
.item-2{
    text-align:center;
    display:table-cell;
    border:2px solid blue;
 }
.demo{
  margin:auto;
  height:5em;
  width:5em;
  background:yellow;
}

<div class='wrapper'>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>

</div>

display:grid;

body{
  background:rgba(10,10,10,.8);
}
.wrapper{
  position:relative;
  width:100%;
  margin:auto;
  display:grid;
  grid-template-columns:50% 50%;
}
.item-2{
    text-align:center;
    border:2px solid blue;
 }
.demo{
  margin:auto;
  height:5em;
  width:5em;
  background:yellow;
}

<div class='wrapper'>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>

</div>


问:
Linq ToDictionary returns an anonymous type
I want to call a method that returns an anonymous type.  I need to know what the Type of this anonymous type is because I am returning it in a method.  Is it called "dynamic"?  When I debug, the watch window says the type is <>f__AnonymousType0.

Here is my code:

```<code>// this doesn't compile
public static Dictionary<int,dynamic> GetRuleNamesDictionary()
{
    List<ResponseRoutingRule> rules = GetResponseRoutingRules();
    var q = (rules.Select(r => new {r.ResponseRoutingRuleId, r.RuleName}));

    var dict1 = q.ToDictionary(d => d.ResponseRoutingRuleId);
    var dict = q.ToDictionary(d => d.ResponseRoutingRuleId, d => d.RuleName);
    return dict;
}

public static List<ResponseRoutingRule> GetResponseRoutingRules()
{
   ....
}

public class ResponseRoutingRule
{
    public int ResponseRoutingRuleId { get; set; }
    ....
    public string RuleName { get; set; }
    ...
}
</code>```

答: It's an object.  If you need strong typing, don't make it anonymous.</p>

ContentLicense: CC BY-SA 2.5

Body:
I want to call a method that returns an anonymous type.  I need to know what the Type of this anonymous type is because I am returning it in a method.  Is it called "dynamic"?  When I debug, the watch window says the type is <>f__AnonymousType0.

Here is my code:

// this doesn't compile
public static Dictionary<int,dynamic> GetRuleNamesDictionary()
{
    List<ResponseRoutingRule> rules = GetResponseRoutingRules();
    var q = (rules.Select(r => new {r.ResponseRoutingRuleId, r.RuleName}));

    var dict1 = q.ToDictionary(d => d.ResponseRoutingRuleId);
    var dict = q.ToDictionary(d => d.ResponseRoutingRuleId, d => d.RuleName);
    return dict;
}

public static List<ResponseRoutingRule> GetResponseRoutingRules()
{
   ....
}

public class ResponseRoutingRule
{
    public int ResponseRoutingRuleId { get; set; }
    ....
    public string RuleName { get; set; }
    ...
}


问:
Reuse connection when sending email with Javamail library
I'm trying to send a lot of email using the JavaMail API and am finding that the slowest part of my code (around 1 second per email) is the following:

```<code>long startSendTime = System.currentTimeMillis();
Transport transport = mailSession.getTransport();
transport.connect();
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();
long endTime = System.currentTimeMillis();
logger.info("Finished sending message, took: " + (endTime - startSendTime) + "ms");
</code>```

I am guessing this is because every email requires setting up a TCP connection. Is there a way to have a connection pool for email sending? Are there other libraries that are more performant which I could use?

答:
You have multiple options here depending on the result you are looking for.

With your current implementation, you add additional time for the socket connect / disconnect - this is what a connection pool would solve.

Option 1

With a connection pool, the result is that you grab an already established channel, and your only wait time is for that message to actually be sent.

This gives you the advantage in that you can return a response dependent on whether or not the message was actually sent through the relay successfully - this is still blocking network IO, and probably the longest of the calls.

Option 2

If you do not care about the response message, or can come back for it at a later time - you can optionally add the message to a queue somewhere else, where a separate thread, independent of the users interactions is doing the network IO. This will result in a much faster execution, as you end up with no blocking calls on your UI thread.

Body:
I'm trying to send a lot of email using the JavaMail API and am finding that the slowest part of my code (around 1 second per email) is the following:

long startSendTime = System.currentTimeMillis();
Transport transport = mailSession.getTransport();
transport.connect();
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();
long endTime = System.currentTimeMillis();
logger.info("Finished sending message, took: " + (endTime - startSendTime) + "ms");

I am guessing this is because every email requires setting up a TCP connection. Is there a way to have a connection pool for email sending? Are there other libraries that are more performant which I could use?


问:
How to mock Push notification native module in React native jest tests?
When using the module react-native-push-notification, I had this error:

```<code> FAIL  __tests__/index.android.js
  ● Test suite failed to run

    Invariant Violation: Native module cannot be null.

      at invariant (node_modules/fbjs/lib/invariant.js:44:15)
      at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:32:1)
      at Object.<anonymous> (node_modules/react-native/Libraries/PushNotificationIOS/PushNotificationIOS.js:18:29)
      at Object.get PushNotificationIOS [as PushNotificationIOS] (node_modules/react-native/Libraries/react-native/react-native.js:97:34)
      at Object.<anonymous> (node_modules/react-native-push-notification/component/index.ios.js:10:23)
</code>```

I tried to mock the module by creating __mocks__/react-native.js and putting this code within it:

```<code>const rn = require('react-native')

jest.mock('PushNotificationIOS', () => ({
  addEventListener: jest.fn(),
  requestPermissions: jest.fn(),
  then: jest.fn()
}));

module.exports = rn
</code>```

Now, I have this error:

```<code> FAIL  __tests__/index.android.js
  ● Test suite failed to run

    TypeError: Cannot read property 'then' of null

      at Object.<anonymous>.Notifications.popInitialNotification (node_modules/react-native-push-notification/index.js:278:42)
      at Object.<anonymous>.Notifications.configure (node_modules/react-native-push-notification/index.js:93:6)
      at Object.<anonymous> (app/utils/localPushNotification.js:4:39)
      at Object.<anonymous> (app/actions/trip.js:5:28)
</code>```

How I could mock fully this module the right way?

答: The problem is that in the line where the error is thrown, the lib tries to call getInitialNotification in the react-native module and expect an promise with some kind of result to be return. So you need to add this function to the mock and let it return a resolved promise.

Body:
When using the module react-native-push-notification, I had this error:

 FAIL  __tests__/index.android.js
  ● Test suite failed to run

    Invariant Violation: Native module cannot be null.

      at invariant (node_modules/fbjs/lib/invariant.js:44:15)
      at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:32:1)
      at Object.<anonymous> (node_modules/react-native/Libraries/PushNotificationIOS/PushNotificationIOS.js:18:29)
      at Object.get PushNotificationIOS [as PushNotificationIOS] (node_modules/react-native/Libraries/react-native/react-native.js:97:34)
      at Object.<anonymous> (node_modules/react-native-push-notification/component/index.ios.js:10:23)

I tried to mock the module by creating __mocks__/react-native.js and putting this code within it:

const rn = require('react-native')

jest.mock('PushNotificationIOS', () => ({
  addEventListener: jest.fn(),
  requestPermissions: jest.fn(),
  then: jest.fn()
}));

module.exports = rn

Now, I have this error:

 FAIL  __tests__/index.android.js
  ● Test suite failed to run

    TypeError: Cannot read property 'then' of null

      at Object.<anonymous>.Notifications.popInitialNotification (node_modules/react-native-push-notification/index.js:278:42)
      at Object.<anonymous>.Notifications.configure (node_modules/react-native-push-notification/index.js:93:6)
      at Object.<anonymous> (app/utils/localPushNotification.js:4:39)
      at Object.<anonymous> (app/actions/trip.js:5:28)

How I could mock fully this module the right way?


问:
Not able to apply display property on li element
i am a newbie to CSS,HTML and trying to understand lists.however something confuses me .As you can see below my HTML i am trying to create a drop down navigation bar.what i don't understand is why would display property won't work on a single li element.

  ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>
.block1{background-color:#736570;margin:0px;}
ul a {color:white;}
ul li{list-style-type: none; padding:5px;}

.hidden {display:none;}
.home:hover .hidden{display:block;}
.hidden a:hover{background-color: #f1f1f1;}</code>```

Home

  contact us

about

Investor

 what we do

```

答:
i don't understand is why would display property won't work on a
  single li element.

The div with class .home is not the parent of li tag with class hidden. Hence it will never trigger a hover over that. Whenever you trigger a hover over a parent container it trickles down and find its children and does some sort of styling.

In your case, you are trying to use display:none to hide a li and make it display by means of hover.

Consider the snippet below, whenever you hover over the parent container, the li tag is being displayed. (This approach below does not make a drop down menu for you but it is give you some insight how to make that display property change on hover)

.block1 {
  background-color: #736570;
  margin: 0px;
}

ul a {
  color: white;
}

ul li {
  list-style-type: none;
  padding: 5px;
}

.hidden {
  display: none;
}

.block1:hover .hidden {
  display: block;
}

.hidden a:hover {
  background-color: #f1f1f1;
}

.home```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<body>
  <ul class="block1">
    <li class="home">Home

      <li class="hidden">
        contact us
      </li>

      <li>about
        <li>
          <li>Investor</li>
          <li> what we do</li>
        </li>
  </ul>

</body>

</html></code>```

Body:
i am a newbie to CSS,HTML and trying to understand lists.however something confuses me .As you can see below my HTML i am trying to create a drop down navigation bar.what i don't understand is why would display property won't work on a single li element.

.block1{background-color:#736570;margin:0px;}
ul a {color:white;}
ul li{list-style-type: none; padding:5px;}

.hidden {display:none;}
.home:hover .hidden{display:block;}
.hidden a:hover{background-color: #f1f1f1;}

Home

  contact us

about

Investor

 what we do

Body:
i don't understand is why would display property won't work on a
  single li element.

The div with class .home is not the parent of li tag with class hidden. Hence it will never trigger a hover over that. Whenever you trigger a hover over a parent container it trickles down and find its children and does some sort of styling.

In your case, you are trying to use display:none to hide a li and make it display by means of hover.

Consider the snippet below, whenever you hover over the parent container, the li tag is being displayed. (This approach below does not make a drop down menu for you but it is give you some insight how to make that display property change on hover)

.block1 {
  background-color: #736570;
  margin: 0px;
}

ul a {
  color: white;
}

ul li {
  list-style-type: none;
  padding: 5px;
}

.hidden {
  display: none;
}

.block1:hover .hidden {
  display: block;
}

.hidden a:hover {
  background-color: #f1f1f1;
}

.home

<html>

<body>
  <ul class="block1">
    <li class="home"><a href="#">Home</a>

      <li class="hidden">
        <a href="#">contact us</a>
      </li>

      <li><a href="#">about</a>
        <li>
          <li><a href="#">Investor</a></li>
          <li> <a href="#">what we do</a></li>
        </li>
  </ul>

</body>

</html>


问:
Certificate Pinning on AWS Lambda
Certificate Pinning on AWS Lambda

Can handler functions in AWS lambda, invoked by API Gateway, reach down into the connection layer of the request at all to access what certificate was used to establish the SSL/TLS connection on the client side? I'd like to implement a certificate pinning strategy for the API I'm building as I've found a dozen ways in which SSL without pinning can be bypassed and the data in my API is not social media posts.

Any Alternatives if not possible?

If Lambda functions don't have access to the connection layer is there a comparable way of further enforcing security and not simply saying "SSL is enough"

Last Resort

If Lambda doesn't give me access to the certificate info of the client connections I'll have to resort to asymmetric encryption.

答:
An AWS Lambda function doesn't have a direct connection with an HTTP request, it can be invoked by a lot of things, e.g. an SNS subscription, or a simple SDK invocation. Or, and that's I guess what you're aiming at, you can invoke a Lambda function via the AWS API Gateway. </p>

<p>So if you want any HTTP or TLS details in your Lambda function, you need to make sure that the API Gateway is somehow injecting that data into the payload that's going to the Lambda function. I'm not sure if that's possible, a deep dive into some API Gateway documentation will probably help you further. </p>

Title: Certificate Pinning on AWS Lambda

Body:
An AWS Lambda function doesn't have a direct connection with an HTTP request, it can be invoked by a lot of things, e.g. an SNS subscription, or a simple SDK invocation. Or, and that's I guess what you're aiming at, you can invoke a Lambda function via the AWS API Gateway.

So if you want any HTTP or TLS details in your Lambda function, you need to make sure that the API Gateway is somehow injecting that data into the payload that's going to the Lambda function. I'm not sure if that's possible, a deep dive into some API Gateway documentation will probably help you further.


问:
posting object to controller mvc2 from silverlight
i have an application on mvc that have a controller with a post method

```<code>[HttpPost]
public EmptyResult(DispositivoMovil dispositivo)
{
  try
  {
     //Something
  }
}
</code>```

And I have another silverlight application that need to use this method, how can i send a DispositivoMovil object to this method?

答:
You can't directly send an object to this controller from a Silverlight application. You need to send an HTTP POST request by using a WebClient for example and passing the values in the POST body. Here's an example:

```<code>var client = new WebClient();
var values = new NameValueCollection
{
    { "PropName1", "value 1" },
    { "PropName2", "value 2" },
    { "ComplexPropName3.SimpleProp", "value 3" },
    // And so on for each value in the DispositivoMovil
};
client.UploadValuesCompleted += (sender, e) =>
{
    byte[] result = e.Result;
    // TODO: Do something with the response returned from the controller
};
client.UploadValuesAsync(new Uri("http://example.com/home/emptyresult"), values);
</code>```

For more advanced binding scenarios you could take a look at this blog post.

Body:
i have an application on mvc that have a controller with a post method

[HttpPost]
public EmptyResult(DispositivoMovil dispositivo)
{
  try
  {
     //Something
  }
}

And I have another silverlight application that need to use this method, how can i send a DispositivoMovil object to this method?

Body:
You can't directly send an object to this controller from a Silverlight application. You need to send an HTTP POST request by using a WebClient for example and passing the values in the POST body. Here's an example:

var client = new WebClient();
var values = new NameValueCollection
{
    { "PropName1", "value 1" },
    { "PropName2", "value 2" },
    { "ComplexPropName3.SimpleProp", "value 3" },
    // And so on for each value in the DispositivoMovil
};
client.UploadValuesCompleted += (sender, e) =>
{
    byte[] result = e.Result;
    // TODO: Do something with the response returned from the controller
};
client.UploadValuesAsync(new Uri("http://example.com/home/emptyresult"), values);

For more advanced binding scenarios you could take a look at this blog post.


问:
HTML/CSS code for creating a Table
I am currently working on this assignment for school. I have two issues I can't find the solution for.

HTML Validation gives me this error - A table row was 5 columns wide and exceeded the column count established by the first row (4).
From line 72, column 5; to line 72, column 9

As you can see on the table there is an extra column at the end that is very small. I am not sure how to eliminate that.

table {
 margin: auto;
 border: 1px solid #3399cc;
 width: 90%;
 border-collapse: collapse;
    }

    td, th {
 padding: 5px;
 border: 1px solid #3399cc;
    }

    td {
 text-align: center;
    }

    .text {
 text-align: left;
    }

    tr:nth-of-type(even) {
 background-color: #f5fafc
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <th id="package-names">Package Name</th>
    <th id="description">Description</th>
    <th id="nights">Nights</th>
    <th id="cost-per-person">Cost per Person</th>
  </tr>
  <tr>
    <td headers="package-names">Weekend Escape</td>
    <td headers="description" class="text">Two breakfasts, a     trail map, a picnic snack</td>
    <td headers="nights">2</td>
    <td headers="cost-per-person">$450</td>
  </tr>
  <tr>
    <td headers="package-names">Zen Retreat</td>
    <td headers="description" class="text">Four breakfasts, a trail map, a pass for daily yoga</td>
    <td headers="nights">4</td>
    <td headers="cost-per-person">$600</td>
  </tr>
  <tr>
    <td headers="package-names">Kayak Away</td>
    <td headers="description" class="text">Two breakfasts, two hours of kayak rental daily, a trail map</td>
    <td headers="nights">2</td>
    <td headers="cost-per-person">$500<td>
  </tr>
</table></code>```

答:
You're simply missing a slash in your closing  on the last row, which should look like so:

```<code><td headers="cost-per-person">$500</td>
</code>```

Fixed Version: http://codepen.io/alexgurrola/pen/EWrNEv?editors=1000

Title: HTML/CSS code for creating a Table

Body:
I am currently working on this assignment for school. I have two issues I can't find the solution for.

HTML Validation gives me this error - A table row was 5 columns wide and exceeded the column count established by the first row (4).
From line 72, column 5; to line 72, column 9

As you can see on the table there is an extra column at the end that is very small. I am not sure how to eliminate that.

table {
 margin: auto;
 border: 1px solid #3399cc;
 width: 90%;
 border-collapse: collapse;
    }

    td, th {
 padding: 5px;
 border: 1px solid #3399cc;
    }

    td {
 text-align: center;
    }

    .text {
 text-align: left;
    }

    tr:nth-of-type(even) {
 background-color: #f5fafc
    }

    Package Name
    Description
    Nights
    Cost per Person

    Weekend Escape
    Two breakfasts, a     trail map, a picnic snack
    2
    $450

    Zen Retreat
    Four breakfasts, a trail map, a pass for daily yoga
    4
    $600

    Kayak Away
    Two breakfasts, two hours of kayak rental daily, a trail map
    2
    $500

Body:
You're simply missing a slash in your closing <td> on the last row, which should look like so:

<td headers="cost-per-person">$500</td>

Fixed Version: http://codepen.io/alexgurrola/pen/EWrNEv?editors=1000


问:
jQuery: 'load more' masonry elements?
I have a few elements on my page which I'm loading 5 at a time.

What I need to do is to animate the loaded elements using animate.css.

To explain this, I've created this fiddle:

https://jsfiddle.net/89v781rL/6/

Scroll down to see the Show more button and click on it to see it in action.

When i load more items, the elements are animated but because they are layed out in a Masonry style, the position of them keep changing which is not what i want. Basically I need to keep the elements in their first position and keep adding/loading more elements.

If you comment out the following CSS code and run the JSFIDDLE, you will see how nicely the elements are layed out and that is how i want them to be when they are loading 5 at a time too:

```<code>#grid li:nth-child(n+6) {
  /*display: none;*/
}
</code>```

what I need to do is to bounce the elements UP using animate.css.

This is my full code:

```<code>$('#sales').click(function() {
$('#grid li').not(':visible').slice(0, 5).slideDown();

$('#grid li').not(':visible').slice(0, 5).addClass('animated bounceInUp');
});
</code>```

Note: I don't want to use any plugins like this

Mainly because it is very big and bloated for my project and it doesn't function properly in my project either.

Could someone please advise on this issue?

EDIT:

Here is another failed attempt to do this:

https://jsfiddle.net/89v781rL/8/

And this one too:

https://jsfiddle.net/89v781rL/9/

答:
I don't think you will be able to achieve this effect using the column-count css because of the way it calculates the columns. When you set 'display:none;' on an item the positioning of the items in columns behaves as if it didn't exist. It seems the columns are also taking into account the height of the element.

My suggestion is could you change your approach and rather use your own wrappers for columns and your own javascript/jquery?

Anyway looking at this problem and searching around I found that your question appears to be a duplicate on here and here is the answer (similar conclusion to mine but there's a clever workaround too): CSS column-count elements jumping across columns

Title: jQuery: 'load more' masonry elements?

Body:
I have a few elements on my page which I'm loading 5 at a time.

What I need to do is to animate the loaded elements using animate.css.

To explain this, I've created this fiddle:

https://jsfiddle.net/89v781rL/6/

Scroll down to see the Show more button and click on it to see it in action.

When i load more items, the elements are animated but because they are layed out in a Masonry style, the position of them keep changing which is not what i want. Basically I need to keep the elements in their first position and keep adding/loading more elements.

If you comment out the following CSS code and run the JSFIDDLE, you will see how nicely the elements are layed out and that is how i want them to be when they are loading 5 at a time too:

#grid li:nth-child(n+6) {
  /*display: none;*/
}

what I need to do is to bounce the elements UP using animate.css.

This is my full code:

$('#sales').click(function() {
$('#grid li').not(':visible').slice(0, 5).slideDown();

$('#grid li').not(':visible').slice(0, 5).addClass('animated bounceInUp');
});

Note: I don't want to use any plugins like this

Mainly because it is very big and bloated for my project and it doesn't function properly in my project either.

Could someone please advise on this issue?

EDIT:

Here is another failed attempt to do this:

https://jsfiddle.net/89v781rL/8/

And this one too:

https://jsfiddle.net/89v781rL/9/


问:
How can I check for a specific class using javascript?
So I need to be able to check if a specified id has a specific class, but I'm not completely sure on how to do that.

Here is my code. You can see my attempt at checking a id for a specific class in the homeTransition function.

function homeTransition()
    {
        if(document.getElementById("aboutContent").hasClass("animated fadeInUp")){
            document.getElementById("aboutContent").className = " animated slideOutDown";
        } else if(document.getElementById("projectsContent").hasClass("animated fadeInUp")){
            document.getElementById("projectsContent").className = " animated slideOutDown";
            } else if(document.getElementById("contactContent").hasClass("animated fadeInUp")){
                document.getElementById("contactContent").className = " animated slideOutDown";
            }
                    document.getElementById("astronaut").className = " animated fadeIn";
    }

function aboutTransition()
    {
        document.getElementById("astronaut").className = " animated fadeOut";
        document.getElementById("aboutContent").className = " animated fadeInUp";

        document.getElementById("projectsContent").className = " animated fadeOutLeft";
        document.getElementById("contactContent").className = " animated fadeOutLeft";
    }

function projectsTransition()
    {
        document.getElementById("astronaut").className = " animated fadeOut";
        document.getElementById("projectsContent").className = " animated fadeInUp";

        document.getElementById("aboutContent").className = " animated fadeOutLeft";
        document.getElementById("contactContent").className = " animated fadeOutLeft";
    }

function contactTransition()
    {
        document.getElementById("astronaut").className = " animated fadeOut";
        document.getElementById("contactContent").className = " animated fadeInUp";

        document.getElementById("aboutContent").className = " animated fadeOutLeft";
        document.getElementById("projectsContent").className = " animated fadeOutLeft";
    }

//Menu
function expand(){
  $(this).toggleClass("on");
  $(".menu").toggleClass("active");
};
$(".button").on('click', expand);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color: black;
  overflow: hidden;
}

#aboutContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: #2b2b41;
  z-index: -1;
}

#projectsContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: #42424b;
  z-index: -1;
}

#contactContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: #353440;
  z-index: -1;
}

.menu {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  background: rgba(45, 51, 54, 0.9);
  width: 18%;
  box-sizing: border-box;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  text-align:center;
  box-shadow: 0 0 20px #000000;
}

.active {
  transform: translateZ(0) translateX(0);
  transform: translateZ(0) translateX(0);
  -webkit-transition: 0.4s;
  transition: 0.4s;
  color: #e5e5e5;
}

h1 {
  margin-top:60%;
  font-size: 2.5em;
  cursor: default;
}

ul {
  padding:0;
  list-style:none;
  font-size:14px;
}

li {
  padding:10px 10px;
}

a {
  text-decoration:none;
  padding:10px 15px;
  color:#fff;
  font-family:"Roboto";
  font-size: 1.5em;
  font-weight: 300;
}

a:hover {
  text-decoration: line-through;
  color: #0dffec;
}

.content {
  position:relative;
  width:300px;
}

.button {
  width:20px;
  height:40px;
  margin:24% 36%;
  padding: 14px;
  cursor:pointer;
}

.line {
 width: 40px;
 height: 2px;
    background-color: #fff;
 transition: transform 0.3s ease, background 0.3s ease, opacity 0.3s ease, top 0.3s ease;
}

.line.first {
  transform: translateX(-10px) translateY(22px) rotate(-90deg);
}

.line.second {
  transform: translateX(-10px) translateY(19px) rotate(0deg);
}

.button.on .line.top {
 transform: translateX(-10px) translateY(20px) rotate(45deg);
}

.button.on .line.bottom {
 transform: translateX(-10px) translateY(17px)rotate(-45deg);
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play|Raleway" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">
    <link rel="stylesheet" type="text/css" href="css/animate.css">

Title

 home

 about

 projects

 contact

```

答:
You can check like this

```<code>document.getElementById("projectsContent").className.indexOf("animated") !== -1 // class exists on element
</code>```

But for this you can check for only one class, if you want to check for multiple classes store the className in a variable and check for all of them or write a utility function.

EDIT:

As mentioned by @Jerinaw in comment you can also use the below code, which is much shorter than above if you don't need support for < ie10

```<code>document.getElementById("projectsContent").classList.contains("animated") // class exists on element
</code>```

Body:
So I need to be able to check if a specified id has a specific class, but I'm not completely sure on how to do that.

Here is my code. You can see my attempt at checking a id for a specific class in the homeTransition function.

function homeTransition()
    {
        if(document.getElementById("aboutContent").hasClass("animated fadeInUp")){
            document.getElementById("aboutContent").className = " animated slideOutDown";
        } else if(document.getElementById("projectsContent").hasClass("animated fadeInUp")){
            document.getElementById("projectsContent").className = " animated slideOutDown";
            } else if(document.getElementById("contactContent").hasClass("animated fadeInUp")){
                document.getElementById("contactContent").className = " animated slideOutDown";
            }
                    document.getElementById("astronaut").className = " animated fadeIn";
    }

function aboutTransition()
    {
        document.getElementById("astronaut").className = " animated fadeOut";
        document.getElementById("aboutContent").className = " animated fadeInUp";

        document.getElementById("projectsContent").className = " animated fadeOutLeft";
        document.getElementById("contactContent").className = " animated fadeOutLeft";
    }

function projectsTransition()
    {
        document.getElementById("astronaut").className = " animated fadeOut";
        document.getElementById("projectsContent").className = " animated fadeInUp";

        document.getElementById("aboutContent").className = " animated fadeOutLeft";
        document.getElementById("contactContent").className = " animated fadeOutLeft";
    }

function contactTransition()
    {
        document.getElementById("astronaut").className = " animated fadeOut";
        document.getElementById("contactContent").className = " animated fadeInUp";

        document.getElementById("aboutContent").className = " animated fadeOutLeft";
        document.getElementById("projectsContent").className = " animated fadeOutLeft";
    }

//Menu
function expand(){
  $(this).toggleClass("on");
  $(".menu").toggleClass("active");
};
$(".button").on('click', expand);

body {
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color: black;
  overflow: hidden;
}

#aboutContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: #2b2b41;
  z-index: -1;
}

#projectsContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: #42424b;
  z-index: -1;
}

#contactContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: #353440;
  z-index: -1;
}

.menu {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  background: rgba(45, 51, 54, 0.9);
  width: 18%;
  box-sizing: border-box;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  text-align:center;
  box-shadow: 0 0 20px #000000;
}

.active {
  transform: translateZ(0) translateX(0);
  transform: translateZ(0) translateX(0);
  -webkit-transition: 0.4s;
  transition: 0.4s;
  color: #e5e5e5;
}

h1 {
  margin-top:60%;
  font-size: 2.5em;
  cursor: default;
}

ul {
  padding:0;
  list-style:none;
  font-size:14px;
}

li {
  padding:10px 10px;
}

a {
  text-decoration:none;
  padding:10px 15px;
  color:#fff;
  font-family:"Roboto";
  font-size: 1.5em;
  font-weight: 300;
}

a:hover {
  text-decoration: line-through;
  color: #0dffec;
}

.content {
  position:relative;
  width:300px;
}

.button {
  width:20px;
  height:40px;
  margin:24% 36%;
  padding: 14px;
  cursor:pointer;
}

.line {
 width: 40px;
 height: 2px;
    background-color: #fff;
 transition: transform 0.3s ease, background 0.3s ease, opacity 0.3s ease, top 0.3s ease;
}

.line.first {
  transform: translateX(-10px) translateY(22px) rotate(-90deg);
}

.line.second {
  transform: translateX(-10px) translateY(19px) rotate(0deg);
}

.button.on .line.top {
 transform: translateX(-10px) translateY(20px) rotate(45deg);
}

.button.on .line.bottom {
 transform: translateX(-10px) translateY(17px)rotate(-45deg);
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}
@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Home</title>

    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Play|Raleway" rel="stylesheet">

    <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css'>

    <link rel="stylesheet" type="text/css" href="css/style.css">
    <link rel="stylesheet" type="text/css" href="css/animate.css">

Title

 home

 about

 projects

 contact

Body:
You can check like this

document.getElementById("projectsContent").className.indexOf("animated") !== -1 // class exists on element

But for this you can check for only one class, if you want to check for multiple classes store the className in a variable and check for all of them or write a utility function.

EDIT:

As mentioned by @Jerinaw in comment you can also use the below code, which is much shorter than above if you don't need support for < ie10

document.getElementById("projectsContent").classList.contains("animated") // class exists on element


问:
Join/Merge data frames on inconsistent time stamps with long and wide data
I have two data frames,

df3 has a time stamp with date and time, user id, and heart rate with multiple observations (long data)

df4 has a time stamp with date only, user id, calories and sleep (wide data)

I would like to combine them so that the data frame with long data can be filled in with the data frame with wide data based on the date and user id

Here is the code for a toy data set with a similar layout

```<code>df3 <- data.frame(  time_stamp=c('2016-11-01 10:29:41','2016-11-01 10:53:11','2016-11-02 01:07:54','2016-11-02 02:00:40','2016-11-02 04:01:33','2016-11-02 05:23:53','2016-11-02 13:20:17'),
               users_user_id=c(7,7,7,7,7,7,7),
               avg_heart_rate=c(94,90,88,85,91,89,95))
df4 <- data.frame(  time_stamp=c('2016-11-01','2016-11-02'), users_user_id=c(7,7), calories=c(1800,2000), sleep=c(480,560))
df3$time_stamp <- as.POSIXct(df3$time_stamp)
df4$time_stamp <- as.POSIXct(df4$time_stamp)
</code>```

I tried splitting the time from the date, but then when I did a full_join on dplyr using the time stamp and userID I was left with a lot of NAs. I tried looking up how to use reshape2 to melt my data? but I'm lost as to how it could help me...

Body:
I have two data frames,

df3 has a time stamp with date and time, user id, and heart rate with multiple observations (long data)

df4 has a time stamp with date only, user id, calories and sleep (wide data)

I would like to combine them so that the data frame with long data can be filled in with the data frame with wide data based on the date and user id

Here is the code for a toy data set with a similar layout

df3 <- data.frame(  time_stamp=c('2016-11-01 10:29:41','2016-11-01 10:53:11','2016-11-02 01:07:54','2016-11-02 02:00:40','2016-11-02 04:01:33','2016-11-02 05:23:53','2016-11-02 13:20:17'),
               users_user_id=c(7,7,7,7,7,7,7),
               avg_heart_rate=c(94,90,88,85,91,89,95))
df4 <- data.frame(  time_stamp=c('2016-11-01','2016-11-02'), users_user_id=c(7,7), calories=c(1800,2000), sleep=c(480,560))
df3$time_stamp <- as.POSIXct(df3$time_stamp)
df4$time_stamp <- as.POSIXct(df4$time_stamp)

I tried splitting the time from the date, but then when I did a full_join on dplyr using the time stamp and userID I was left with a lot of NAs. I tried looking up how to use reshape2 to melt my data? but I'm lost as to how it could help me...

Body:
You could create a new column that just contains the date information and merge on that:

df3$date <- as.Date(df3$time_stamp)
df4$date <- as.Date(df4$time_stamp)
merge(df3, df4, by = c("date", "users_user_id"))

Gives you:

        date users_user_id        time_stamp.x avg_heart_rate time_stamp.y calories sleep
1 2016-11-01             7 2016-11-01 10:29:41             94   2016-11-01     1800   480
2 2016-11-01             7 2016-11-01 10:53:11             90   2016-11-01     1800   480
3 2016-11-02             7 2016-11-02 01:07:54             88   2016-11-02     2000   560
4 2016-11-02             7 2016-11-02 02:00:40             85   2016-11-02     2000   560
5 2016-11-02             7 2016-11-02 04:01:33             91   2016-11-02     2000   560
6 2016-11-02             7 2016-11-02 05:23:53             89   2016-11-02     2000   560
7 2016-11-02             7 2016-11-02 13:20:17             95   2016-11-02     2000   560


问:
Does it make sense to use `ordered_set` for `select` statement with `>` and `<=` for lowering time compexity
I use ETS table of type ordered_set, and row looks like {{integer_value, string}} (basically it has no value, only key).

When I perform ets:select(tab, [match_spec]), what match_spec does is selecting all rows, where integer_value meets greater than and lower than comprehensions.

I wonder, do I benefit and instead of scanning whole table, find both lower and upper bounds in logarithmic time and then get all elements in between, like I would expect from SQL table, or such functionality is not implemented in ETS and there is no particular benefit from using ordered_set instead of ordinary set?

答:
Simple way is using timer:tc/3 function for getting execution time of your functions or ets module's functions.

You can profile your code using fprof or eprof for undestanding what function called and how much time it takes for its execution.

This can help you.

If you are not familiar with erlang profilers, i can show simple example of ets set and ordered_set with profilers.


问:
How can I create a custom View with a Relative Size?
I would like to design an application which could work with devices of any screen resolution.

My idea to do so was to create one Custom View for each type of View I use, and use the layout_width and layout_height specified in the XML as a percentage of the parent size (for example, layout_width="100dp" is equivalent to fill_parent, and layout_width="50dp" means the View's width will be half the parent's one).

Here is the custom TextView class I made:

```<code>public class RSTextView extends TextView {

    public RSTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int w, int h) {
        int parentWidth = ((View)this.getParent()).getWidth();
        int parentHeight = ((View)this.getParent()).getHeight();
        Log.i(null, "Width: " + w + "; Height: " + parentHeight);
        this.setMeasuredDimension(parentWidth * MeasureSpec.getSize(w) / 100,
                parentHeight * MeasureSpec.getSize(h) / 100);
    }
}
</code>```

However, it does not work. The parentWidth and parentHeight size is always 0.

Is there any better way to create an application with a relative size?

And if it is the right way to go, how can I retrieve the View's parents' size from the onMeasure method?

答:
Since you're checking a view's height during the layout phase, you probably want to be using getMeasuredHeight, not getHeight, but I'm not sure you need to be doing what you're doing at all. It's hard to tell from your description, but it seems like you might be trying to recreate the behavior of LinearLayout weights. For example, if you have a horizontal LinearLayout with 3 children, you can easily set the first to take up half its width and the others each to take up 25% by assigning them 0px layout_widths and layout_weights of 2, 1 and 1 respectively (or any other weights of those proportions).

If you do decide to go the custom View route, though, don't overload what layout_height and layout_width do -- use custom XML attributes to take the argument for the percentages (I'd dig into LinearLayout's code to see how layout_weight is implemented).

ContentLicense: CC BY-SA 4.0

Body:
I would like to design an application which could work with devices of any screen resolution.

My idea to do so was to create one Custom View for each type of View I use, and use the layout_width and layout_height specified in the XML as a percentage of the parent size (for example, layout_width="100dp" is equivalent to fill_parent, and layout_width="50dp" means the View's width will be half the parent's one).

Here is the custom TextView class I made:

public class RSTextView extends TextView {

    public RSTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int w, int h) {
        int parentWidth = ((View)this.getParent()).getWidth();
        int parentHeight = ((View)this.getParent()).getHeight();
        Log.i(null, "Width: " + w + "; Height: " + parentHeight);
        this.setMeasuredDimension(parentWidth * MeasureSpec.getSize(w) / 100,
                parentHeight * MeasureSpec.getSize(h) / 100);
    }
}

However, it does not work. The parentWidth and parentHeight size is always 0.

Is there any better way to create an application with a relative size?

And if it is the right way to go, how can I retrieve the View's parents' size from the onMeasure method?


问:
Java Servlets and Raspberry Pi IO
I'm trying to learn how to write simple servlets to use with a Raspberry Pi.
I want to control the board I/O via web.I'm using the Pi4J library which is a wrapper for the WiringPi C library.It works when I use it to blink a led locally so I assume that I'm doing something wrong coding my servlet.

This is the code I wrote:

```<code>package com.luca.servlet;

import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.io.gpio.PinState;

public class MyServlet extends javax.servlet.http.HttpServlet {

  private GpioController gpio=GpioFactory.getInstance();
  private GpioPinDigitalOutput redLed=gpio.provisionDigitalOutputPin(RaspiPin.GPIO_23,PinState.LOW);
  private GpioPinDigitalOutput greenLed=gpio.provisionDigitalOutputPin(RaspiPin.GPIO_22,PinState.LOW);
  private GpioPinDigitalOutput blueLed=gpio.provisionDigitalOutputPin(RaspiPin.GPIO_21,PinState.LOW);
  private GpioPinDigitalOutput[] pins=new GpioPinDigitalOutput[]{redLed,greenLed,blueLed};

  @Override
  public void doGet(javax.servlet.http.HttpServletRequest request,javax.servlet.http.HttpServletResponse response) throws java.io.IOException {
    java.io.PrintWriter print=response.getWriter();
    print.write("<body>"+
                   "<p> Choose a color! </p>"+
                   "<form action=\"first\" method=\"POST\">"+
                   "<input type=\"submit\" name=\"button\" value=\"red\"/>"+
                   "</form>"+
                   "<form action=\"first\" method=\"POST\">"+
                   "<input type=\"submit\" name=\"button\" value=\"green\"/>"+
                   "</form>"+
                   "<form action=\"first\" method=\"POST\">"+
                   "<input type=\"submit\" name=\"button\" value=\"blue\"/>"+
                   "</form>"+
                 "</body>");
  }

  public void doPost(javax.servlet.http.HttpServletRequest request,javax.servlet.http.HttpServletResponse response) throws java.io.IOException {
    java.io.PrintWriter pw=response.getWriter();
    String act=request.getParameter("button");
    switch(act) {
      case "red":
        togglePin();
        redLed.high();
        pw.write("<p>the led is red!</p>");
        break;
      case "green":
        togglePin();
        greenLed.high();
        pw.write("<p>the led is green</p>");
        break;
      case "blue":
        togglePin();
        blueLed.high();
        pw.write("<p>the led is blue!</p>");
        break;
    }
  }

  private void togglePin() {
    for (GpioPinDigitalOutput pin : pins)
      if (pin.isHigh()) pin.toggle();
  }
</code>```

it compiles fine and I manually deploy it inside tomcat,with the deployment descriptor and all.
But when I connect it says to me that the resource is unavailable.
If I remove the GPIO related code it works fine.

Can someone please help me out? Google searching doesn't seem to help

答: You must put in your project the pi4j libraries in path WEB-INF/lib</p>

Title: Java Servlets and Raspberry Pi IO

Body:
I'm trying to learn how to write simple servlets to use with a Raspberry Pi.
I want to control the board I/O via web.I'm using the Pi4J library which is a wrapper for the WiringPi C library.It works when I use it to blink a led locally so I assume that I'm doing something wrong coding my servlet.

This is the code I wrote:

package com.luca.servlet;

import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.io.gpio.PinState;

public class MyServlet extends javax.servlet.http.HttpServlet {

  private GpioController gpio=GpioFactory.getInstance();
  private GpioPinDigitalOutput redLed=gpio.provisionDigitalOutputPin(RaspiPin.GPIO_23,PinState.LOW);
  private GpioPinDigitalOutput greenLed=gpio.provisionDigitalOutputPin(RaspiPin.GPIO_22,PinState.LOW);
  private GpioPinDigitalOutput blueLed=gpio.provisionDigitalOutputPin(RaspiPin.GPIO_21,PinState.LOW);
  private GpioPinDigitalOutput[] pins=new GpioPinDigitalOutput[]{redLed,greenLed,blueLed};

  @Override
  public void doGet(javax.servlet.http.HttpServletRequest request,javax.servlet.http.HttpServletResponse response) throws java.io.IOException {
    java.io.PrintWriter print=response.getWriter();
    print.write(""+
                   "
 Choose a color!
"+
                   "<form action=\"first\" method=\"POST\">"+
                   "<input type=\"submit\" name=\"button\" value=\"red\"/>"+
                   "</form>"+
                   "<form action=\"first\" method=\"POST\">"+
                   "<input type=\"submit\" name=\"button\" value=\"green\"/>"+
                   "</form>"+
                   "<form action=\"first\" method=\"POST\">"+
                   "<input type=\"submit\" name=\"button\" value=\"blue\"/>"+
                   "</form>"+
                 "");
  }

  public void doPost(javax.servlet.http.HttpServletRequest request,javax.servlet.http.HttpServletResponse response) throws java.io.IOException {
    java.io.PrintWriter pw=response.getWriter();
    String act=request.getParameter("button");
    switch(act) {
      case "red":
        togglePin();
        redLed.high();
        pw.write("
the led is red!
");
        break;
      case "green":
        togglePin();
        greenLed.high();
        pw.write("
the led is green
");
        break;
      case "blue":
        togglePin();
        blueLed.high();
        pw.write("
the led is blue!
");
        break;
    }
  }

  private void togglePin() {
    for (GpioPinDigitalOutput pin : pins)
      if (pin.isHigh()) pin.toggle();
  }

it compiles fine and I manually deploy it inside tomcat,with the deployment descriptor and all.
But when I connect it says to me that the resource is unavailable.
If I remove the GPIO related code it works fine.

Can someone please help me out? Google searching doesn't seem to help


问:
How to show edit and delete buttons on datatables when right clicking a row?
I am using datatables. Is it possible to show working edit and delete buttons on right click like the example here?
The only working example I found is this. But it is not what I am trying to achieve.

Example for click events: https://datatables.net/examples/advanced_init/events_live.html

答:
You could init the contextmenu in the drawCallback handler, and retrieve the id from the clicked row in $.contextMenu's own callback :

```<code>drawCallback : function() {
  $.contextMenu({
        selector: 'tbody tr td',
        callback: function(key, options) {
            var id = options.$trigger[0].parentElement.id;
            var m = "clicked: " + key + ' ' + id;
            window.console && console.log(m) || alert(m);
            /*
             switch (key) {
               case 'delete' :
                 yourDeleteMethod(id); break;
               case 'edit' :
                 yourEditMethod(id); break;
               ...
              }
            */
        },
        items: {
            "edit": {name: "Edit", icon: "edit"},
            "cut": {name: "Cut", icon: "cut"},
           copy: {name: "Copy", icon: "copy"},
            "paste": {name: "Paste", icon: "paste"},
            "delete": {name: "Delete", icon: "delete"},
            "sep1": "---------",
            "quit": {name: "Quit", icon: function(){
                return 'context-menu-icon context-menu-icon-quit';
            }}
        }
    });
},
</code>```

updated fiddle -> http://jsfiddle.net/0f9Ljfjr/900/

Since the selector is set to tbody tr td the id will always could be found by options.$trigger[0].parentElement.id. Now you just need to respond to what ever actions you need, and call your own methods with the retrieved id.

Body:
You could init the contextmenu in the drawCallback handler, and retrieve the id from the clicked row in $.contextMenu's own callback :

drawCallback : function() {
  $.contextMenu({
        selector: 'tbody tr td',
        callback: function(key, options) {
            var id = options.$trigger[0].parentElement.id;
            var m = "clicked: " + key + ' ' + id;
            window.console && console.log(m) || alert(m);
            /*
             switch (key) {
               case 'delete' :
                 yourDeleteMethod(id); break;
               case 'edit' :
                 yourEditMethod(id); break;
               ...
              }
            */
        },
        items: {
            "edit": {name: "Edit", icon: "edit"},
            "cut": {name: "Cut", icon: "cut"},
           copy: {name: "Copy", icon: "copy"},
            "paste": {name: "Paste", icon: "paste"},
            "delete": {name: "Delete", icon: "delete"},
            "sep1": "---------",
            "quit": {name: "Quit", icon: function(){
                return 'context-menu-icon context-menu-icon-quit';
            }}
        }
    });
},

updated fiddle -> http://jsfiddle.net/0f9Ljfjr/900/

Since the selector is set to tbody tr td the id will always could be found by options.$trigger[0].parentElement.id. Now you just need to respond to what ever actions you need, and call your own methods with the retrieved id.


问:
Can I override the alert/prompt dialog boxes behavior in a WebBrowser?
Is there something similar to Qt QWebView's QWebPage where I can override the method that gets called every time a prompt/alert is about to be displayed? I've been told about to implement IDocHostShowUI but even after done some search, I have no idea how do this with WebBrowser.

答:
Paulo Morgado provided an answer on the MSDN forums.

Code and comments from that post are provided below for future readers.

It's the WebBrowserSite, not the WebBrowser that needs to implement
  IDocHostShowUI

```<code> using System;
 using System.Runtime.InteropServices;

 namespace WebBrowserMessageBox
 {
    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
       public int x;
       public int y;
    }

    [ComImport, Guid("C4D244B0-D43E-11CF-893B-00AA00BDCE1A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
      public interface IDocHostShowUI
      {
        [return: MarshalAs(UnmanagedType.U4)]
        [PreserveSig]
        int ShowMessage(IntPtr hwnd,
          [MarshalAs(UnmanagedType.LPWStr)] string lpstrText,
          [MarshalAs(UnmanagedType.LPWStr)] string lpstrCaption,
          int dwType,
          [MarshalAs(UnmanagedType.LPWStr)] string lpstrHelpFile,
          int dwHelpContext,
          out int lpResult);
    [return: MarshalAs(UnmanagedType.U4)]
    [PreserveSig]
    int ShowHelp(
      IntPtr hwnd,
      [MarshalAs(UnmanagedType.LPWStr)] string pszHelpFile,
      int uCommand,
      int dwData,
      POINT ptMouse,
      [MarshalAs(UnmanagedType.IDispatch)] object pDispatchObjectHit);
  }

  public class ShowMessageEventArgs : EventArgs
 {
    public ShowMessageEventArgs(string text, string caption, int type, string helpFile, int helpContext)
    {
    }

    public bool Handled { get; set; }
    public int Result { get; set; }
    public int Type { get; private set; }
    public int HelpContext { get; private set; }
    public string Text { get; private set; }
    public string Caption { get; private set; }
    public string HelpFile { get; private set; }
  }

  public class MyWebBrowser : global::System.Windows.Forms.WebBrowser
  {
    protected class MyWebBrowserSite : global::System.Windows.Forms.WebBrowser.WebBrowserSite, IDocHostShowUI
    {
      private readonly MyWebBrowser host;

      public MyWebBrowserSite(MyWebBrowser host)
        : base(host)
      {
        this.host = host;
      }

      public int ShowMessage(IntPtr hwnd, string lpstrText, string lpstrCaption, int dwType, string lpstrHelpFile, int dwHelpContext, out int lpResult)
      {
        var e = new ShowMessageEventArgs(lpstrText, lpstrCaption, dwType, lpstrHelpFile, dwHelpContext);
        this.host.OnShowMessage(e);

        if (e.Handled)
        {
          lpResult = e.Result;
          return 0;
        }
        else
        {
          lpResult = 0;
          return 1;
        }
      }

      public int ShowHelp(IntPtr hwnd, string pszHelpFile, int uCommand, int dwData, POINT ptMouse, object pDispatchObjectHit)
      {
        return 1;
      }
    }

    protected override System.Windows.Forms.WebBrowserSiteBase CreateWebBrowserSiteBase()
    {
      return new MyWebBrowserSite(this);
    }

    protected virtual void OnShowMessage(ShowMessageEventArgs e)
    {
      var handler = this.Events["ShowMessage"] as EventHandler<ShowMessageEventArgs>;

      if (handler != null)
      {
        handler(this, e);
      }
    }

    public event EventHandler<ShowMessageEventArgs> ShowMessage
    {
      add { this.Events.AddHandler("ShowMessage", value); }
      remove { this.Events.RemoveHandler("ShowMessage", value); }
    }
  }

  public static class Program
  {
    [STAThread]
    private static void Main(params string[] args)
    {
      var webBrowser = new MyWebBrowser
      {
        Dock = System.Windows.Forms.DockStyle.Fill,
        DocumentText = @"<html><head><body><script language='JScript'>alert(""test"")</script></body></head></html>"
      };
      webBrowser.ShowMessage += (sender, e) =>
      {
        e.Result = 0;
        e.Handled = true;
      };

      var form = new global::System.Windows.Forms.Form
      {
        Controls = { webBrowser }
      };

      global::System.Windows.Forms.Application.Run(form);
    }
  }
}
</code>```

Please note I am not the author of this code.

Body:
Paulo Morgado provided an answer on the MSDN forums.

Code and comments from that post are provided below for future readers.

It's the WebBrowserSite, not the WebBrowser that needs to implement
  IDocHostShowUI

 using System;
 using System.Runtime.InteropServices;

 namespace WebBrowserMessageBox
 {
    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
       public int x;
       public int y;
    }

    [ComImport, Guid("C4D244B0-D43E-11CF-893B-00AA00BDCE1A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
      public interface IDocHostShowUI
      {
        [return: MarshalAs(UnmanagedType.U4)]
        [PreserveSig]
        int ShowMessage(IntPtr hwnd,
          [MarshalAs(UnmanagedType.LPWStr)] string lpstrText,
          [MarshalAs(UnmanagedType.LPWStr)] string lpstrCaption,
          int dwType,
          [MarshalAs(UnmanagedType.LPWStr)] string lpstrHelpFile,
          int dwHelpContext,
          out int lpResult);
    [return: MarshalAs(UnmanagedType.U4)]
    [PreserveSig]
    int ShowHelp(
      IntPtr hwnd,
      [MarshalAs(UnmanagedType.LPWStr)] string pszHelpFile,
      int uCommand,
      int dwData,
      POINT ptMouse,
      [MarshalAs(UnmanagedType.IDispatch)] object pDispatchObjectHit);
  }

  public class ShowMessageEventArgs : EventArgs
 {
    public ShowMessageEventArgs(string text, string caption, int type, string helpFile, int helpContext)
    {
    }

    public bool Handled { get; set; }
    public int Result { get; set; }
    public int Type { get; private set; }
    public int HelpContext { get; private set; }
    public string Text { get; private set; }
    public string Caption { get; private set; }
    public string HelpFile { get; private set; }
  }

  public class MyWebBrowser : global::System.Windows.Forms.WebBrowser
  {
    protected class MyWebBrowserSite : global::System.Windows.Forms.WebBrowser.WebBrowserSite, IDocHostShowUI
    {
      private readonly MyWebBrowser host;

      public MyWebBrowserSite(MyWebBrowser host)
        : base(host)
      {
        this.host = host;
      }

      public int ShowMessage(IntPtr hwnd, string lpstrText, string lpstrCaption, int dwType, string lpstrHelpFile, int dwHelpContext, out int lpResult)
      {
        var e = new ShowMessageEventArgs(lpstrText, lpstrCaption, dwType, lpstrHelpFile, dwHelpContext);
        this.host.OnShowMessage(e);

        if (e.Handled)
        {
          lpResult = e.Result;
          return 0;
        }
        else
        {
          lpResult = 0;
          return 1;
        }
      }

      public int ShowHelp(IntPtr hwnd, string pszHelpFile, int uCommand, int dwData, POINT ptMouse, object pDispatchObjectHit)
      {
        return 1;
      }
    }

    protected override System.Windows.Forms.WebBrowserSiteBase CreateWebBrowserSiteBase()
    {
      return new MyWebBrowserSite(this);
    }

    protected virtual void OnShowMessage(ShowMessageEventArgs e)
    {
      var handler = this.Events["ShowMessage"] as EventHandler<ShowMessageEventArgs>;

      if (handler != null)
      {
        handler(this, e);
      }
    }

    public event EventHandler<ShowMessageEventArgs> ShowMessage
    {
      add { this.Events.AddHandler("ShowMessage", value); }
      remove { this.Events.RemoveHandler("ShowMessage", value); }
    }
  }

  public static class Program
  {
    [STAThread]
    private static void Main(params string[] args)
    {
      var webBrowser = new MyWebBrowser
      {
        Dock = System.Windows.Forms.DockStyle.Fill,
        DocumentText = @"<html><head><body><script language='JScript'>alert(""test"")</script></body></head></html>"
      };
      webBrowser.ShowMessage += (sender, e) =>
      {
        e.Result = 0;
        e.Handled = true;
      };

      var form = new global::System.Windows.Forms.Form
      {
        Controls = { webBrowser }
      };

      global::System.Windows.Forms.Application.Run(form);
    }
  }
}

Please note I am not the author of this code.


问:
How to succinctly write a formula with many variables from a data frame?
Suppose I have a response variable and a data containing three covariates (as a toy example):

```<code>y = c(1,4,6)
d = data.frame(x1 = c(4,-1,3), x2 = c(3,9,8), x3 = c(4,-4,-2))
</code>```

I want to fit a linear regression to the data:

```<code>fit = lm(y ~ d$x1 + d$x2 + d$y2)
</code>```

Is there a way to write the formula, so that I don't have to write out each individual covariate? For example, something like

```<code>fit = lm(y ~ d)
</code>```

(I want each variable in the data frame to be a covariate.) I'm asking because I actually have 50 variables in my data frame, so I want to avoid writing out x1 + x2 + x3 + etc.

答:
An extension of juba's method is to use reformulate, a function which is explicitly designed for such a task.

```<code>## Create a formula for a model with a large number of variables:
xnam <- paste("x", 1:25, sep="")

reformulate(xnam, "y")
y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 +
    x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 +
    x22 + x23 + x24 + x25
</code>```

For the example in the OP, the easiest solution here would be

```<code># add y variable to data.frame d
d <- cbind(y, d)
reformulate(names(d)[-1], names(d[1]))
y ~ x1 + x2 + x3
</code>```

or

```<code>mod <- lm(reformulate(names(d)[-1], names(d[1])), data=d)
</code>```

Note that adding the dependent variable to the data.frame in d <- cbind(y, d) is preferred not only because it allows for the use of reformulate, but also because it allows for future use of the lm object in functions like predict.

Body:
Suppose I have a response variable and a data containing three covariates (as a toy example):

y = c(1,4,6)
d = data.frame(x1 = c(4,-1,3), x2 = c(3,9,8), x3 = c(4,-4,-2))

I want to fit a linear regression to the data:

fit = lm(y ~ d$x1 + d$x2 + d$y2)

Is there a way to write the formula, so that I don't have to write out each individual covariate? For example, something like

fit = lm(y ~ d)

(I want each variable in the data frame to be a covariate.) I'm asking because I actually have 50 variables in my data frame, so I want to avoid writing out x1 + x2 + x3 + etc.

Body:
An extension of juba's method is to use reformulate, a function which is explicitly designed for such a task.

## Create a formula for a model with a large number of variables:
xnam <- paste("x", 1:25, sep="")

reformulate(xnam, "y")
y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 +
    x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 +
    x22 + x23 + x24 + x25

For the example in the OP, the easiest solution here would be

# add y variable to data.frame d
d <- cbind(y, d)
reformulate(names(d)[-1], names(d[1]))
y ~ x1 + x2 + x3

or

mod <- lm(reformulate(names(d)[-1], names(d[1])), data=d)

Note that adding the dependent variable to the data.frame in d <- cbind(y, d) is preferred not only because it allows for the use of reformulate, but also because it allows for future use of the lm object in functions like predict.


问:
how to uninstall perlbrew from macbook
I have few modules associated with it. However when I try to switch from system perl to perlbrew it displays

-sh: perlbrew: command not found

however in the directory I have,

bin        lib        man         perlbrew

It has been almost over a year since I used perl and perlbrew and I am not able to figure it out how I did it the last time. Any help is appreciated.

答:
From the login script, delete the line

```<code>source ~/perl5/perlbrew/etc/bashrc
</code>```

Delete the perlbrew directory

```<code>rm -rf ~/perl5/perlbrew
</code>```

That assumes you installed perlbrew in its default location. If not, env var $PERLBREW_ROOT should indicate to where it's installed.

If instead you'd rather fix the problem,

Move ~/perl5/perlbrew/perls to somewhere safe.

Delete ~/perl5/perlbrew.

Reinstall perlbrew.

Restore the perls directory.

Title: how to uninstall perlbrew from macbook

Body:
From the login script, delete the line

source ~/perl5/perlbrew/etc/bashrc

Delete the perlbrew directory

rm -rf ~/perl5/perlbrew

That assumes you installed perlbrew in its default location. If not, env var $PERLBREW_ROOT should indicate to where it's installed.

If instead you'd rather fix the problem,

Move ~/perl5/perlbrew/perls to somewhere safe.

Delete ~/perl5/perlbrew.

Reinstall perlbrew.

Restore the perls directory.


问:
Understanding Twitter API's "Cursor" parameter
I don't really get how to use the Curesor parameter in Twitter's API, for an exmaple - here.
Am I supposed to make a new API call for each 100 followers?

I'd love it if someone could provide a PHP example for getting a full list of followers assuming I have more than 100...

Thanks in advance!

答:
Despite you asked it some time ago, I hope this will be the more accurated answer.

Twitter does not offer info about what next_cursor means. Only how cursor works.

It is only an easy way for Twitter to manage pagination.

«The function is intended to be used linearly, one cursor set at a time per user.» Source

«It's potentially less efficient for you but much more efficient
  for us.» Twitter Staff

BUT...
Someone ask before in a broken link «are cursors persistents? seem that the answer is "yes"»

This means you can save your last cursor before 0 and continue with it next time.


问:
ttk.Progressbar being duplicated
I'm having a peculiar problem when displaying a widget containing a tkinter.StringVar variable.

This happens whether or not I use frames to locate the variable.

In brief, I have three non-variable labels, one variable label, a progressbar and two buttons all gridded vertically (the button are side by side though (irrelevant but supplied for completeness).

When the variable is changed programmatically, concatenating a new character ('\n) and more text, the variable shows the extra lines, but duplicate progressbars and buttons are displayed:

(Separate images here).

Interesting note: This does not happen if the '\n' is not added.

```<code>import os
import sys
import time
import tkinter as tk
import tkinter.ttk as ttk

class rtGetPaths(tk.Frame):
    """
    """
    def __init__(self, root):
        tk.Frame.__init__(self, root)

        self.root = root

        # Get the system separator
        self.path_sep = os.pathsep
        # Find the root on the drive
        self.root_id = os.path.abspath(os.sep)
        self.data = [(os.path.join('C:', 'Program Files', 'App_1.exe')),
                     (os.path.join('C:', 'Program Files', 'App_2.exe')),
                     (os.path.join('C:', 'Program Files', 'App_3.exe')),
                     (os.path.join('C:', 'Program Files', 'App_4.exe'))
                    ]

        self.locns = []

        self.root.title('Get Paths')

        self.gpw_l1 = tk.Label(self.root, text='Searching for apps')
        self.gpw_l2 = tk.Label(self.root, text='This may take some time')
        self.gpw_l3 = tk.Label(self.root, text='Please be patient')

        self.gpw_found_l_svar = tk.StringVar()
        self.gpw_found_l_svar.set('')
        self.gpw_found_l = tk.Label(self.root, textvariable=self.gpw_found_l_svar)

        self.gpw_pb_ivar = tk.IntVar()
        self.gpw_pb_ivar.set(0)
        self.gpw_pb_length = 350
        self.gpw_pb_max = 5
        self.gpw_pb = ttk.Progressbar(self.root,
                                      mode='determinate',
                                      maximum=self.gpw_pb_max,
                                      length=self.gpw_pb_length,
                                      variable=self.gpw_pb_ivar)

        self.gpw_exit_b = tk.Button(self.root,
                                    text='Exit',
                                    command=sys.exit)
        self.gpw_continue_b = tk.Button(self.root,
                                        text='Continue',
                                        command=self.gpw_action_continue_b)

        row = 0
        self.gpw_l1.grid(row=row, columnspan=2)
        row += 1
        self.gpw_l2.grid(row=row, columnspan=2)
        row += 1
        self.gpw_l3.grid(row=row, columnspan=2)
        row += 1
        self.gpw_found_l.grid(row=row, columnspan=2)
        row += 1
        self.gpw_pb.grid(row=row, columnspan=2)
        row += 1
        self.gpw_exit_b.grid(row=row, column=0, sticky='ew')
        self.gpw_continue_b.grid(row=row, column=1, sticky='ew')

        self.gpw_found_l.grid_remove()

        self.root.geometry('+100+200')

    def gpw_action_continue_b(self):
        """

        :return:
        """
        for file in self.data:
            lookfor = ''
            if 'App_1.exe' in file:
                lookfor = file
            elif 'App_2.exe' in file:
                lookfor = file
            elif 'App_3.exe' in file:
                lookfor = file
            elif 'App_4.exe' in file:
                lookfor = file

            if lookfor != '':
                self.locns.append(lookfor)

                label = self.gpw_found_l_svar.get()
                if 0 < self.gpw_pb_ivar.get() < 5:
                    label = label + '\n'
                label = label + os.path.join(lookfor)
                self.gpw_found_l_svar.set(label)

                self.gpw_pb_ivar.set(self.gpw_pb_ivar.get() + 1)
                if not self.gpw_found_l.winfo_viewable():
                    self.gpw_found_l.grid()

                self.root.update_idletasks()
                time.sleep(1)

        self.gpw_continue_b['state'] = 'disabled'
        self.gpw_pb_ivar.set(self.gpw_pb_max)
        self.root.update_idletasks()

        return

#==============================================================================
#   MAIN (MAIN)
#==============================================================================
def main():
    """ Run the app
    """
    # # Create the screen instance and name it
    root = tk.Tk()
    app = rtGetPaths(root)
    root.mainloop()
    root.quit()

#==============================================================================
#   MAIN (STARTUP)
#==============================================================================
if __name__ == '__main__':
    # Run the function name main()
    main()
</code>```

Why is it doing this, and how do I stop it?

答:
I'm not sure why this problem is occurring, but you can fix it by updating the progress bar each time you change the lable

The code:

```<code>def gpw_action_continue_b(self):

    for file in self.data:
        ...
        self.gpw_pb.update() # this fixes the problem
        self.root.update_idletasks()
        time.sleep(1)
</code>```

Proof it works:

Title: ttk.Progressbar being duplicated

Body:
I'm having a peculiar problem when displaying a widget containing a tkinter.StringVar variable.

This happens whether or not I use frames to locate the variable.

In brief, I have three non-variable labels, one variable label, a progressbar and two buttons all gridded vertically (the button are side by side though (irrelevant but supplied for completeness).

When the variable is changed programmatically, concatenating a new character ('\n) and more text, the variable shows the extra lines, but duplicate progressbars and buttons are displayed:

(Separate images here).

Interesting note: This does not happen if the '\n' is not added.

import os
import sys
import time
import tkinter as tk
import tkinter.ttk as ttk

class rtGetPaths(tk.Frame):
    """
    """
    def __init__(self, root):
        tk.Frame.__init__(self, root)

        self.root = root

        # Get the system separator
        self.path_sep = os.pathsep
        # Find the root on the drive
        self.root_id = os.path.abspath(os.sep)
        self.data = [(os.path.join('C:', 'Program Files', 'App_1.exe')),
                     (os.path.join('C:', 'Program Files', 'App_2.exe')),
                     (os.path.join('C:', 'Program Files', 'App_3.exe')),
                     (os.path.join('C:', 'Program Files', 'App_4.exe'))
                    ]

        self.locns = []

        self.root.title('Get Paths')

        self.gpw_l1 = tk.Label(self.root, text='Searching for apps')
        self.gpw_l2 = tk.Label(self.root, text='This may take some time')
        self.gpw_l3 = tk.Label(self.root, text='Please be patient')

        self.gpw_found_l_svar = tk.StringVar()
        self.gpw_found_l_svar.set('')
        self.gpw_found_l = tk.Label(self.root, textvariable=self.gpw_found_l_svar)

        self.gpw_pb_ivar = tk.IntVar()
        self.gpw_pb_ivar.set(0)
        self.gpw_pb_length = 350
        self.gpw_pb_max = 5
        self.gpw_pb = ttk.Progressbar(self.root,
                                      mode='determinate',
                                      maximum=self.gpw_pb_max,
                                      length=self.gpw_pb_length,
                                      variable=self.gpw_pb_ivar)

        self.gpw_exit_b = tk.Button(self.root,
                                    text='Exit',
                                    command=sys.exit)
        self.gpw_continue_b = tk.Button(self.root,
                                        text='Continue',
                                        command=self.gpw_action_continue_b)

        row = 0
        self.gpw_l1.grid(row=row, columnspan=2)
        row += 1
        self.gpw_l2.grid(row=row, columnspan=2)
        row += 1
        self.gpw_l3.grid(row=row, columnspan=2)
        row += 1
        self.gpw_found_l.grid(row=row, columnspan=2)
        row += 1
        self.gpw_pb.grid(row=row, columnspan=2)
        row += 1
        self.gpw_exit_b.grid(row=row, column=0, sticky='ew')
        self.gpw_continue_b.grid(row=row, column=1, sticky='ew')

        self.gpw_found_l.grid_remove()

        self.root.geometry('+100+200')

    def gpw_action_continue_b(self):
        """

        :return:
        """
        for file in self.data:
            lookfor = ''
            if 'App_1.exe' in file:
                lookfor = file
            elif 'App_2.exe' in file:
                lookfor = file
            elif 'App_3.exe' in file:
                lookfor = file
            elif 'App_4.exe' in file:
                lookfor = file

            if lookfor != '':
                self.locns.append(lookfor)

                label = self.gpw_found_l_svar.get()
                if 0 < self.gpw_pb_ivar.get() < 5:
                    label = label + '\n'
                label = label + os.path.join(lookfor)
                self.gpw_found_l_svar.set(label)

                self.gpw_pb_ivar.set(self.gpw_pb_ivar.get() + 1)
                if not self.gpw_found_l.winfo_viewable():
                    self.gpw_found_l.grid()

                self.root.update_idletasks()
                time.sleep(1)

        self.gpw_continue_b['state'] = 'disabled'
        self.gpw_pb_ivar.set(self.gpw_pb_max)
        self.root.update_idletasks()

        return

#==============================================================================
#   MAIN (MAIN)
#==============================================================================
def main():
    """ Run the app
    """
    # # Create the screen instance and name it
    root = tk.Tk()
    app = rtGetPaths(root)
    root.mainloop()
    root.quit()

#==============================================================================
#   MAIN (STARTUP)
#==============================================================================
if __name__ == '__main__':
    # Run the function name main()
    main()

Why is it doing this, and how do I stop it?

Body:
I'm not sure why this problem is occurring, but you can fix it by updating the progress bar each time you change the lable

The code:

def gpw_action_continue_b(self):

    for file in self.data:
        ...
        self.gpw_pb.update() # this fixes the problem
        self.root.update_idletasks()
        time.sleep(1)

Proof it works:


问:
Pandas: Replace Function syntax
I have a huge DataFrame with a column which has a list of names. The names have numbers and brackets attached to them. I'm trying to strip them off from the names. I found that the method which would work for this is:

```<code>df.Name = df.Name.str.replace(r'[\(\)\d]+', '')
</code>```

Could someone please help me to understand the syntax inside the replace function?

```<code>(r'[\(\)\d]+', '')
</code>```

答:
Could someone please help me to understand the syntax inside the replace function?

What you see is a regular expression. Regular expressions have a special syntax to specify patterns.

In this regex the [...] means a character group. The character group here is filled with \( (the open bracket), \) (the closing bracket) and \d (digits).

The + at the end means "one or more" so we specify that the pattern consists out of sequence of the characters in the character group. So a string like '142(2' will match the regex.

You replace all substrings in the string that match with that pattern by the empty string, so you remove them.

A useful tool to build, test, and fix regexes, is regex101. If you follow the link you can specify a regex and see what strings that do match the described pattern. At the right side there is a panel that aims to explain in natural language what the pattern is doing.

Furthermore there is this regex visualizer that shows the structure of the regex:

A substring "matches" if you can follow the railroads until you reach your destination, so here we can keep cycling through the gray box as long as there is an open bracket, closing bracket or a digit until we decide to hit the finish.

Title: Pandas: Replace Function syntax

Body:
I have a huge DataFrame with a column which has a list of names. The names have numbers and brackets attached to them. I'm trying to strip them off from the names. I found that the method which would work for this is:

df.Name = df.Name.str.replace(r'[\(\)\d]+', '')

Could someone please help me to understand the syntax inside the replace function?

(r'[\(\)\d]+', '')


问:
Update parameter on controller
I am creating 2 modules, 1) price list, 2) discount list. These two modules share a table in the database called "relclili" in it will store the customer id called "CustomerCustomer", the id of the price list "ListP" and the id of the discount list " ". When the customer is added to a list of discounts or prices then the record is created the relclili, but if the customer is added to a price list and then added to a discount then one should not create a new record but modify The record that was created when the customer was added to the price list

I Tried to make it work but it shows me an error in the .js file
this is the error I get:

```<code>ActionView::Template::Error (undefined method `CodCliente' for true:TrueClass):
    1: $("#myclientadder_<%= @relclili.CodCliente %>").modal('hide');
    2:
    3: $("#container_relclilis").prepend('<%= j render @relclili %>'); //Prepend before append
    4: $("#relclili_<%= @relclili.id %>").hide().fadeIn(1000);
  app/views/relclilis/create.js.erb:1:in `_app_views_relclilis_create_js_erb___1051626349__1016832438'
</code>```

this is my create action:

```<code>def create
    if Relclili.exists?(CodCliente: relclili_params[:CodCliente])
      @relclili =  (Relclili.find_by(CodCliente: relclili_params[:CodCliente]).first.update(ListaP: relclili_params[:ListaP]))
      respond_to do |format|
        format.html { redirect_to @relclili, notice: 'Relclili was successfully created.' }
        format.json { render :show, status: :created, location: @relclili }
        format.js {flash.now[:notice] = 'El cliente se ha agregado de forma exitosa.'} #ajax
      end

    else
      @relclili = Relclili.new(relclili_params)
      respond_to do |format|
        if @relclili.save
          format.html { redirect_to @relclili, notice: 'Relclili was successfully created.' }
          format.json { render :show, status: :created, location: @relclili }
          format.js {flash.now[:notice] = 'El cliente se ha agregado de forma exitosa.'} #ajax

        else
          format.html { render :new }
          format.json { render json: @relclili.errors, status: :unprocessable_entity }
          format.js {flash.now[:alert] = 'Error al agregar el cliente.'} #ajax

        end
      end
    end
  end
</code>```

this is my create.js.erb

```<code>$("#myclientadder_<%= @relclili.CodCliente %>").modal('hide');

$("#container_relclilis").prepend('<%= j render @relclili %>'); //Prepend before append
$("#relclili_<%= @relclili.id %>").hide().fadeIn(1000);
$("#cliente_<%= @relclili.CodCliente %>").fadeOut(500, function(){
  $(this).remove();
  $(".child").remove();

});
$("#notice").html("<%= escape_javascript(render :partial => 'partials/flash' , :locals => { :flash => flash }).html_safe %>");

setTimeout(function(){
  $('#notice').fadeIn("slow", function() {
    $(this).create();
  })
}, 1500);
</code>```

答:
The issue lies here:

```<code>@relclili =  (Relclili.find_by(CodCliente: relclili_params[:CodCliente]).first.update(ListaP: relclili_params[:ListaP]))
</code>```

Split the above into 2 lines (one to get, and 1 to update):

```<code>@relclili =  (Relclili.find_by(CodCliente: relclili_params[:CodCliente]).first
@relclili.update(ListaP: relclili_params[:ListaP])) if @relclili.present?
</code>```

The reason why your code fails is because the update command does not return the object, but just a boolean saying whether update succeeded or failed. Hence it says undefined method CodCliente for true:TrueClass)

Title: Update parameter on controller

Body:
I am creating 2 modules, 1) price list, 2) discount list. These two modules share a table in the database called "relclili" in it will store the customer id called "CustomerCustomer", the id of the price list "ListP" and the id of the discount list " ". When the customer is added to a list of discounts or prices then the record is created the relclili, but if the customer is added to a price list and then added to a discount then one should not create a new record but modify The record that was created when the customer was added to the price list

I Tried to make it work but it shows me an error in the .js file
this is the error I get:

ActionView::Template::Error (undefined method `CodCliente' for true:TrueClass):
    1: $("#myclientadder_<%= @relclili.CodCliente %>").modal('hide');
    2:
    3: $("#container_relclilis").prepend('<%= j render @relclili %>'); //Prepend before append
    4: $("#relclili_<%= @relclili.id %>").hide().fadeIn(1000);
  app/views/relclilis/create.js.erb:1:in `_app_views_relclilis_create_js_erb___1051626349__1016832438'

this is my create action:

def create
    if Relclili.exists?(CodCliente: relclili_params[:CodCliente])
      @relclili =  (Relclili.find_by(CodCliente: relclili_params[:CodCliente]).first.update(ListaP: relclili_params[:ListaP]))
      respond_to do |format|
        format.html { redirect_to @relclili, notice: 'Relclili was successfully created.' }
        format.json { render :show, status: :created, location: @relclili }
        format.js {flash.now[:notice] = 'El cliente se ha agregado de forma exitosa.'} #ajax
      end

    else
      @relclili = Relclili.new(relclili_params)
      respond_to do |format|
        if @relclili.save
          format.html { redirect_to @relclili, notice: 'Relclili was successfully created.' }
          format.json { render :show, status: :created, location: @relclili }
          format.js {flash.now[:notice] = 'El cliente se ha agregado de forma exitosa.'} #ajax

        else
          format.html { render :new }
          format.json { render json: @relclili.errors, status: :unprocessable_entity }
          format.js {flash.now[:alert] = 'Error al agregar el cliente.'} #ajax

        end
      end
    end
  end

this is my create.js.erb

$("#myclientadder_<%= @relclili.CodCliente %>").modal('hide');

$("#container_relclilis").prepend('<%= j render @relclili %>'); //Prepend before append
$("#relclili_<%= @relclili.id %>").hide().fadeIn(1000);
$("#cliente_<%= @relclili.CodCliente %>").fadeOut(500, function(){
  $(this).remove();
  $(".child").remove();

});
$("#notice").html("<%= escape_javascript(render :partial => 'partials/flash' , :locals => { :flash => flash }).html_safe %>");

setTimeout(function(){
  $('#notice').fadeIn("slow", function() {
    $(this).create();
  })
}, 1500);

Body:
The issue lies here:

@relclili =  (Relclili.find_by(CodCliente: relclili_params[:CodCliente]).first.update(ListaP: relclili_params[:ListaP]))

Split the above into 2 lines (one to get, and 1 to update):

@relclili =  (Relclili.find_by(CodCliente: relclili_params[:CodCliente]).first
@relclili.update(ListaP: relclili_params[:ListaP])) if @relclili.present?

The reason why your code fails is because the update command does not return the object, but just a boolean saying whether update succeeded or failed. Hence it says undefined method CodCliente for true:TrueClass)