问:
Angularjs: Dynamically load directives in view with data
I am trying to make a dynamic framework with angularjs. I load sections with a webapi, that have data about the directive that it uses and the data that should be used in that directive. The data that I send can look like this:

```<code>[
    {
        id: "section1",
        directive: "<my-directive></my-directive>",
        content: {
            title: "This is a title",
            text: "This is a text"
        }
    },
    {
        id: "section2",
        directive: "<my-other></my-other>",
        content: {
            title: "This is another title",
            list: ["This is a text", "This is another text"]
        }
    }
]
</code>```

When I load this data, I convert the directives in to element with $compile.

```<code>angular.forEach($sections, (value, key):void => {
    value.directive = $compile(value.directive)($scope);
}
</code>```

So I can actually load this data in the view, like this:

```<code><div ng-repeat="section in sections">
    {{section.directive}}
</div>
</code>```

First of all, this doesn't show up in my view, so how do I fix this?
Then the second issue I have. When I actually get this directive loaded into the view, how will I be able to access the data that should be used in this directive? I do have an id added to the sections.This is what I tried:

```<code>angular.forEach($sections, (value, key):void => {
    value.directive = $compile(value.directive)($scope);
    var parent = angular.element('#sectionsparent'); //The parent element has this id
    parent.append(value.directive);
}
</code>```

This way the section elements show up, but I cannot access the data that should be loaded inside the directive.

Thank you for your help in advance, let me know if you need more information.

EDIT:

When the directive is eventually loaded, I want to be able to access the data that belongs to that section. So if we take first section in the sample data, I want to be able to do the following in the template of the directive:

```<code><!-- This file is myDirectiveTemplate.hmtl -->
<div id="{{id}}>
    <h1>{{title}}</h1>
    <p>{{text}}</p>
</div>
</code>```

I don't care if I have to access these properties through a viewmodel object, so it would be {{vm.id}} instead of {{id}}. But I prefer to not have any function calls inside my template to actually get data.

答:
Alright. There may be another way to accomplish this, or perhaps using includes instead of directives, but here's one way at least.

Taking your example code, you can follow your second route with $compile and append but you also need to pass an html-attribute for the isolate scope's content and bind it with a new $scope with the section added. (You also need to wrap in a $timeout so querying the DOM happens after it's initially rendered).

var app = angular.module('app', []);
app.controller('AppCtrl', function($scope, $compile, $timeout) {
  $scope.sections = [
      {
          id: "section1",
          directive: "my-directive",
          content: {
              title: "This is a title",
              text: "This is a text"
          }
      },
      {
          id: "section2",
          directive: "my-other",
          content: {
              title: "This is another title",
              list: ["This is a text", "This is another text"]
          }
      }
  ];

  // Need to timeout so rendering occurs and we can query the DOM.
  $timeout(() => {
    angular.forEach($scope.sections, (section) => {
      let newScope = $scope.$new();
      newScope.content = section.content;
      let dir = section.directive;
      let compiled = $compile(`<${dir} content="content"></${dir}>`)(newScope);
      let parent = angular.element(document.querySelector('#' + section.id));
      parent.append(compiled);
    });
  });
});

app.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {content: '='},
    template: `

{{content.title}}

{{content.text}}

`,
  };
});

app.directive('myOther', function() {
  return {
    restrict: 'E',
    scope: {content: '='},
    template: `

{{content.title}}

{{item}}

`,
  };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="AppCtrl">
  <div ng-repeat="section in sections" id="{{section.id}}"></div>
</div></code>```

Body:
I am trying to make a dynamic framework with angularjs. I load sections with a webapi, that have data about the directive that it uses and the data that should be used in that directive. The data that I send can look like this:

[
    {
        id: "section1",
        directive: "<my-directive></my-directive>",
        content: {
            title: "This is a title",
            text: "This is a text"
        }
    },
    {
        id: "section2",
        directive: "<my-other></my-other>",
        content: {
            title: "This is another title",
            list: ["This is a text", "This is another text"]
        }
    }
]

When I load this data, I convert the directives in to element with $compile.

angular.forEach($sections, (value, key):void => {
    value.directive = $compile(value.directive)($scope);
}

So I can actually load this data in the view, like this:

    {{section.directive}}

First of all, this doesn't show up in my view, so how do I fix this?
Then the second issue I have. When I actually get this directive loaded into the view, how will I be able to access the data that should be used in this directive? I do have an id added to the sections.This is what I tried:

angular.forEach($sections, (value, key):void => {
    value.directive = $compile(value.directive)($scope);
    var parent = angular.element('#sectionsparent'); //The parent element has this id
    parent.append(value.directive);
}

This way the section elements show up, but I cannot access the data that should be loaded inside the directive.

Thank you for your help in advance, let me know if you need more information.

EDIT:

When the directive is eventually loaded, I want to be able to access the data that belongs to that section. So if we take first section in the sample data, I want to be able to do the following in the template of the directive:

{{title}}

{{text}}

I don't care if I have to access these properties through a viewmodel object, so it would be {{vm.id}} instead of {{id}}. But I prefer to not have any function calls inside my template to actually get data.

Body:
Alright. There may be another way to accomplish this, or perhaps using includes instead of directives, but here's one way at least.

Taking your example code, you can follow your second route with $compile and append but you also need to pass an html-attribute for the isolate scope's content and bind it with a new $scope with the section added. (You also need to wrap in a $timeout so querying the DOM happens after it's initially rendered).

var app = angular.module('app', []);
app.controller('AppCtrl', function($scope, $compile, $timeout) {
  $scope.sections = [
      {
          id: "section1",
          directive: "my-directive",
          content: {
              title: "This is a title",
              text: "This is a text"
          }
      },
      {
          id: "section2",
          directive: "my-other",
          content: {
              title: "This is another title",
              list: ["This is a text", "This is another text"]
          }
      }
  ];

  // Need to timeout so rendering occurs and we can query the DOM.
  $timeout(() => {
    angular.forEach($scope.sections, (section) => {
      let newScope = $scope.$new();
      newScope.content = section.content;
      let dir = section.directive;
      let compiled = $compile(`<${dir} content="content"></${dir}>`)(newScope);
      let parent = angular.element(document.querySelector('#' + section.id));
      parent.append(compiled);
    });
  });
});

app.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {content: '='},
    template: `<div>
        <h1>{{content.title}}</h1>
        <p>{{content.text}}</p>
      </div>`,
  };
});

app.directive('myOther', function() {
  return {
    restrict: 'E',
    scope: {content: '='},
    template: `<div>
        <h1>{{content.title}}</h1>
        <ul>
          <li ng-repeat="item in content.list">{{item}}</li>
        </ul>
      </div>`,
  };
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="AppCtrl">
  <div ng-repeat="section in sections" id="{{section.id}}"></div>
</div>


来源: stackexchange

问:
Comma separated values join to master table
i want to display data when data from other table with two rows or more and to be one row with "for xml path", but alway null when use "for xml path". please look my sample table and my sql query now.

```<code>TCPAR :
IdCPAR | IdReferensi
1        '1','2'
2        '1','3','4'

TReferensi :
IdReferensi | Referensi
1              Alfa
2              Beta
3              Carlie
4              Delta

i want result like this:
IdCpar | IdReferensi | ReferensiName
1         '1','2'      'Alfa','Beta'
</code>```

and this is my sql query :

```<code>select
a.idCpar,
a.IdReferensi,
(
    SELECT LEFT(result, Len(result) - 1) FROM(SELECT '''' + Referensi + ''',' FROM TReferensi (NOLOCK)
    WHERE IdReferensi IN (a.IdReferensi)
    ORDER  BY Referensi FOR XML PATH ('')) x (result)
)as ReferensiName
from TCPAR as a
where a.IdCPAR=1

and the result:
idCpar | IdReferensi | ReferensiName
1          '1','2'     NULL
</code>```

Please help me... thanks...

答:
Try this</p>

```<code>select
a.idCpar,
a.IdReferensi,
STUFF(
   (SELECT CONCAT(',''', Referensi , '''') FROM TReferensi (NOLOCK)
   WHERE a.IdReferensi LIKE CONCAT('%''',IdReferensi,'''%')
   ORDER  BY Referensi FOR XML PATH ('') )
,1,1,'') as ReferensiName
from TCPAR as a
where a.IdCPAR=1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i want to display data when data from other table with two rows or more and to be one row with "for xml path", but alway null when use "for xml path". please look my sample table and my sql query now.

TCPAR :
IdCPAR | IdReferensi
1        '1','2'
2        '1','3','4'

TReferensi :
IdReferensi | Referensi
1              Alfa
2              Beta
3              Carlie
4              Delta

i want result like this:
IdCpar | IdReferensi | ReferensiName
1         '1','2'      'Alfa','Beta'

and this is my sql query :

select
a.idCpar,
a.IdReferensi,
(
    SELECT LEFT(result, Len(result) - 1) FROM(SELECT '''' + Referensi + ''',' FROM TReferensi (NOLOCK)
    WHERE IdReferensi IN (a.IdReferensi)
    ORDER  BY Referensi FOR XML PATH ('')) x (result)
)as ReferensiName
from TCPAR as a
where a.IdCPAR=1

and the result:
idCpar | IdReferensi | ReferensiName
1          '1','2'     NULL

Please help me... thanks...

Body:
Try this

select
a.idCpar,
a.IdReferensi,
STUFF(
   (SELECT CONCAT(',''', Referensi , '''') FROM TReferensi (NOLOCK)
   WHERE a.IdReferensi LIKE CONCAT('%''',IdReferensi,'''%')
   ORDER  BY Referensi FOR XML PATH ('') )
,1,1,'') as ReferensiName
from TCPAR as a
where a.IdCPAR=1


问:
How can an AWS Lambda function update all records in a DynamoDB table?
I'm working on an AWS Lambda function (Node 4.3) that needs to run through all the items in a DynamoDB table and update certain attributes.

The problem I'm having is how to get Lambda to wait until all of the DynamoDB operations are finished.

```<code>var async = require('async');
var aws = require('aws-sdk');
var doc = new aws.DynamoDB.DocumentClient();

exports.handler = (event, context, callback) => {
    doc.scan({
        TableName: 'Occupations_dev'
    }, function (err, data) {
        console.log(data.Items.length);

        var funcs = [];

        data.Items.forEach(function (item) {
            funcs.push(function (cb) {
                item.Popularity = 0;

                doc.put({
                    TableName: 'Occupations_dev',
                    Item: item
                }, function (err, data) {
                    if (err) {
                        console.log("ERROR: " + item.Name);
                        cb(err);
                    } else {
                        console.log('Finished put for ' + item.Id)
                        cb(null, item);
                    }
                });
            });
        });

        async.parallel(funcs, function (err, results) {
            console.log('Finished');

            if (err) {
                context.fail(err);
            } else {
                callback(null, 'Finished');
            }
        });
    });
};
</code>```

I tried using async.parallel to wait for all of the db.put requests to finish but it ends with a Process exited before completing request error whenever the Lambda function runs.

It does update some of the DynamoDB items but definitely not all of them.

I added some console.log calls when there are errors but the only output I see in the log is this:

```<code>START RequestId: b72fd7c6-14ed-11e7-a95a-c1185af4e870 Version: $LATEST
2017-03-30T02:08:11.691Z    b72fd7c6-14ed-11e7-a95a-c1185af4e870    1362
END RequestId: b72fd7c6-14ed-11e7-a95a-c1185af4e870
REPORT RequestId: b72fd7c6-14ed-11e7-a95a-c1185af4e870  Duration: 37165.80 ms   Billed Duration: 37200 ms   Memory Size: 128 MB Max Memory Used: 128 MB
RequestId: b72fd7c6-14ed-11e7-a95a-c1185af4e870 Process exited before completing request
</code>```

What's the proper way to make the Lambda function wait until everything is done? (It's not a huge amount of data so I'm not worried about running longer than 5 minutes and timing out.)

答:
The message "Process exited before completing request" means that the Javascript function exited before calling context.done (or context.succeed, etc.).

Here are some suggestions:

First of all, try increasing memory limit for the function. This line Memory Size: 128 MB Max Memory Used: 128 MB  may indicate that memory is not enough and the process just gets killed without calling last callback.

What you will probably see after increasing memory limit is one of the following:

Your function will timeout. In this case you may need to increase table's provisioned capacity (and/or your lambda timeout)

Even if the function ends without timeout, you will probably see that not all the table records are processed. This is because scan and query operations may return not all the table's rows, if the total number of scanned items exceeds the maximum data set size limit of 1 MB. When a scan completes, you should check if LastEvaluatedKey is returned along with the data. If it is, you should make another scan providing LastEvaluatedKey value as ExclusiveStartKey parameter

Body:
I'm working on an AWS Lambda function (Node 4.3) that needs to run through all the items in a DynamoDB table and update certain attributes.

The problem I'm having is how to get Lambda to wait until all of the DynamoDB operations are finished.

var async = require('async');
var aws = require('aws-sdk');
var doc = new aws.DynamoDB.DocumentClient();

exports.handler = (event, context, callback) => {
    doc.scan({
        TableName: 'Occupations_dev'
    }, function (err, data) {
        console.log(data.Items.length);

        var funcs = [];

        data.Items.forEach(function (item) {
            funcs.push(function (cb) {
                item.Popularity = 0;

                doc.put({
                    TableName: 'Occupations_dev',
                    Item: item
                }, function (err, data) {
                    if (err) {
                        console.log("ERROR: " + item.Name);
                        cb(err);
                    } else {
                        console.log('Finished put for ' + item.Id)
                        cb(null, item);
                    }
                });
            });
        });

        async.parallel(funcs, function (err, results) {
            console.log('Finished');

            if (err) {
                context.fail(err);
            } else {
                callback(null, 'Finished');
            }
        });
    });
};

I tried using async.parallel to wait for all of the db.put requests to finish but it ends with a Process exited before completing request error whenever the Lambda function runs.

It does update some of the DynamoDB items but definitely not all of them.

I added some console.log calls when there are errors but the only output I see in the log is this:

START RequestId: b72fd7c6-14ed-11e7-a95a-c1185af4e870 Version: $LATEST
2017-03-30T02:08:11.691Z    b72fd7c6-14ed-11e7-a95a-c1185af4e870    1362
END RequestId: b72fd7c6-14ed-11e7-a95a-c1185af4e870
REPORT RequestId: b72fd7c6-14ed-11e7-a95a-c1185af4e870  Duration: 37165.80 ms   Billed Duration: 37200 ms   Memory Size: 128 MB Max Memory Used: 128 MB
RequestId: b72fd7c6-14ed-11e7-a95a-c1185af4e870 Process exited before completing request

What's the proper way to make the Lambda function wait until everything is done? (It's not a huge amount of data so I'm not worried about running longer than 5 minutes and timing out.)


问:
Trying to automate facebook login and writing a post on friends timeline
Here is the code attached:

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs",prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("http://www.facebook.com/")
driver.find_element_by_name("email").send_keys("***EMAIL***")
driver.find_element_by_id("pass").send_keys("***PW***")
wait = WebDriverWait(driver, 15)
driver.find_element_by_xpath("//*[@id='loginbutton']").click()
wait = WebDriverWait(driver, 10)
ele = driver.find_element_by_name("q")
ele.send_keys("**FRIEND NAME**")
wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.XPATH,"//*[@id='js_e']/form/button/i")))
element.click()
wait = WebDriverWait(driver, 5)
element = wait.until(EC.element_to_be_clickable((By.XPATH,"//*[@id='js_9t']/img")))
element.click()
driver.find_element_by_xpath("//*[@id='js_3q9']/div[1]/div[1]/div[2]/div/div/div/div/div[2]/div/div/div/div").send_keys("Its Automated")
</code>```

The code is not working and gets stuck after logging in or after searching my friend's name and sometimes not even writing my friend's name. It's different every time not able to figure out what to do. The element locators also change all of sudden. Below are the errors I'm getting:

1) selenium.common.exceptions.InvalidElementStateException: Message: invalid element state

2) raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

3) Message: stale element reference: element is not attached to the page document

答: The error is telling you exactly what the problem is. The element you are trying to access via xpath is not being found on the document/page. Consequently, Selenium waits for a bit before timing out.</p>

Body:
Here is the code attached:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs",prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("http://www.facebook.com/")
driver.find_element_by_name("email").send_keys("***EMAIL***")
driver.find_element_by_id("pass").send_keys("***PW***")
wait = WebDriverWait(driver, 15)
driver.find_element_by_xpath("//*[@id='loginbutton']").click()
wait = WebDriverWait(driver, 10)
ele = driver.find_element_by_name("q")
ele.send_keys("**FRIEND NAME**")
wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.XPATH,"//*[@id='js_e']/form/button/i")))
element.click()
wait = WebDriverWait(driver, 5)
element = wait.until(EC.element_to_be_clickable((By.XPATH,"//*[@id='js_9t']/img")))
element.click()
driver.find_element_by_xpath("//*[@id='js_3q9']/div[1]/div[1]/div[2]/div/div/div/div/div[2]/div/div/div/div").send_keys("Its Automated")

The code is not working and gets stuck after logging in or after searching my friend's name and sometimes not even writing my friend's name. It's different every time not able to figure out what to do. The element locators also change all of sudden. Below are the errors I'm getting:

1) selenium.common.exceptions.InvalidElementStateException: Message: invalid element state

2) raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

3) Message: stale element reference: element is not attached to the page document


问:
How are variables shared between concurrent `session.run(...)` calls in tensorflow?
If you make two concurrent calls to the same session, sess.run(...), how are variables concurrently accessed in tensorflow?

Will each call see a snapshot of the variables as of the moment run was called, consistent throughout the call? Or will they see dynamic updates to the variables and only guarantee atomic updates to each variable?

I'm considering running test set evaluation on a separate CPU thread and want to verify that it's as trivial as running the inference op on a CPU device in parallel.

I'm having troubles figuring out exactly what guarantees are provided that make sessions "thread safe".

答:
After doing some experimentation it appears that each call to sess.run(...) does indeed see a consistent point-in-time snapshot of the variables.

To test this I performed 2 big matrix multiply operations (taking about 10 sec each to complete), and updated a single, dependent, variable before, between, and after. In another thread I grabbed and printed that variable every 1/10th second to see if it picked up the change that occurred between operations while the first thread was still running. It did not, I only saw it's initial and final values. Therefore I conclude that variable changes are only visible outside of a specific call to sess.run(...) at the end of that run.


问:
How to render LocalDateRenderer for Grid in Vaadin 8
I understand that Vaadin 8.1.0 will include a new LocalDateRenderer to work with Java 8's new date LocalDate but in the meantime I'm trying to setup my own custom LocalDateRenderer. I've got it mostly working in that it's all hooked up but based on the documentation I need to setup an AbstractRendererConnector but there's no such class...

The following code is all in my main UI class (for testing purposes):

```<code>private void setupGrid(Grid<Dog> grid)
{
    grid.addColumn(dog -> dog.getBirthday(), new LocalDateRenderer()).setCaption("Birthday");
}

class LocalDateRenderer extends AbstractRenderer<Object, LocalDate>
{
    public LocalDateRenderer()
    {
        super(LocalDate.class, "");
    }

    @Override
    public JsonValue encode(LocalDate localDate)
    {
        return encode(DateTimeFormatter.ofPattern("MMM dd, YYYY").format(localDate), String.class);
    }
}
</code>```

I have confirmed that the LocalDateRenderer is called by adding logging statements, however on the grid no values are displayed. If I use the same code but instead of LocalDate I do it for a Long but instead of extends AbstractRenderer I extend NumberRenderer with my own code then it works.

This lead me to the documentation where I need to setup the Renderer with a AbstractRendererConnector but whenever I try to do this I get the compiler error saying that AbstractRendererConnector cannot be resolved to a type. And then of course I have a number of compiler errors (in the code below). My code for this (still in the main UI class) is:

```<code>@Connect(LocalDateRenderer.class)
class LocalDateRendererConnector extends AbstractRendererConnector<LocalDate>
{
    @Override
    public LocalDateRenderer getRenderer()
    {
        return (LocalDateRenderer) super.getRenderer();
    }
}
</code>```

Any assistance with how to get it linked up so that it displays my actual dates would be greatly appreciated. Thank you.

Also in the documentation it's not clear which class is which when they refer to TextRenderer since they use the same name to to be different things...

答:
If your compiler can't resolve AbstractRendererConnector<T> to a type, you must be missing a dependency. If you are using Maven, you can add the following dependency, assuming that you have the vaadin-bom in your <dependencyManagement> section.

```<code>    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-client</artifactId>
    </dependency>
</code>```

This artifact is not included by default in most of the Vaadin archtetypes.

Also be careful: there are two Renderer interfaces, one in com.vaadin.client.renderers and one in com.vaadin.ui.renderers. Your covariant return in LocalDateRendererConnector.getRenderer() won't work because AbstractRendererConnector<T> implements a different Renderer interface.

Body:
I understand that Vaadin 8.1.0 will include a new LocalDateRenderer to work with Java 8's new date LocalDate but in the meantime I'm trying to setup my own custom LocalDateRenderer. I've got it mostly working in that it's all hooked up but based on the documentation I need to setup an AbstractRendererConnector but there's no such class...

The following code is all in my main UI class (for testing purposes):

private void setupGrid(Grid<Dog> grid)
{
    grid.addColumn(dog -> dog.getBirthday(), new LocalDateRenderer()).setCaption("Birthday");
}

class LocalDateRenderer extends AbstractRenderer<Object, LocalDate>
{
    public LocalDateRenderer()
    {
        super(LocalDate.class, "");
    }

    @Override
    public JsonValue encode(LocalDate localDate)
    {
        return encode(DateTimeFormatter.ofPattern("MMM dd, YYYY").format(localDate), String.class);
    }
}

I have confirmed that the LocalDateRenderer is called by adding logging statements, however on the grid no values are displayed. If I use the same code but instead of LocalDate I do it for a Long but instead of extends AbstractRenderer I extend NumberRenderer with my own code then it works.

This lead me to the documentation where I need to setup the Renderer with a AbstractRendererConnector but whenever I try to do this I get the compiler error saying that AbstractRendererConnector cannot be resolved to a type. And then of course I have a number of compiler errors (in the code below). My code for this (still in the main UI class) is:

@Connect(LocalDateRenderer.class)
class LocalDateRendererConnector extends AbstractRendererConnector<LocalDate>
{
    @Override
    public LocalDateRenderer getRenderer()
    {
        return (LocalDateRenderer) super.getRenderer();
    }
}

Any assistance with how to get it linked up so that it displays my actual dates would be greatly appreciated. Thank you.

Also in the documentation it's not clear which class is which when they refer to TextRenderer since they use the same name to to be different things...

Body:
If your compiler can't resolve AbstractRendererConnector<T> to a type, you must be missing a dependency. If you are using Maven, you can add the following dependency, assuming that you have the vaadin-bom in your <dependencyManagement> section.

    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-client</artifactId>
    </dependency>

This artifact is not included by default in most of the Vaadin archtetypes.

Also be careful: there are two Renderer interfaces, one in com.vaadin.client.renderers and one in com.vaadin.ui.renderers. Your covariant return in LocalDateRendererConnector.getRenderer() won't work because AbstractRendererConnector<T> implements a different Renderer interface.


问:
How to access MenuFlyout through Hub or make it not disappear
I want to make my MenuFlyout to don't disappear after I click at the ToggleMenuFlyoutItem. So if you could answer how can I do it simply that would be great. I come up with an idea to make function that will be called when any of ToggleMenuFlyoutItem has been clicked where I don;t hide MenuFlyout.
Here's XAML code snippet of my Hub:

```<code><Hub x:Uid="SettingsPageTitle" x:Name="settingsPage" Header="Settings">
        <HubSection x:Uid="SettingsPageGeneral" x:Name="settingsGeneral" Header="General">
            <DataTemplate x:Uid="anotherSettingGeneralPage">
                <Grid>
                    <StackPanel Width="500" Height="500" x:Name="settingsGeneralPage" Background="WhiteSmoke">
                        <StackPanel x:Name="enabledDaysPage" Height="Auto">
                            <Button x:Name="enabledDays" Content="Enabled Days" FontWeight="Bold" Background="Transparent" Width="500" HorizontalContentAlignment="Left" Click="enabledDays_Click">
                                <FlyoutBase.AttachedFlyout>
                                    <MenuFlyout x:Name="enabledDaysMenuFlyout">
                                        <ToggleMenuFlyoutItem x:Name="mon" Text="Monday" Tag="enabledDay" Click="enabledDays_Click"/>
                                        <ToggleMenuFlyoutItem Text="Tuesday" x:Name="tue" Tag="enabledDay" Click="enabledDays_Click"/>
                                        <ToggleMenuFlyoutItem Text="Wednesday" x:Name="wed" Tag="enabledDay" Click="enabledDays_Click"/>
                                        <ToggleMenuFlyoutItem Text="Thursday" x:Name="thu" Tag="enabledDay" Click="enabledDays_Click"/>
                                        <ToggleMenuFlyoutItem Text="Friday" x:Name="fri" Tag="enabledDay" Click="enabledDays_Click"/>
                                        <ToggleMenuFlyoutItem Text="Saturday" x:Name="sat" Tag="enabledDay" Click="enabledDays_Click"/>
                                        <ToggleMenuFlyoutItem Text="Sunday" x:Name="sun" Tag="enabledDay" Click="enabledDays_Click"/>
                                    </MenuFlyout>
                                </FlyoutBase.AttachedFlyout>
                            </Button>
                            <TextBlock x:Name="enabledDaysText"/>
                        </StackPanel>
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </HubSection>
</code>```

So can you help to make this to happen? Or at least how can I access my MenuFlyout, note that i tried this but it didn't helped me. Thanks!

答:
If you want to click the ToggleMenuFlyoutItem and do not want the MenuFlyout to be hided. You should be able to add the Closing event of the MenuFlyout.

In the Closing event, we can use the FlyoutBaseClosingEventArgs.Cancel property. If we set the true to it, it will prevent the flyout from closing.

For example:

```<code>private void enabledDaysMenuFlyout_Closing(FlyoutBase sender, FlyoutBaseClosingEventArgs args)
{
    args.Cancel = true;
}
</code>```

Update:

```<code><Hub x:Uid="SettingsPageTitle" x:Name="settingsPage" Header="Settings">
    <HubSection x:Uid="SettingsPageGeneral" x:Name="settingsGeneral" Header="General">
        <DataTemplate x:Uid="anotherSettingGeneralPage">
            <Grid>
                <StackPanel Width="500" Height="500" x:Name="settingsGeneralPage" Background="WhiteSmoke">
                    <StackPanel x:Name="enabledDaysPage" Height="Auto">
                        <Button x:Name="enabledDays" Content="Enabled Days" FontWeight="Bold" Background="Transparent" Width="500" HorizontalContentAlignment="Left" Click="enabledDays_Click">
                            <FlyoutBase.AttachedFlyout>
                                <MenuFlyout x:Name="enabledDaysMenuFlyout" Closing="enabledDaysMenuFlyout_Closing">
                                    <ToggleMenuFlyoutItem x:Name="mon" Text="Monday" Tag="enabledDay" Click="enabledDays_Click" />
                                    <ToggleMenuFlyoutItem Text="Tuesday" x:Name="tue" Tag="enabledDay" Click="enabledDays_Click" />
                                    <ToggleMenuFlyoutItem Text="Wednesday" x:Name="wed" Tag="enabledDay" Click="enabledDays_Click" />
                                    <ToggleMenuFlyoutItem Text="Thursday" x:Name="thu" Tag="enabledDay" Click="enabledDays_Click" />
                                    <ToggleMenuFlyoutItem Text="Friday" x:Name="fri" Tag="enabledDay" Click="enabledDays_Click" />
                                    <ToggleMenuFlyoutItem Text="Saturday" x:Name="sat" Tag="enabledDay" Click="enabledDays_Click" />
                                    <ToggleMenuFlyoutItem Text="Sunday" x:Name="sun" Tag="enabledDay" Click="enabledDays_Click" />
                                </MenuFlyout>
                            </FlyoutBase.AttachedFlyout>
                        </Button>
                        <TextBlock x:Name="enabledDaysText" />
                    </StackPanel>
                </StackPanel>
            </Grid>
        </DataTemplate>
    </HubSection>
</Hub>
</code>```

Body:
I want to make my MenuFlyout to don't disappear after I click at the ToggleMenuFlyoutItem. So if you could answer how can I do it simply that would be great. I come up with an idea to make function that will be called when any of ToggleMenuFlyoutItem has been clicked where I don;t hide MenuFlyout.
Here's XAML code snippet of my Hub:

<Hub x:Uid="SettingsPageTitle" x:Name="settingsPage" Header="Settings">
        <HubSection x:Uid="SettingsPageGeneral" x:Name="settingsGeneral" Header="General">
            <DataTemplate x:Uid="anotherSettingGeneralPage">
                <Grid>
                    <StackPanel Width="500" Height="500" x:Name="settingsGeneralPage" Background="WhiteSmoke">
                        <StackPanel x:Name="enabledDaysPage" Height="Auto">
                            <Button x:Name="enabledDays" Content="Enabled Days" FontWeight="Bold" Background="Transparent" Width="500" HorizontalContentAlignment="Left" Click="enabledDays_Click">
                                <FlyoutBase.AttachedFlyout>
                                    <MenuFlyout x:Name="enabledDaysMenuFlyout">
                                        <ToggleMenuFlyoutItem x:Name="mon" Text="Monday" Tag="enabledDay" Click="enabledDays_Click"/>
                                        <ToggleMenuFlyoutItem Text="Tuesday" x:Name="tue" Tag="enabledDay" Click="enabledDays_Click"/>
                                        <ToggleMenuFlyoutItem Text="Wednesday" x:Name="wed" Tag="enabledDay" Click="enabledDays_Click"/>
                                        <ToggleMenuFlyoutItem Text="Thursday" x:Name="thu" Tag="enabledDay" Click="enabledDays_Click"/>
                                        <ToggleMenuFlyoutItem Text="Friday" x:Name="fri" Tag="enabledDay" Click="enabledDays_Click"/>
                                        <ToggleMenuFlyoutItem Text="Saturday" x:Name="sat" Tag="enabledDay" Click="enabledDays_Click"/>
                                        <ToggleMenuFlyoutItem Text="Sunday" x:Name="sun" Tag="enabledDay" Click="enabledDays_Click"/>
                                    </MenuFlyout>
                                </FlyoutBase.AttachedFlyout>
                            </Button>
                            <TextBlock x:Name="enabledDaysText"/>
                        </StackPanel>
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </HubSection>

So can you help to make this to happen? Or at least how can I access my MenuFlyout, note that i tried this but it didn't helped me. Thanks!

Body:
If you want to click the ToggleMenuFlyoutItem and do not want the MenuFlyout to be hided. You should be able to add the Closing event of the MenuFlyout.

In the Closing event, we can use the FlyoutBaseClosingEventArgs.Cancel property. If we set the true to it, it will prevent the flyout from closing.

For example:

private void enabledDaysMenuFlyout_Closing(FlyoutBase sender, FlyoutBaseClosingEventArgs args)
{
    args.Cancel = true;
}

Update:

<Hub x:Uid="SettingsPageTitle" x:Name="settingsPage" Header="Settings">
    <HubSection x:Uid="SettingsPageGeneral" x:Name="settingsGeneral" Header="General">
        <DataTemplate x:Uid="anotherSettingGeneralPage">
            <Grid>
                <StackPanel Width="500" Height="500" x:Name="settingsGeneralPage" Background="WhiteSmoke">
                    <StackPanel x:Name="enabledDaysPage" Height="Auto">
                        <Button x:Name="enabledDays" Content="Enabled Days" FontWeight="Bold" Background="Transparent" Width="500" HorizontalContentAlignment="Left" Click="enabledDays_Click">
                            <FlyoutBase.AttachedFlyout>
                                <MenuFlyout x:Name="enabledDaysMenuFlyout" Closing="enabledDaysMenuFlyout_Closing">
                                    <ToggleMenuFlyoutItem x:Name="mon" Text="Monday" Tag="enabledDay" Click="enabledDays_Click" />
                                    <ToggleMenuFlyoutItem Text="Tuesday" x:Name="tue" Tag="enabledDay" Click="enabledDays_Click" />
                                    <ToggleMenuFlyoutItem Text="Wednesday" x:Name="wed" Tag="enabledDay" Click="enabledDays_Click" />
                                    <ToggleMenuFlyoutItem Text="Thursday" x:Name="thu" Tag="enabledDay" Click="enabledDays_Click" />
                                    <ToggleMenuFlyoutItem Text="Friday" x:Name="fri" Tag="enabledDay" Click="enabledDays_Click" />
                                    <ToggleMenuFlyoutItem Text="Saturday" x:Name="sat" Tag="enabledDay" Click="enabledDays_Click" />
                                    <ToggleMenuFlyoutItem Text="Sunday" x:Name="sun" Tag="enabledDay" Click="enabledDays_Click" />
                                </MenuFlyout>
                            </FlyoutBase.AttachedFlyout>
                        </Button>
                        <TextBlock x:Name="enabledDaysText" />
                    </StackPanel>
                </StackPanel>
            </Grid>
        </DataTemplate>
    </HubSection>
</Hub>


问:
Swift filter dictionary error: Cannot assign a value of type '[(_, _)]' to a value of type '[_ : _]'
I am trying to filter a dictionary in swift:

```<code>var data: [String: String] = [:]
data = data.filter { $0.1 == "Test" }
</code>```

the filter code above compiles under Swift 2 but yields the following error:

Cannot assign a value of type '[(String, String)]' to a value of type '[String : String]'

is this a bug in the Swift compiler or is this not the right way to filter dictionaries in Swift?

答:
I've found this method to be useful after filtering or applying some other transform that results in an array of dictionary elements:

```<code>extension Array {
    func dictionary<K: Hashable, V>() -> [K: V] where Element == Dictionary<K, V>.Element {
        var dictionary = [K: V]()
        for element in self {
            dictionary[element.key] = element.value
        }
        return dictionary
    }
}
</code>```

To use it, just say something like:

```<code>dictionary = dictionary.filter{ $0.key == "test" }.dictionary()
</code>```

The advantage of this method is that no argument of any kind needs to be passed to the dictionary() method. Generic type arguments tell the compiler everything it needs to know.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to filter a dictionary in swift:

var data: [String: String] = [:]
data = data.filter { $0.1 == "Test" }

the filter code above compiles under Swift 2 but yields the following error:

Cannot assign a value of type '[(String, String)]' to a value of type '[String : String]'

is this a bug in the Swift compiler or is this not the right way to filter dictionaries in Swift?

Body:
I've found this method to be useful after filtering or applying some other transform that results in an array of dictionary elements:

extension Array {
    func dictionary<K: Hashable, V>() -> [K: V] where Element == Dictionary<K, V>.Element {
        var dictionary = [K: V]()
        for element in self {
            dictionary[element.key] = element.value
        }
        return dictionary
    }
}

To use it, just say something like:

dictionary = dictionary.filter{ $0.key == "test" }.dictionary()

The advantage of this method is that no argument of any kind needs to be passed to the dictionary() method. Generic type arguments tell the compiler everything it needs to know.


问:
Preserve SSI (Server Side includes) declarations with gulp-uglify
During gulp-uglify task, SSI (server side includes) declarations are removed, maybe because uglify() removes invalid blocks of non-javascript code.

i.e.:

mymodule-source.js

```<code>"use strict";
<!--# include file="/ssi/config.js" -->
window.mymodule = function(mymodule) {};
</code>```

After uglify() call on gulp pipe, it compress file to the following:

mymodule-minified.js

```<code>"use strict";window.mymodule=function(e){};
</code>```

Expected result for app health, is the following result:

mymodule-expected.js

```<code>"use strict";<!--# include file="/ssi/config.js" -->window.mymodule=function(e){};
</code>```

There is some kind of filter to declare to avoid SSI declarations being purged from final minified/uglified file?

By example, some kind of filter over regex ]+>

答:
I have the same question.I noticed that uglifyJs has --comment parameter.
 Preserve copyright comments in the output. By
                                default this works like Google Closure, keeping
                                JSDoc-style comments that contain "@license" or
                                "@preserve". You can optionally pass one of the
                                following arguments to this flag:
                                - "all" to keep all comments
                                - a valid JS RegExp like /foo/ or /^!/ to
                                keep only matching comments.
                                Note that currently not all comments can be
                                kept when compression is on, because of dead
                                code removal or cascading statements into
                                sequences.

But I don't know how to use --comment in gulp task.

Body:
During gulp-uglify task, SSI (server side includes) declarations are removed, maybe because uglify() removes invalid blocks of non-javascript code.

i.e.:

mymodule-source.js

"use strict";

window.mymodule = function(mymodule) {};

After uglify() call on gulp pipe, it compress file to the following:

mymodule-minified.js

"use strict";window.mymodule=function(e){};

Expected result for app health, is the following result:

mymodule-expected.js

"use strict";window.mymodule=function(e){};

There is some kind of filter to declare to avoid SSI declarations being purged from final minified/uglified file?

By example, some kind of filter over regex ]+>


问:
Jekyll / Bundler fails when creating new default site with `bundle exec jekyll new . --force`
I did bundle config --global path vendor/bundle so that Bundler installs dependencies (including Jekyll) to project directories instead of GEM_HOME. I don't have Jekyll installed to GEM_HOME.

When I initialized a project directory...

```<code>mkdir site && cd site
bundle init
</code>```

Updated the contents of my project Gemfile...

```<code># frozen_string_literal: true
source "https://rubygems.org"

gem "jekyll"
</code>```

Installed Jekyll to the project directory and created a new site with default scaffolding...

```<code>bundle install
bundle exec jekyll new . --force
</code>```

...I expected that Jekyll would write the default site scaffolding into the current directory, overwrite my original Gemfile, and then bundle install default site dependencies from its Gemfile (e.g., minima) to vendor/bundle.

Instead, here is the output:

```<code>Running bundle install in /Users/joeptacek/site...
  Bundler: /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/resolver.rb:386:in `block in verify_gemfile_dependencies_are_found!': Could not find gem 'minima (~> 2.0)' in any of the gem sources listed in your Gemfile. (Bundler::GemNotFound)
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/resolver.rb:356:in `each'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/resolver.rb:356:in `verify_gemfile_dependencies_are_found!'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/resolver.rb:203:in `start'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/resolver.rb:182:in `resolve'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/definition.rb:252:in `resolve'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/definition.rb:176:in `specs'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/definition.rb:235:in `specs_for'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/definition.rb:224:in `requested_specs'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/runtime.rb:118:in `block in definition_method'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/runtime.rb:19:in `setup'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler.rb:100:in `setup'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/setup.rb:20:in `<top (required)>'
  Bundler: from /Users/joeptacek/.rubies/ruby-2.4.1/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  Bundler: from /Users/joeptacek/.rubies/ruby-2.4.1/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
</code>```

If I run bundle install again, the dependencies are installed without further issue.

To avoid errors, my workaround has been to make a new site with

```<code>bundle exec jekyll new . --force --skip-bundle && bundle install
</code>```

Is this a bug, or am I misunderstanding something about the way Jekyll and Bundler work?

答:
From what I gather, the only difference in your workflow from the official documentation is that you install jekyll gem and its dependencies to vendor/bundle.

jekyll new creates a Gemfile along with the site scaffolding. So you needn't initialize one beforehand and then overwrite it with the --force switch.

To scaffold a new Jekyll Site at /projects/site, you simply need to do the following:

```<code># from 'projects/' directory
$ jekyll new site
</code>```

Now you may edit the Gemfile and include any other gems as required.

Note: Its not bundle exec jekyll new -- but plain ol' jekyll new.

bundle exec is prepended to every other command only if a Gemfile exists within the directory.

Body:
I did bundle config --global path vendor/bundle so that Bundler installs dependencies (including Jekyll) to project directories instead of GEM_HOME. I don't have Jekyll installed to GEM_HOME.

When I initialized a project directory...

mkdir site && cd site
bundle init

Updated the contents of my project Gemfile...

# frozen_string_literal: true
source "https://rubygems.org"

gem "jekyll"

Installed Jekyll to the project directory and created a new site with default scaffolding...

bundle install
bundle exec jekyll new . --force

...I expected that Jekyll would write the default site scaffolding into the current directory, overwrite my original Gemfile, and then bundle install default site dependencies from its Gemfile (e.g., minima) to vendor/bundle.

Instead, here is the output:

Running bundle install in /Users/joeptacek/site...
  Bundler: /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/resolver.rb:386:in `block in verify_gemfile_dependencies_are_found!': Could not find gem 'minima (~> 2.0)' in any of the gem sources listed in your Gemfile. (Bundler::GemNotFound)
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/resolver.rb:356:in `each'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/resolver.rb:356:in `verify_gemfile_dependencies_are_found!'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/resolver.rb:203:in `start'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/resolver.rb:182:in `resolve'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/definition.rb:252:in `resolve'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/definition.rb:176:in `specs'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/definition.rb:235:in `specs_for'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/definition.rb:224:in `requested_specs'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/runtime.rb:118:in `block in definition_method'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/runtime.rb:19:in `setup'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler.rb:100:in `setup'
  Bundler: from /Users/joeptacek/.gem/ruby/2.4.1/gems/bundler-1.14.6/lib/bundler/setup.rb:20:in `<top (required)>'
  Bundler: from /Users/joeptacek/.rubies/ruby-2.4.1/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  Bundler: from /Users/joeptacek/.rubies/ruby-2.4.1/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'

If I run bundle install again, the dependencies are installed without further issue.

To avoid errors, my workaround has been to make a new site with

bundle exec jekyll new . --force --skip-bundle && bundle install

Is this a bug, or am I misunderstanding something about the way Jekyll and Bundler work?

Body:
From what I gather, the only difference in your workflow from the official documentation is that you install jekyll gem and its dependencies to vendor/bundle.

jekyll new creates a Gemfile along with the site scaffolding. So you needn't initialize one beforehand and then overwrite it with the --force switch.

To scaffold a new Jekyll Site at /projects/site, you simply need to do the following:

# from 'projects/' directory
$ jekyll new site

Now you may edit the Gemfile and include any other gems as required.

Note: Its not bundle exec jekyll new -- but plain ol' jekyll new.

bundle exec is prepended to every other command only if a Gemfile exists within the directory.


问:
What does %{} do in Ruby?
In Matt's post about drying up cucumber tests, Aslak suggests the following.

When I have lots of quotes, I prefer this:

Given %{I enter “#{User.first.username}” in “username”}

What is the %{CONTENT} construct called? Will someone mind referencing it in some documentation? I'm not sure how to go about looking it up.

There's also the stuff about %Q. Is that equivalent to just %? What of the curly braces? Can you use square braces? Do they function differently?

Finally, what is the #{<ruby stuff to be evaluated>} construct called? Is there a reference to that in documentation somewhere, too?

答:
None of the other answers actually answer the question.

This is percent sign notation.  The percent sign indicates that the next character is a literal delimiter, and you can use any (non alphanumeric) one you want.  For example:

```<code>%{stuff}
%[stuff]
%?stuff?
</code>```

etc.  This allows you to put double quotes, single quotes etc into the string without escaping:

```<code>%{foo='bar with embedded "baz"'}
</code>```

returns the literal string:
foo='bar with embedded "baz"'

The percent sign can be followed by a letter modifier to determine how the string is interpolated.  For example, %Q[ ] is an interpolated String, %q[ ] is a non-interpolated String, %i[ ]   is a non-interpolated Array of Symbols etc.  So for example:

```<code> %i#potato tuna#
</code>```

returns this array of Symbols:

```<code>[:potato, :tuna]
</code>```

Details are here: Wikibooks

ContentLicense: CC BY-SA 2.5

Title: What does %{} do in Ruby?

Body:
None of the other answers actually answer the question.

This is percent sign notation.  The percent sign indicates that the next character is a literal delimiter, and you can use any (non alphanumeric) one you want.  For example:

%{stuff}
%[stuff]
%?stuff?

etc.  This allows you to put double quotes, single quotes etc into the string without escaping:

%{foo='bar with embedded "baz"'}

returns the literal string:
foo='bar with embedded "baz"'

The percent sign can be followed by a letter modifier to determine how the string is interpolated.  For example, %Q[ ] is an interpolated String, %q[ ] is a non-interpolated String, %i[ ]   is a non-interpolated Array of Symbols etc.  So for example:

 %i#potato tuna#

returns this array of Symbols:

[:potato, :tuna]

Details are here: Wikibooks


问:
Python OS - check if file exists, if so rename, check again, then save
I have a script that takes a file from a form, renames it and uploads it to a folder and inserts record into a database. I would like to add the functionality where before the file is saved, it checks the upload folder to determine if the filename exists. If it does exist, renames the file in a loop and then saves the file.

What I have currently:

```<code>file = request.files['xx']
extension = os.path.splitext(file.filename)[1]
xx = str(uuid.uuid4()) + extension
## if xx exists .. xx = str(uuid.uuid4()) + extension.. loop endlessly.
file.save(os.path.join(app.config['UPLOAD_FOLDER'], xx)
</code>```

答:
Have you tried to use the glob Module, it provides an interface similar to ls, you can use it as it follows:

```<code>import os
import glob
file_list = glob.glob('my_file')
if len(file_list) > 0:
   os.rename('my_file', 'new_name')
</code>```

Body:
I have a script that takes a file from a form, renames it and uploads it to a folder and inserts record into a database. I would like to add the functionality where before the file is saved, it checks the upload folder to determine if the filename exists. If it does exist, renames the file in a loop and then saves the file.

What I have currently:

file = request.files['xx']
extension = os.path.splitext(file.filename)[1]
xx = str(uuid.uuid4()) + extension
## if xx exists .. xx = str(uuid.uuid4()) + extension.. loop endlessly.
file.save(os.path.join(app.config['UPLOAD_FOLDER'], xx)

Body:
Have you tried to use the glob Module, it provides an interface similar to ls, you can use it as it follows:

import os
import glob
file_list = glob.glob('my_file')
if len(file_list) > 0:
   os.rename('my_file', 'new_name')


问:
Entity Framework Core is slow - how do I make it faster?
Retrieve records from database and assign it to an object.

```<code>private readonly ApplicationDbContext _context;
var itemsData = _context.Items;

for (int i = 0; i < itemsData.Count(); i++)
{
    _Response.Items.Add(new Models.Items
        {
            Name = itemsData.ToList()[i].Name,
            ....
            Created = (DateTime)itemsData.ToList()[i].Created,
            Updated = (DateTime)itemsData.ToList()[i].Updated
        });
}
</code>```

Note: There are less than 1000 records and already it's noticeability slow.

答:
You are calling ToList on every iteration, which executes the SQL query against the database every time. Do this 1000 times and no wonder it's slow.

Just call ToList once and then foreach the result:

```<code>var itemsData = _context.Items.ToList();

foreach (var item in itemsData)
{
    _Response.Items.Add(new Models.Items
    {
        Name = item .Name,
        ....
        Created = (DateTime)item.Created,
        Updated = (DateTime)item.Updated
    });
}
</code>```

Body:
Retrieve records from database and assign it to an object.

private readonly ApplicationDbContext _context;
var itemsData = _context.Items;

for (int i = 0; i < itemsData.Count(); i++)
{
    _Response.Items.Add(new Models.Items
        {
            Name = itemsData.ToList()[i].Name,
            ....
            Created = (DateTime)itemsData.ToList()[i].Created,
            Updated = (DateTime)itemsData.ToList()[i].Updated
        });
}

Note: There are less than 1000 records and already it's noticeability slow.

Body:
You are calling ToList on every iteration, which executes the SQL query against the database every time. Do this 1000 times and no wonder it's slow.

Just call ToList once and then foreach the result:

var itemsData = _context.Items.ToList();

foreach (var item in itemsData)
{
    _Response.Items.Add(new Models.Items
    {
        Name = item .Name,
        ....
        Created = (DateTime)item.Created,
        Updated = (DateTime)item.Updated
    });
}


问:
jQuery .when().then() not working as expected
I have an object which acts as a client side API Client which exposes several functions which all return jQuery ajax() objects. Some of those ajax calls have .done() and .fail() calls chained directly onto them because they are actions which need to be taken every time the API responses come back before the rest of the js code is allowed to deal with the response. Pretty standard stuff.

I need to kick off a variable number of API requests, wait for all to fail or succeed, and then continue processing. For the examples I will create, I will simplify this down to just two ajax calls.

So I create an array to hold the returned ajax objects, and then use $.when().apply(null, deferreds).then(function(){//do something after both ajax requests complete}). When the calls complete successfully, everything works great. When calls fail (such as if the ajax call 404s), things are not so great.

The problem is that .then() doesn't seem to detect the fails, even though I thought then() was supposed to be fired regardless of success or failure of the underlying promise(s).

I can switch to .always(), which seems to work better (in that it detects the failures and still triggers the callback) but it seems to fire before some of the .fail() callbacks that are registered directly on the ajax calls, which doesn't make sense to me since I thought the callbacks for an ajax call were called in the order they were registered.

I'm sure I'm just missing something about the behavior of the ajax() when() then() combo.

Fiddle showing successful calls using .then(): https://jsfiddle.net/kwrLyw6q/5/

Fiddle using .then() with failed ajax calls (not working, would love to know why. Seems like this is the "right" way to do it, but I can't figure out where I'm going wrong): https://jsfiddle.net/kwrLyw6q/2/

Fiddle using .always() (working, but notice the out-of-order callback order. At least, out of order compared to the order I want them!): https://jsfiddle.net/kwrLyw6q/7/

答:
It looks like deferred.then() takes three arguments:

success function (first argument).

fail function (second argument).

progress function (third)

updated fiddle


问:
strange for loop? C#

Possible Duplicate:

  In C# is a for(;;) safe and what does it really do?

So i recently came across something ive never seen before..

```<code>        for (; ; )
        {

        }
</code>```

What is exactly happening when the feilds are left blank like that?

答:
This is an infinite loop, almost equivalent to a while(true) loop.

The break condition is not there in between the two semicolons, therefore, it must be there somewhere in the loop body.

Title: strange for loop? C#

Body:
Possible Duplicate:

  In C# is a for(;;) safe and what does it really do?

So i recently came across something ive never seen before..

        for (; ; )
        {

        }

What is exactly happening when the feilds are left blank like that?


问:
How to use quotes in bash scrips when a command in the script needs quotes too?
I am attempting to make a script that will make a backup file of a video file in the same directory with the time stamp at the end of the tar file. The script is for demonstration purposes only, that is why I do not intend on sending the file to a different directory. Below is how far I have come with it.

```<code>#!/bin/bash
cd Compression_Play/
echo Me.$(date +%d_%b_%Y-%k:%M:%S).tar.xz
tar -I "pixz -9t" -cvf Me.$(date +%d_%b_%Y-%k:%M:%S).tar.xz 2017-03-23_01-13-02.avi
</code>```

My problem is whenever I try to execute the script it gives me this:

```<code>Me.29_Mar_2017-22:03:49.tar.xz
tar: -9: (PROGRAM ERROR) Option should have been recognized!?
Try 'tar --help' or 'tar --usage' for more information.
</code>```

As best as I can tell the problem is with the quotes in my tar command. Is there a way to make the script so I can keep the quotes or substitute them?

答:
Given your goal to make an archive, presumably preserving owner, file modes, file flags and ACLs, if available, then this should do what you need:

```<code>#!/bin/bash
archive_name="Me.$(date +%d_%b_%Y-%k:%M:%S).tar.xz"
$(cd Compression_Play/
  tar -cvp 2017-03-23_01-13-02.avi |
  pixz -9t > $archive_name
)
</code>```

Based on the GitHub page for tarball compress/decompress for pixz, you will need to reverse the pipe to get your data out:

```<code>pixz -x9T < $archive_name | tar xvpf -
</code>```

Body:
I am attempting to make a script that will make a backup file of a video file in the same directory with the time stamp at the end of the tar file. The script is for demonstration purposes only, that is why I do not intend on sending the file to a different directory. Below is how far I have come with it.

#!/bin/bash
cd Compression_Play/
echo Me.$(date +%d_%b_%Y-%k:%M:%S).tar.xz
tar -I "pixz -9t" -cvf Me.$(date +%d_%b_%Y-%k:%M:%S).tar.xz 2017-03-23_01-13-02.avi

My problem is whenever I try to execute the script it gives me this:

Me.29_Mar_2017-22:03:49.tar.xz
tar: -9: (PROGRAM ERROR) Option should have been recognized!?
Try 'tar --help' or 'tar --usage' for more information.

As best as I can tell the problem is with the quotes in my tar command. Is there a way to make the script so I can keep the quotes or substitute them?

Body:
Given your goal to make an archive, presumably preserving owner, file modes, file flags and ACLs, if available, then this should do what you need:

#!/bin/bash
archive_name="Me.$(date +%d_%b_%Y-%k:%M:%S).tar.xz"
$(cd Compression_Play/
  tar -cvp 2017-03-23_01-13-02.avi |
  pixz -9t > $archive_name
)

Based on the GitHub page for tarball compress/decompress for pixz, you will need to reverse the pipe to get your data out:

pixz -x9T < $archive_name | tar xvpf -


问:
Heroku - error running browserify on Node deployment
I'm trying to deploy a Node app to Heroku, but I'm having an issue successfully running browserify when the app is deployed.

When I'm running locally, I browserify my script with npm run bundle like so (from package.json):

"bundle": "./node_modules/browserify/bin/cmd.js build/main.js -o public/scripts/bundle.js

which browserifies the script in build/main.js and puts it into public/scripts/bundle.js.

For deploying to Heroku, I added

"postinstall": "npm run bundle"

However, when I deploy, I get the following error:

Error: ENOENT: no such file or directory, open 'public/scripts/bundle.js.tmp-browserify-59309133185877094263'

Well, that's correct, that file shouldn't exist... yet. When I run npm run bundle locally, I do see that file briefly pop into existence, but then it is quickly removed and I'm left with a nice updated bundle.js.

I read through Heroku's docs on this, but I'm miffed... can anyone clarify how to get through this?

For reference, here are the relevant parts of my package.json:

```<code>"scripts": {
    "bundle": "./node_modules/browserify/bin/cmd.js build/main.js -o public/scripts/bundle.js",
    "postinstall": "npm run bundle"
},
"dependencies": {
    "body-parser": "^1.17.1",
    "browserify": "^14.1.0",
    "ejs": "^2.5.6",
    "express": "^4.15.2",
    "jquery": "^3.2.1",
    "path": "^0.12.7",
    "superagent": "^3.5.2"
},
"devDependencies": {},
"engines": {
    "node": "6.8.1",
    "npm": "4.0.5"
}
</code>```

答: Solved!  I had bundle.js included in my global gitinore configuration.  Just had to take that out, good to go!

Body:
I'm trying to deploy a Node app to Heroku, but I'm having an issue successfully running browserify when the app is deployed.

When I'm running locally, I browserify my script with npm run bundle like so (from package.json):

"bundle": "./node_modules/browserify/bin/cmd.js build/main.js -o public/scripts/bundle.js

which browserifies the script in build/main.js and puts it into public/scripts/bundle.js.

For deploying to Heroku, I added

"postinstall": "npm run bundle"

However, when I deploy, I get the following error:

Error: ENOENT: no such file or directory, open 'public/scripts/bundle.js.tmp-browserify-59309133185877094263'

Well, that's correct, that file shouldn't exist... yet. When I run npm run bundle locally, I do see that file briefly pop into existence, but then it is quickly removed and I'm left with a nice updated bundle.js.

I read through Heroku's docs on this, but I'm miffed... can anyone clarify how to get through this?

For reference, here are the relevant parts of my package.json:

"scripts": {
    "bundle": "./node_modules/browserify/bin/cmd.js build/main.js -o public/scripts/bundle.js",
    "postinstall": "npm run bundle"
},
"dependencies": {
    "body-parser": "^1.17.1",
    "browserify": "^14.1.0",
    "ejs": "^2.5.6",
    "express": "^4.15.2",
    "jquery": "^3.2.1",
    "path": "^0.12.7",
    "superagent": "^3.5.2"
},
"devDependencies": {},
"engines": {
    "node": "6.8.1",
    "npm": "4.0.5"
}


问:
New Google ReCAPTCHA with django-recaptcha
Is there an easy way to adapt the django-recaptcha plugin for using the new google re-captcha API?
I already changed the template and the captcha gets displayed in the write way but the validation is not working. Has anybody an idea how I can fix this in an easy way?</p>

答:
I know your question is old, but Nowadays, you just have to write in settings.py:

```<code>NOCAPTCHA = True
</code>```

And that's it.

Body:
I know your question is old, but Nowadays, you just have to write in settings.py:

NOCAPTCHA = True

And that's it.


问:
Substitute formal arguments in a function factory r
I'm trying to make a function factory to make functions with custom formal argument names. The idea is to supply a string to the factory, which in turn substitutes it both in the formals and in the body of the function returned. I've managed to do it using eval(parse(text=paste())) , but I read elsewhere that this bad practice. How can I get the same output while avoiding doing evalparse?</p>

```<code>MyLinearRateFunctions<-function(varX){

  eval(parse(text=paste("function(a,b,",
                    varX,
                    ") 1/(a + b*",
                    varX,
                    ")",sep="")
  ))

 }

(LinearRateMPG<-MyLinearRateFunctions('mpg'))

# function(a,b,mpg) 1/(a + b*mpg)
# <environment: 0x11c2f2a00>

(LinearRateCYL<-MyLinearRateFunctions('cyl'))

# function(a,b,cyl) 1/(a + b*cyl)
# <environment: 0x11e4cb908>

(LinearRateDISP<-MyLinearRateFunctions('disp'))

# function(a,b,disp) 1/(a + b*disp)
# <environment: 0x11e47eae8>
</code>```

答:
Here is an alternative which uses pryr::make_function. This has the added benefit of setting the function "environment" to the  calling environment of the "function factory" call

```<code>fn2 <- function(x) {
  fbody <- bquote(1 / (a + b * .(as.name(x))))
  fargs <- setNames(alist(,,),c('a','b',x))
  pryr::make_function(fargs,fbody, env=parent.frame(2))
}
</code>```

While this looks like it avoids a call to eval, it is simply hidden within make_function

Body:
I'm trying to make a function factory to make functions with custom formal argument names. The idea is to supply a string to the factory, which in turn substitutes it both in the formals and in the body of the function returned. I've managed to do it using eval(parse(text=paste())) , but I read elsewhere that this bad practice. How can I get the same output while avoiding doing evalparse?

MyLinearRateFunctions<-function(varX){

  eval(parse(text=paste("function(a,b,",
                    varX,
                    ") 1/(a + b*",
                    varX,
                    ")",sep="")
  ))

 }

(LinearRateMPG<-MyLinearRateFunctions('mpg'))

# function(a,b,mpg) 1/(a + b*mpg)
# <environment: 0x11c2f2a00>

(LinearRateCYL<-MyLinearRateFunctions('cyl'))

# function(a,b,cyl) 1/(a + b*cyl)
# <environment: 0x11e4cb908>

(LinearRateDISP<-MyLinearRateFunctions('disp'))

# function(a,b,disp) 1/(a + b*disp)
# <environment: 0x11e47eae8>

Body:
Here is an alternative which uses pryr::make_function. This has the added benefit of setting the function "environment" to the  calling environment of the "function factory" call

fn2 <- function(x) {
  fbody <- bquote(1 / (a + b * .(as.name(x))))
  fargs <- setNames(alist(,,),c('a','b',x))
  pryr::make_function(fargs,fbody, env=parent.frame(2))
}

While this looks like it avoids a call to eval, it is simply hidden within make_function


问:
Erlang - serialize a string (with no newlines/carriage returns)?
I've seen some answers to this in other programming languages, but not a specific erlang one. I'm able to read the file and I use:

```<code>re:replace(Subject, RE, Replacement, Options)
</code>```

specifically:

```<code>re:replace(Content, "\r" , " ",[global,{return,list}]),
</code>```

to remove those escape sequences (I believe that's what they are called)

And it perfectly replaces all the \r with a space. So my question is:

1) is there a way to put multiple replacements in RE, so I could also remove "\n"?

2) is there a different/better/more efficient way to do it?

答:
It's the basics of regular expressions.

In your first question, you can use the solution:

```<code>re:replace(Content, "[\r\n]", " ", [global, {return, list}])
</code>```

Erlang string syntax is not convenient enough, if you need to do a lot of very complex string processing, you should consider using another language.

Body:
I've seen some answers to this in other programming languages, but not a specific erlang one. I'm able to read the file and I use:

re:replace(Subject, RE, Replacement, Options)

specifically:

re:replace(Content, "\r" , " ",[global,{return,list}]),

to remove those escape sequences (I believe that's what they are called)

And it perfectly replaces all the \r with a space. So my question is:

1) is there a way to put multiple replacements in RE, so I could also remove "\n"?

2) is there a different/better/more efficient way to do it?

Body:
It's the basics of regular expressions.

In your first question, you can use the solution:

re:replace(Content, "[\r\n]", " ", [global, {return, list}])

Erlang string syntax is not convenient enough, if you need to do a lot of very complex string processing, you should consider using another language.


问:
Trying to compute the error from comparing two arrays
Some context: I have an explicit formula which is the exact solution to my problem. I have written code which implements a finite-difference scheme (explicit Forward-Euler, i.e: forward march-in-time iterative scheme) to approximate the solution to a partial differential equation (PDE). I have discretized the problem.

I want to compare these two and verify that the error between the exact solution and my approximation to the solution is indeed small. I have stored the values of the exact solution and the approximation in two (NxM) arrays, for each time-step and node in space.

Here is the code I have written to calculate the error:

```<code># Compute the Error
E = np.zeros((N+1, M+1)) # so that E has NxM entries--one for each time-step and node in space
for m in range(1, M+1):
    for j in range(0, N+1):
        E_new = np.absolute(BS[j,m] - u[j,m])
        if (np.any(E_new >= E)):
            E = E_new
        else:
            E = E

print 'Error = ', E
</code>```

Here, I am taking N = 100, M = 10,000. If necessary, I can post the segments of my code where I calculate the arrays BS and u. Both are defined as arrays of the same size, and when I plot them, I am receiving an output which agrees with what the solution looks like. So I believe I am on the right track and that the rest of my code is working as it is supposed to.

However, when I run this particular segment in an attempt to calculate the error, I get that the error is roughly 29. I know this is wrong, the error should be small.

My attempt to fix the problem:

I think the problem possibly lies in the line containing if (np.any(E_new >= E)):. I want to check if any entry of the array E_new is greater than or equal to E. If I just run it with if (E_new >= E):, I get this ValueError: "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()."

I also tried running this: if (np.any([E_new, E])):, but again no luck. I received this error message, "ValueError: setting an array element with a sequence". I have also tried using np.all in place of np.any in each of my attempts and this also does not seem to fix the issue.

Here is some pseudocode for what I wish to do:

```<code>E = 0
for i = 1,...,N:
    E_new = | BS(x_i) - u_i |
    if E_new >= E
        E = E_new
    else:
        E = E
    end
</code>```

Any and all help is very greatly appreciated. Thank you in advance! I am really stuck here and I do not know how to move forward. I don't need a direct answer necessarily, but some insight as to what is causing the problem and a push in the right direction would be immensely helpful. Thanks again!!

答:
Maybe it would help to go through your program line-by-line:

```<code># Compute the Error
E = np.zeros((N+1, M+1)) # so that E has NxM entries--one for each time-step and node in space
# to get NxM use np.zeros((N, M))

for m in range(1, M+1):
    for j in range(0, N+1):
    # any reason you start the outer loop at 1 and the inner loop at 0?

        E_new = np.absolute(BS[j,m] - u[j,m])
        # if BS is MxN (or (M+1)x(N+1)) BS[j, m] selects the entry at the
        # j-th row and m-th column which is a scalar. Similar for u, so in
        # the end E_new will contain a scalar

        if (np.any(E_new >= E)):
        # at the first iteration this will compare the scalar E_new to the
        # array E resulting in an array of same shape of truth values
        # at all later iterations E will also be a scalar
        # the array allocated for E in the beginning will be garbage
        # collected

            E = E_new
        else:
            E = E

# why the error is so large in the end I can't tell you
print 'Error = ', E
</code>```

And a suggestions, if I may:

If you want the maximum element-wise absolute difference as an error measure you can have that in one line which as a bonus executes much faster because it is vectorised. Assuming BS and u have the same shape:

```<code>E = np.abs(BS-u).max()
</code>```

Body:
Some context: I have an explicit formula which is the exact solution to my problem. I have written code which implements a finite-difference scheme (explicit Forward-Euler, i.e: forward march-in-time iterative scheme) to approximate the solution to a partial differential equation (PDE). I have discretized the problem.

I want to compare these two and verify that the error between the exact solution and my approximation to the solution is indeed small. I have stored the values of the exact solution and the approximation in two (NxM) arrays, for each time-step and node in space.

Here is the code I have written to calculate the error:

# Compute the Error
E = np.zeros((N+1, M+1)) # so that E has NxM entries--one for each time-step and node in space
for m in range(1, M+1):
    for j in range(0, N+1):
        E_new = np.absolute(BS[j,m] - u[j,m])
        if (np.any(E_new >= E)):
            E = E_new
        else:
            E = E

print 'Error = ', E

Here, I am taking N = 100, M = 10,000. If necessary, I can post the segments of my code where I calculate the arrays BS and u. Both are defined as arrays of the same size, and when I plot them, I am receiving an output which agrees with what the solution looks like. So I believe I am on the right track and that the rest of my code is working as it is supposed to.

However, when I run this particular segment in an attempt to calculate the error, I get that the error is roughly 29. I know this is wrong, the error should be small.

My attempt to fix the problem:

I think the problem possibly lies in the line containing if (np.any(E_new >= E)):. I want to check if any entry of the array E_new is greater than or equal to E. If I just run it with if (E_new >= E):, I get this ValueError: "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()."

I also tried running this: if (np.any([E_new, E])):, but again no luck. I received this error message, "ValueError: setting an array element with a sequence". I have also tried using np.all in place of np.any in each of my attempts and this also does not seem to fix the issue.

Here is some pseudocode for what I wish to do:

E = 0
for i = 1,...,N:
    E_new = | BS(x_i) - u_i |
    if E_new >= E
        E = E_new
    else:
        E = E
    end

Any and all help is very greatly appreciated. Thank you in advance! I am really stuck here and I do not know how to move forward. I don't need a direct answer necessarily, but some insight as to what is causing the problem and a push in the right direction would be immensely helpful. Thanks again!!

Body:
Maybe it would help to go through your program line-by-line:

# Compute the Error
E = np.zeros((N+1, M+1)) # so that E has NxM entries--one for each time-step and node in space
# to get NxM use np.zeros((N, M))

for m in range(1, M+1):
    for j in range(0, N+1):
    # any reason you start the outer loop at 1 and the inner loop at 0?

        E_new = np.absolute(BS[j,m] - u[j,m])
        # if BS is MxN (or (M+1)x(N+1)) BS[j, m] selects the entry at the
        # j-th row and m-th column which is a scalar. Similar for u, so in
        # the end E_new will contain a scalar

        if (np.any(E_new >= E)):
        # at the first iteration this will compare the scalar E_new to the
        # array E resulting in an array of same shape of truth values
        # at all later iterations E will also be a scalar
        # the array allocated for E in the beginning will be garbage
        # collected

            E = E_new
        else:
            E = E

# why the error is so large in the end I can't tell you
print 'Error = ', E

And a suggestions, if I may:

If you want the maximum element-wise absolute difference as an error measure you can have that in one line which as a bonus executes much faster because it is vectorised. Assuming BS and u have the same shape:

E = np.abs(BS-u).max()


答:
Haven't tested this yet but you can use os.path.isfile() to check if a file already exists (for directories, use os.path.exists).

```<code>import os

def save():
    file = request.files['xx']
    extension = os.path.splitext(file.filename)[1]

    xx = generate_filename(extension)

    file.save(os.path.join(app.config['UPLOAD_FOLDER'], xx))

def generate_filename(extension):
    xx = str(uuid.uuid4()) + extension
    if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], xx)):
        return generate_filename(extension)
    return xx
</code>```

Title: Python OS - check if file exists, if so rename, check again, then save

Body:
Haven't tested this yet but you can use os.path.isfile() to check if a file already exists (for directories, use os.path.exists).

import os

def save():
    file = request.files['xx']
    extension = os.path.splitext(file.filename)[1]

    xx = generate_filename(extension)

    file.save(os.path.join(app.config['UPLOAD_FOLDER'], xx))

def generate_filename(extension):
    xx = str(uuid.uuid4()) + extension
    if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], xx)):
        return generate_filename(extension)
    return xx


问:
Java selenium avoiding iframe address bar element
Currently I wrote a short program that traverses through a page and looks for web elements with the tagname = "input", then uses sendkeys to send data to the element, then submits it. The problem I have is that although it works most of the time, if I have an iframe on the page, and I traverse through the webpage looking for an element with the tagname = "input", it focuses on the addressbar of the iframe and sends data to it, then tries to submit it causing an error (when I printed the tagname of the addressbar in the iframe, it printed out "input" on the console).

Is there a way to avoid the addressbar on an iframe from being picked up as an element with the tagname = "input"?

Im using the following to check if an element has tagname of "input":

```<code>    List<WebElement> element = driver.findElements(By.xpath("//*"));
    int mainSize = element.size();

    for ( int j = 0; j < mainSize; j++ ) {
        if(frameElement.get(j).getTagName().toString().equals("input")){
        //do something
        }
    }
</code>```

Some notes:

-This occurs when going through the webpage elements searching through tagnames for "input" elements BEFORE switching to the iframe element with the switchTo() method.

答:
In order to avoid the address bar, you can introduce one more check to ensure that the input element is not an address bar. Following is the updated code to achieve this:

```<code>List<WebElement> element = driver.findElements(By.xpath("//*"));
        int mainSize = element.size();

        for ( int j = 0; j < mainSize; j++ ) {
            if(element.get(j).getTagName().toString().equals("input") &&
                    !element.get(j).getAttribute("class").equals("urlbar")){
            //do something
            }
        }
</code>```

UPDATE 1

We can retry when unexpected browser search bar appears. Try following:

```<code> List<WebElement> element = driver.findElements(By.xpath("//*"));
        int mainSize = element.size();

        for ( int j = 0; j < mainSize; j++ ) {
            if(element.get(j).getTagName().toString().equals("input") &&
                    !element.get(j).getAttribute("class").equals("urlbar")){
            //do something
                try {
                element.get(j).sendKeys(somedata);
                element.get(j).submit();
            } catch (WebDriverException we) {
                System.out.println("It seems browser search bar has been appeared. Retrying...");
                //Pressing escape key to get rid of browser search bar
                element.get(j).sendKeys(Keys.ESCAPE);
                //Retrying
                element.get(j).sendKeys(somedata);
                element.get(j).submit();
            }
        }
     }
</code>```

Let me know, if you have any further queries.

Body:
Currently I wrote a short program that traverses through a page and looks for web elements with the tagname = "input", then uses sendkeys to send data to the element, then submits it. The problem I have is that although it works most of the time, if I have an iframe on the page, and I traverse through the webpage looking for an element with the tagname = "input", it focuses on the addressbar of the iframe and sends data to it, then tries to submit it causing an error (when I printed the tagname of the addressbar in the iframe, it printed out "input" on the console).

Is there a way to avoid the addressbar on an iframe from being picked up as an element with the tagname = "input"?

Im using the following to check if an element has tagname of "input":

    List<WebElement> element = driver.findElements(By.xpath("//*"));
    int mainSize = element.size();

    for ( int j = 0; j < mainSize; j++ ) {
        if(frameElement.get(j).getTagName().toString().equals("input")){
        //do something
        }
    }

Some notes:

-This occurs when going through the webpage elements searching through tagnames for "input" elements BEFORE switching to the iframe element with the switchTo() method.

Body:
In order to avoid the address bar, you can introduce one more check to ensure that the input element is not an address bar. Following is the updated code to achieve this:

List<WebElement> element = driver.findElements(By.xpath("//*"));
        int mainSize = element.size();

        for ( int j = 0; j < mainSize; j++ ) {
            if(element.get(j).getTagName().toString().equals("input") &&
                    !element.get(j).getAttribute("class").equals("urlbar")){
            //do something
            }
        }

UPDATE 1

We can retry when unexpected browser search bar appears. Try following:

 List<WebElement> element = driver.findElements(By.xpath("//*"));
        int mainSize = element.size();

        for ( int j = 0; j < mainSize; j++ ) {
            if(element.get(j).getTagName().toString().equals("input") &&
                    !element.get(j).getAttribute("class").equals("urlbar")){
            //do something
                try {
                element.get(j).sendKeys(somedata);
                element.get(j).submit();
            } catch (WebDriverException we) {
                System.out.println("It seems browser search bar has been appeared. Retrying...");
                //Pressing escape key to get rid of browser search bar
                element.get(j).sendKeys(Keys.ESCAPE);
                //Retrying
                element.get(j).sendKeys(somedata);
                element.get(j).submit();
            }
        }
     }

Let me know, if you have any further queries.


问:
Ruby LoadError issue with 'require'
I have researched this for quite some time, and have yet to solve my issue. Here is the error that I am receiving:

```<code>C:/Ruby23/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- nexpose-runner/constants (LoadError)
  from C:/Ruby23/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in require'
  from scan.rb:4:in `<main>'
</code>```

Here is my code:

```<code>require 'nexpose'
require 'csv'
require 'json'
require 'nexpose-runner/constants'
require 'nexpose-runner/scan_run_description'

module NexposeRunner
module Scan
def Scan.start(options)

  run_details = ScanRunDescription.new(options)
  run_details.verify

  nsc = get_new_nexpose_connection(run_details)

  site = create_site(run_details, nsc)

  start_scan(nsc, site, run_details)

  reports = generate_reports(nsc, site, run_details)

  verify_run(reports[0])
end

def self.generate_reports(nsc, site, run_details)
  puts "Scan complete for #{run_details.site_name}, Generating Vulnerability Report"
  vulnerbilities = generate_report(CONSTANTS::VULNERABILITY_REPORT_QUERY, site.id, nsc)
  generate_csv(vulnerbilities, CONSTANTS::VULNERABILITY_REPORT_NAME)

  puts "Scan complete for #{run_details.site_name}, Generating Vulnerability Detail Report"
  vuln_details = generate_report(CONSTANTS:: VULNERABILITY_DETAIL_REPORT_QUERY, site.id, nsc)
  generate_csv(vuln_details, CONSTANTS::VULNERABILITY_DETAIL_REPORT_NAME)

  puts "Scan complete for #{run_details.site_name}, Generating Software Report"
  software = generate_report(CONSTANTS::SOFTWARE_REPORT_QUERY, site.id, nsc)
  generate_csv(software, CONSTANTS::SOFTWARE_REPORT_NAME)

  puts "Scan complete for #{run_details.site_name}, Generating Policy Report"
  policies = generate_report(CONSTANTS::POLICY_REPORT_QUERY, site.id, nsc)
  generate_csv(policies, CONSTANTS::POLICY_REPORT_NAME)

  puts "Scan complete for #{run_details.site_name}, Generating Audit Report"
  generate_template_report(nsc, site.id, CONSTANTS::AUDIT_REPORT_FILE_NAME, CONSTANTS::AUDIT_REPORT_NAME, CONSTANTS::AUDIT_REPORT_FORMAT)

  puts "Scan complete for #{run_details.site_name}, Generating Xml Report"
  generate_template_report(nsc, site.id, CONSTANTS::XML_REPORT_FILE_NAME, CONSTANTS::XML_REPORT_NAME, CONSTANTS::XML_REPORT_FORMAT)

  [vulnerbilities, software, policies]
end

def self.verify_run(vulnerabilities)

  raise StandardError, CONSTANTS::VULNERABILITY_FOUND_MESSAGE if vulnerabilities.count > 0

end

def self.start_scan(nsc, site, run_details)

  puts "Starting scan for #{run_details.site_name} using the #{run_details.scan_template} scan template"
  scan = site.scan nsc

  begin
    sleep(3)
    stats = nsc.scan_statistics(scan.id)
status = stats.status
    puts "Current #{run_details.site_name} scan status: #{status.to_s} -- PENDING: #{stats.tasks.pending.to_s} ACTIVE: #{stats.tasks.active.to_s} COMPLETED #{stats.tasks.completed.to_s}"
  end while status == Nexpose::Scan::Status::RUNNING
end

def self.create_site(run_details, nsc)
  puts "Creating a nexpose site named #{run_details.site_name}"
  site = Nexpose::Site.new run_details.site_name, run_details.scan_template
  run_details.ip_addresses.each { |address|
      site.add_ip address
  }
  if run_details.engine
    site.engine = run_details.engine
  end
  site.save nsc
  puts "Created site #{run_details.site_name} successfully with the following host(s) #{run_details.ip_addresses.join(', ')}"

  site
end

def self.get_new_nexpose_connection(run_details)
  nsc = Nexpose::Connection.new run_details.connection_url, run_details.username, run_details.password, run_details.port
  nsc.login
  puts 'Successfully logged into the Nexpose Server'
  nsc
end

def self.generate_report(sql, site, nsc)
  report = Nexpose::AdhocReportConfig.new(nil, 'sql')
  report.add_filter('version', '1.3.0')
  report.add_filter('query', sql)
  report.add_filter('site', site)
  report_output = report.generate(nsc)
  CSV.parse(report_output.chomp, {:headers => :first_row})
end

def self.generate_template_report(nsc, site, file_name, report_name, report_format)
  adhoc = Nexpose::AdhocReportConfig.new(report_name, report_format, site)
  data = adhoc.generate(nsc)
  File.open(file_name, 'w') { |file| file.write(data) }
end

def self.generate_csv(csv_output, name)
  CSV.open(name, 'w') do |csv_file|
    csv_file << csv_output.headers
    csv_output.each do |row|
      csv_file << row
      if name == CONSTANTS::VULNERABILITY_REPORT_NAME
        puts '--------------------------------------'
        puts "IP: #{row[0]}"
        puts "Vulnerability: #{row[1]}"
        puts "Date Vulnerability was Published: #{row[2]}"
        puts "Severity: #{row[3]}"
        puts "Summary: #{row[4]}"
        puts '--------------------------------------'
      end
     end
    end
  end
 end
end
</code>```

In the command prompt, I am entering in the following code to run it (this file is called scan.rb):

ruby scan.rb "http://localhost:3780" "username" "password" "3780" "webpage" "ip-address" "full-audit-widget-corp"

So far, I've tried changing require to require_relative, as well as re-arranging the paths (like putting the whole path, for example). Neither has worked.

I also made sure to have the Ruby Development Kit installed.

Thanks!

答: please check the local gem list:  gem list --local</p>

Title: Ruby LoadError issue with 'require'

Body:
I have researched this for quite some time, and have yet to solve my issue. Here is the error that I am receiving:

C:/Ruby23/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- nexpose-runner/constants (LoadError)
  from C:/Ruby23/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in require'
  from scan.rb:4:in `'

Here is my code:

require 'nexpose'
require 'csv'
require 'json'
require 'nexpose-runner/constants'
require 'nexpose-runner/scan_run_description'

module NexposeRunner
module Scan
def Scan.start(options)

  run_details = ScanRunDescription.new(options)
  run_details.verify

  nsc = get_new_nexpose_connection(run_details)

  site = create_site(run_details, nsc)

  start_scan(nsc, site, run_details)

  reports = generate_reports(nsc, site, run_details)

  verify_run(reports[0])
end

def self.generate_reports(nsc, site, run_details)
  puts "Scan complete for #{run_details.site_name}, Generating Vulnerability Report"
  vulnerbilities = generate_report(CONSTANTS::VULNERABILITY_REPORT_QUERY, site.id, nsc)
  generate_csv(vulnerbilities, CONSTANTS::VULNERABILITY_REPORT_NAME)

  puts "Scan complete for #{run_details.site_name}, Generating Vulnerability Detail Report"
  vuln_details = generate_report(CONSTANTS:: VULNERABILITY_DETAIL_REPORT_QUERY, site.id, nsc)
  generate_csv(vuln_details, CONSTANTS::VULNERABILITY_DETAIL_REPORT_NAME)

  puts "Scan complete for #{run_details.site_name}, Generating Software Report"
  software = generate_report(CONSTANTS::SOFTWARE_REPORT_QUERY, site.id, nsc)
  generate_csv(software, CONSTANTS::SOFTWARE_REPORT_NAME)

  puts "Scan complete for #{run_details.site_name}, Generating Policy Report"
  policies = generate_report(CONSTANTS::POLICY_REPORT_QUERY, site.id, nsc)
  generate_csv(policies, CONSTANTS::POLICY_REPORT_NAME)

  puts "Scan complete for #{run_details.site_name}, Generating Audit Report"
  generate_template_report(nsc, site.id, CONSTANTS::AUDIT_REPORT_FILE_NAME, CONSTANTS::AUDIT_REPORT_NAME, CONSTANTS::AUDIT_REPORT_FORMAT)

  puts "Scan complete for #{run_details.site_name}, Generating Xml Report"
  generate_template_report(nsc, site.id, CONSTANTS::XML_REPORT_FILE_NAME, CONSTANTS::XML_REPORT_NAME, CONSTANTS::XML_REPORT_FORMAT)

  [vulnerbilities, software, policies]
end

def self.verify_run(vulnerabilities)

  raise StandardError, CONSTANTS::VULNERABILITY_FOUND_MESSAGE if vulnerabilities.count > 0

end

def self.start_scan(nsc, site, run_details)

  puts "Starting scan for #{run_details.site_name} using the #{run_details.scan_template} scan template"
  scan = site.scan nsc

  begin
    sleep(3)
    stats = nsc.scan_statistics(scan.id)
status = stats.status
    puts "Current #{run_details.site_name} scan status: #{status.to_s} -- PENDING: #{stats.tasks.pending.to_s} ACTIVE: #{stats.tasks.active.to_s} COMPLETED #{stats.tasks.completed.to_s}"
  end while status == Nexpose::Scan::Status::RUNNING
end

def self.create_site(run_details, nsc)
  puts "Creating a nexpose site named #{run_details.site_name}"
  site = Nexpose::Site.new run_details.site_name, run_details.scan_template
  run_details.ip_addresses.each { |address|
      site.add_ip address
  }
  if run_details.engine
    site.engine = run_details.engine
  end
  site.save nsc
  puts "Created site #{run_details.site_name} successfully with the following host(s) #{run_details.ip_addresses.join(', ')}"

  site
end

def self.get_new_nexpose_connection(run_details)
  nsc = Nexpose::Connection.new run_details.connection_url, run_details.username, run_details.password, run_details.port
  nsc.login
  puts 'Successfully logged into the Nexpose Server'
  nsc
end

def self.generate_report(sql, site, nsc)
  report = Nexpose::AdhocReportConfig.new(nil, 'sql')
  report.add_filter('version', '1.3.0')
  report.add_filter('query', sql)
  report.add_filter('site', site)
  report_output = report.generate(nsc)
  CSV.parse(report_output.chomp, {:headers => :first_row})
end

def self.generate_template_report(nsc, site, file_name, report_name, report_format)
  adhoc = Nexpose::AdhocReportConfig.new(report_name, report_format, site)
  data = adhoc.generate(nsc)
  File.open(file_name, 'w') { |file| file.write(data) }
end

def self.generate_csv(csv_output, name)
  CSV.open(name, 'w') do |csv_file|
    csv_file << csv_output.headers
    csv_output.each do |row|
      csv_file << row
      if name == CONSTANTS::VULNERABILITY_REPORT_NAME
        puts '--------------------------------------'
        puts "IP: #{row[0]}"
        puts "Vulnerability: #{row[1]}"
        puts "Date Vulnerability was Published: #{row[2]}"
        puts "Severity: #{row[3]}"
        puts "Summary: #{row[4]}"
        puts '--------------------------------------'
      end
     end
    end
  end
 end
end

In the command prompt, I am entering in the following code to run it (this file is called scan.rb):

ruby scan.rb "http://localhost:3780" "username" "password" "3780" "webpage" "ip-address" "full-audit-widget-corp"

So far, I've tried changing require to require_relative, as well as re-arranging the paths (like putting the whole path, for example). Neither has worked.

I also made sure to have the Ruby Development Kit installed.

Thanks!


问:
jQuery : eq() vs get()
I'm new to jQuery, and I'm wondering what the difference is between jQuery's get() and eq() functions.  I may misunderstand what the get() function does, but I thought it odd that I couldn't call a function on the returned on the returned element in the same line.

```<code>//Doesn't work
I.e.  $("h2").get(0).fadeIn("slow");

//Works
$("h2").eq(0).fadeIn("slow");
</code>```

答:
Answers above have explained specificly and correctly. I want to add a few points here that might help for the use of get().

If you don't pass an argument to .get(), it will return an Array of the DOM elements.

If you got a DOM object using get(), like
var s = $("#id").get(0)
you can turn it back into jQuery object simply by using this, $(s)

You can use $obj[i] as an alternative way if you don't want to use $obj.get(i), see below,

```<code>var $obj = $("#ul li");
var obj1 = $obj.get(1);
var obj2 = $obj[1];

//true
return obj2===obj1;
</code>```

Title: jQuery : eq() vs get()

Body:
I'm new to jQuery, and I'm wondering what the difference is between jQuery's get() and eq() functions.  I may misunderstand what the get() function does, but I thought it odd that I couldn't call a function on the returned on the returned element in the same line.

//Doesn't work
I.e.  $("h2").get(0).fadeIn("slow");

//Works
$("h2").eq(0).fadeIn("slow");

Body:
Answers above have explained specificly and correctly. I want to add a few points here that might help for the use of get().

If you don't pass an argument to .get(), it will return an Array of the DOM elements.

If you got a DOM object using get(), like
var s = $("#id").get(0)
you can turn it back into jQuery object simply by using this, $(s)

You can use $obj[i] as an alternative way if you don't want to use $obj.get(i), see below,

var $obj = $("#ul li");
var obj1 = $obj.get(1);
var obj2 = $obj[1];

//true
return obj2===obj1;