问:
Return 2 unique answers per ID
I have a SQL query that pulls in too much information for what I need. My current query looks like this:

```<code>USE LetterGeneration

SELECT g.LetterGenerationTemplateRequestId,
      cast(H.CreatedDate as time) as Time,
      s.StatusKey

FROM LetterGenerationStatusHistory H

INNER JOIN LetterGenerationStatus S
ON H.LetterGenerationStatusId = s.LetterGenerationStatusId
INNER JOIN LetterGeneration G
ON g.LetterGenerationId = h.LetterGenerationId

WHERE g.LetterGenerationTemplateRequestId IN (SELECT [LetterGenerationTemplateRequestId]
                                        FROM [LetterGenerationTemplateRequest]
                                        WHERE CreatedDate >= DATEADD(day,-90, GETDATE()))
AND (s.StatusKey = 'QC1'
OR s.StatusKey = 'Ready')

ORDER BY LetterGenerationTemplateRequestId, h.CreatedDate ASC
</code>```

The results I get look like this:

```<code>LetterGenerationTemplateRequestId   Time          StatusKey
1732189                          01:14:24.1700000   QC1
1732189                          10:13:25.4730000   READY
1732190                          01:14:26.6600000   QC1
1732190                          01:14:26.7230000   QC1
1732190                          01:14:26.7970000   QC1
1732190                          01:14:26.8770000   QC1
1732190                          01:14:26.9500000   QC1
1732190                          01:14:27.0370000   QC1
1732190                          01:14:27.1100000   QC1
1732190                          04:29:17.7170000   READY
1732190                          04:29:33.8500000   READY
1732190                          04:29:50.7900000   READY
</code>```

What I want is to see only 1 result for each Request ID that is status QC1 and status READY. So ideally it'd look like this:

```<code>Request ID  Time    Status
1732189 1:14:24 AM  QC1
1732189 10:13:25 AM READY
1732190 1:14:27 AM  QC1
1732190 4:29:18 AM  READY
1732191 1:14:30 AM  QC1
1732191 4:39:28 AM  READY
</code>```

etc

How can I limit the results to only show 1 status result per ID? I've checked some other questions on here and have tried to adjust them to fit my query but my limited knowledge of SQL has made it very difficult.

答:
You can use row_number():

```<code>SELECT t.*
FROM (SELECT g.LetterGenerationTemplateRequestId,
             cast(H.CreatedDate as time) as Time,
             s.StatusKey,
             ROW_NUMBER() OVER (PARTITION BY g.LetterGenerationTemplateRequestId, s.StatusKey
                                ORDER BY H.CreatedDate DESC
                               ) as seqnum
      FROM LetterGenerationStatusHistory H INNER JOIN
           LetterGenerationStatus S
           ON H.LetterGenerationStatusId = s.LetterGenerationStatusId INNER JOIN
           LetterGeneration G
           ON g.LetterGenerationId = h.LetterGenerationId
      WHERE g.LetterGenerationTemplateRequestId IN (SELECT [LetterGenerationTemplateRequestId]
                                                    FROM [LetterGenerationTemplateRequest]
                                                    WHERE CreatedDate >= DATEADD(day,-90, GETDATE())

                                            ) AND
            s.StatusKey IN ('QC1', 'Ready')
       ) t
WHERE seqnum <= 1
ORDER BY LetterGenerationTemplateRequestId, CreatedDate ASC;
</code>```

The ORDER BY in the ROW_NUMBER() syntax specifies which row you want.  In this case, it is the most recent row.

You can change the "1" in the outer WHERE to get as many rows per group as you like.

Title: Return 2 unique answers per ID

Body:
I have a SQL query that pulls in too much information for what I need. My current query looks like this:

USE LetterGeneration

SELECT g.LetterGenerationTemplateRequestId,
      cast(H.CreatedDate as time) as Time,
      s.StatusKey

FROM LetterGenerationStatusHistory H

INNER JOIN LetterGenerationStatus S
ON H.LetterGenerationStatusId = s.LetterGenerationStatusId
INNER JOIN LetterGeneration G
ON g.LetterGenerationId = h.LetterGenerationId

WHERE g.LetterGenerationTemplateRequestId IN (SELECT [LetterGenerationTemplateRequestId]
                                        FROM [LetterGenerationTemplateRequest]
                                        WHERE CreatedDate >= DATEADD(day,-90, GETDATE()))
AND (s.StatusKey = 'QC1'
OR s.StatusKey = 'Ready')

ORDER BY LetterGenerationTemplateRequestId, h.CreatedDate ASC

The results I get look like this:

LetterGenerationTemplateRequestId   Time          StatusKey
1732189                          01:14:24.1700000   QC1
1732189                          10:13:25.4730000   READY
1732190                          01:14:26.6600000   QC1
1732190                          01:14:26.7230000   QC1
1732190                          01:14:26.7970000   QC1
1732190                          01:14:26.8770000   QC1
1732190                          01:14:26.9500000   QC1
1732190                          01:14:27.0370000   QC1
1732190                          01:14:27.1100000   QC1
1732190                          04:29:17.7170000   READY
1732190                          04:29:33.8500000   READY
1732190                          04:29:50.7900000   READY

What I want is to see only 1 result for each Request ID that is status QC1 and status READY. So ideally it'd look like this:

Request ID  Time    Status
1732189 1:14:24 AM  QC1
1732189 10:13:25 AM READY
1732190 1:14:27 AM  QC1
1732190 4:29:18 AM  READY
1732191 1:14:30 AM  QC1
1732191 4:39:28 AM  READY

etc

How can I limit the results to only show 1 status result per ID? I've checked some other questions on here and have tried to adjust them to fit my query but my limited knowledge of SQL has made it very difficult.

Body:
You can use row_number():

SELECT t.*
FROM (SELECT g.LetterGenerationTemplateRequestId,
             cast(H.CreatedDate as time) as Time,
             s.StatusKey,
             ROW_NUMBER() OVER (PARTITION BY g.LetterGenerationTemplateRequestId, s.StatusKey
                                ORDER BY H.CreatedDate DESC
                               ) as seqnum
      FROM LetterGenerationStatusHistory H INNER JOIN
           LetterGenerationStatus S
           ON H.LetterGenerationStatusId = s.LetterGenerationStatusId INNER JOIN
           LetterGeneration G
           ON g.LetterGenerationId = h.LetterGenerationId
      WHERE g.LetterGenerationTemplateRequestId IN (SELECT [LetterGenerationTemplateRequestId]
                                                    FROM [LetterGenerationTemplateRequest]
                                                    WHERE CreatedDate >= DATEADD(day,-90, GETDATE())

                                            ) AND
            s.StatusKey IN ('QC1', 'Ready')
       ) t
WHERE seqnum <= 1
ORDER BY LetterGenerationTemplateRequestId, CreatedDate ASC;

The ORDER BY in the ROW_NUMBER() syntax specifies which row you want.  In this case, it is the most recent row.

You can change the "1" in the outer WHERE to get as many rows per group as you like.


来源: stackexchange

问:
webdriver can't find element on UI
I'm trying to test search UI using selenium web driver in java

If I click on result it shows some properties of that results.

So now when I click on first result, the webdriver is able to locate those properties by FindElementsByXpath("//li[@class='clickable ng-binding ng-scope']")

Also tried findElementsByCss("*[class='clickable ng-binding ng-scope']")

But when webdriver clicks on second result, it shows up their properties but webdriver is UNABLE to locate properties (have same class name as first).

Any help here?

can't use Xpath since ids are unique and different.

i click result using this-

```<code>findElement(By.xpath("/html/body/div[1]/div/div/div[1]/div[2]/div[1]/div[2]/div/els-result["+num+"]/div")).click();
</code>```

where num is result number

*Stack trace here

org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of all elements located by By.cssSelector: *[class='clickable ng-binding ng-scope'] (tried for 15 second(s) with 500 MILLISECONDS interval)
  Build info: version: '3.1.0', revision: '86a5d70', time: '2017-02-16 07:57:44 -0800'
  System info: host: '', ip: '', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.3', java.version: '1.8.0_121'
  Driver info: org.openqa.selenium.firefox.FirefoxDriver
  Capabilities [{rotatable=false, raisesAccessibilityExceptions=false, marionette=true, appBuildId=20170125094131, version=, platform=MAC, proxy={}, command_id=1, specificationLevel=0, acceptSslCerts=false, processId=22487, browserVersion=51.0.1, platformVersion=16.4.0, XULappId={ec8030f7-c20a-464f-9b0e-13a3a9e97384}, browserName=firefox, takesScreenshot=true, takesElementScreenshot=true, platformName=darwin, firefox_profile=UEsDBBQACAgIAOl6aUoAAAAAAAAAA..., unexpectedAlertBehaviour=dismiss}]
  Session ID: df2df541-1966-5a4b-871c-7cd8c295f4eb
      at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:80)
      at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:257)
      at cucumber.stepdefination.DataSearch.FindElementsByCss(DataSearch.java:166)
      at cucumber.stepdefination.AssestCountSD.assest_count_matches_list(AssestCountSD.java:76)
      at cucumber.stepdefination.AssestCountSD.for_each_source_assest_count_matches_that_in_list_on_right(AssestCountSD.java:51)
      at ✽.Then For each source assest count matches that in list on right(/Users/malikh/Documents/workspace/cucumber/src/test/resource/assetCount.feature:6)

答: I would suggest to use Firefox browser and install one of its extensions called 'Firepath'. This would help you to locate a UI element using both 'Xpath' and  'CSS'.</p>

ContentLicense: CC BY-SA 3.0

Title: webdriver can't find element on UI

Body:
I'm trying to test search UI using selenium web driver in java

If I click on result it shows some properties of that results.

So now when I click on first result, the webdriver is able to locate those properties by FindElementsByXpath("//li[@class='clickable ng-binding ng-scope']")

Also tried findElementsByCss("*[class='clickable ng-binding ng-scope']")

But when webdriver clicks on second result, it shows up their properties but webdriver is UNABLE to locate properties (have same class name as first).

Any help here?

can't use Xpath since ids are unique and different.

i click result using this-

findElement(By.xpath("/html/body/div[1]/div/div/div[1]/div[2]/div[1]/div[2]/div/els-result["+num+"]/div")).click();

where num is result number

*Stack trace here

org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of all elements located by By.cssSelector: *[class='clickable ng-binding ng-scope'] (tried for 15 second(s) with 500 MILLISECONDS interval)
  Build info: version: '3.1.0', revision: '86a5d70', time: '2017-02-16 07:57:44 -0800'
  System info: host: '', ip: '', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.3', java.version: '1.8.0_121'
  Driver info: org.openqa.selenium.firefox.FirefoxDriver
  Capabilities [{rotatable=false, raisesAccessibilityExceptions=false, marionette=true, appBuildId=20170125094131, version=, platform=MAC, proxy={}, command_id=1, specificationLevel=0, acceptSslCerts=false, processId=22487, browserVersion=51.0.1, platformVersion=16.4.0, XULappId={ec8030f7-c20a-464f-9b0e-13a3a9e97384}, browserName=firefox, takesScreenshot=true, takesElementScreenshot=true, platformName=darwin, firefox_profile=UEsDBBQACAgIAOl6aUoAAAAAAAAAA..., unexpectedAlertBehaviour=dismiss}]
  Session ID: df2df541-1966-5a4b-871c-7cd8c295f4eb
      at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:80)
      at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:257)
      at cucumber.stepdefination.DataSearch.FindElementsByCss(DataSearch.java:166)
      at cucumber.stepdefination.AssestCountSD.assest_count_matches_list(AssestCountSD.java:76)
      at cucumber.stepdefination.AssestCountSD.for_each_source_assest_count_matches_that_in_list_on_right(AssestCountSD.java:51)
      at ✽.Then For each source assest count matches that in list on right(/Users/malikh/Documents/workspace/cucumber/src/test/resource/assetCount.feature:6)


问:
Google Compute Engine API: Get object referenced in another object
I am trying to get the instance group for a given container engine cluster. I can successfully get the container cluster object, and it has a property called instanceGroupUrls which is a list of strings where each string is the full URL to an instance group:

```<code>In [14]: gke_api = discovery.build('container', 'v1', credentials=credentials)

In [15]: cluster = gke_api.projects().zones().clusters().get(
    projectId=project_id, zone=zone, clusterId=cluster_id).execute()

In [16]: cluster['instanceGroupUrls']
Out[16]: ['https://www.googleapis.com/compute/v1/projects/{project-id}/zones/{zone-id}/instanceGroupManagers/{instanceGroupID}']
</code>```

My question is: How do I get the instance group, given that I only have the full URL to the resource? Now, I could parse that URL and then use the api discovery thing to do instanceGroups.get(project='foo', instanceGroup='bar') but that seems very hacky and prone to breakage.

Does the API client has a way to provide the full URL? I have done much googling and poking around in IPython, but couldn't find much. The closest I got was the HttpRequest class (http://google.github.io/google-api-python-client/docs/epy/googleapiclient.http.HttpRequest-class.html) but I'm not sure what to pass in for the args.

Any help appreciated,
Aaron

答:
TL;DR - The discovery for container API is independent of the discovery for compute API and neither of them can understand the type of the resource using the URL.

If you just want to view the instance group resource, you can use the httplib2.Http object authenticated with your credentials to send a request to the URL.

If you want the flexibility to access the resource using the discovery for compute API, like you mentioned you will have to extract the zone and instanceGroupName fields out of the URL and pass it to instanceGroups.get() . BTW, this is not hacky since the resource format of the URL is very unlikely to change for most Google Cloud APIs. The instance group API doc is here.

1. Just viewing the Instance Group resource

If you wish to just view the instance group resource and access its properties without any modifications, you can use an authenticated Http object from httplib2 to GET the resource corresponding to the URL.

Working Example

```<code>from googleapiclient import discovery
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
import json
import pprint

# BEGIN CONFIG
PRIVATE_KEY_JSON = '/path/to/service_account_credentials.json'
API_SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
PROJECT_NAME = 'some-arbitrary-project'
ZONE_NAME = 'us-central1-a'
# END CONFIG

# Create a ServiceAccountCredentials object by reading the credentials from
# your JSON file. If you're using a different mechanism to load credentials
# like Application Default Credentials, substitute building the
# credentials object accordingly. I've added steps in the very
# end for using Application Default Credentials.
credentials = ServiceAccountCredentials.from_json_keyfile_name(
    PRIVATE_KEY_JSON, scopes=API_SCOPES)

# Create an authorized http object which can be used for making the
# API requests. We will use this later.
http_auth = credentials.authorize(Http())

# Build the Cloud Container Engine API object which you will be using for
# invoking the corresponding APIs using the authorized Http object
# you created earlier
gke_api = discovery.build('container', 'v1', credentials=credentials)

# List all clusters for the specified project and zone
cluster_list_response = gke_api.projects().zones().clusters().list(
    projectId=PROJECT_NAME, zone=ZONE_NAME).execute()
# Pick a cluster of interest
cluster = cluster_list_response['clusters'][0]
# Pick the instance group of interest
instance_group_url = cluster['instanceGroupUrls'][0]
print 'Instance Group URL: ' + instance_group_url

# Use the authorized Http object to make the request to fetch
# the instance group resource info.
response, content = http_auth.request(instance_group_url)
# Convert the json body into a dict for easy access.
instance_group = json.loads(content)

# Display the instance group using pprint.
print 'Instance Group Info: '
pprint.PrettyPrinter(indent=2).pprint(instance_group)
</code>```

Output

```<code>Instance Group URL: https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/zones/us-central1-a/instanceGroupManagers/gke-cluster-foo-some-group

Instance Group Info:
{ u'baseInstanceName': u'gke-cluster-foo-default-pool-abcdef',
  u'creationTimestamp': u'2017-07-07T10:11:12.678-07:00',
  u'currentActions': { u'abandoning': 0,
                       u'creating': 0,
                       u'creatingWithoutRetries': 0,
                       u'deleting': 0,
                       u'none': 3,
                       u'recreating': 0,
                       u'refreshing': 0,
                       u'restarting': 0},
  u'fingerprint': u'AABBCCDDEFG=',
  u'id': u'12345678901234',
  u'instanceGroup': u'https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/zones/us-central1-a/instanceGroups/gke-cluster-foo-default-pool-some-group',
  u'instanceTemplate': u'https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/global/instanceTemplates/gke-cluster-foo-default-pool-abcdef',
  u'kind': u'compute#instanceGroupManager',
  u'name': u'gke-cluster-foo-default-pool-some-group',
  u'selfLink': u'https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/zones/us-central1-a/instanceGroupManagers/gke-cluster-foo-default-pool-some-grp',
  u'targetSize': 3,
  u'zone': u'https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/zones/us-central1-a'}
</code>```

Application Default Credentials

Instead of a service account if you're using Application Default Credentials, you will need to make the following modifications to the above example where you build the credentials object and rest of the code remains the same:

```<code>from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
</code>```

2. Extracting the instance group name and using the Compute API

Below is a code snippet (you might need to combine with the snippet I've posted above) for extracting the instance group name and zone name components from the URL. There is no need to extract the project name since it will be the same as the project where you have your Google Container Engine cluster. The output is identical to above.

Snippet to extract the info from URL and invoke Compute Engine API

```<code>import urlparse

# Extract the path component of the URL, and using that extract instance group
# name and zone name.
instance_group_url_components = urlparse.urlsplit(
    instance_group_url).path.split('/')
instance_group_name = instance_group_url_components[-1]
zone_name = instance_group_url_components[-3]

compute_api = discovery.build('compute', 'v1', credentials=credentials)
instance_group_info = compute_api.instanceGroups().get(
    project=PROJECT_NAME, zone=zone_name,
    instanceGroup=instance_group_name).execute()

print 'Instance Group Info: '
pprint.PrettyPrinter(indent=2).pprint(instance_group)
</code>```

Output

```<code>Instance Group URL: https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/zones/us-central1-a/instanceGroupManagers/gke-cluster-foo-some-group

Instance Group Info:
{ u'baseInstanceName': u'gke-cluster-foo-default-pool-abcdef',
  u'creationTimestamp': u'2017-07-07T10:11:12.678-07:00',
  u'currentActions': { u'abandoning': 0,
                       u'creating': 0,
                       u'creatingWithoutRetries': 0,
                       u'deleting': 0,
                       u'none': 3,
                       u'recreating': 0,
                       u'refreshing': 0,
                       u'restarting': 0},
  u'fingerprint': u'AABBCCDDEFG=',
  u'id': u'12345678901234',
  u'instanceGroup': u'https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/zones/us-central1-a/instanceGroups/gke-cluster-foo-default-pool-some-group',
  u'instanceTemplate': u'https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/global/instanceTemplates/gke-cluster-foo-default-pool-abcdef',
  u'kind': u'compute#instanceGroupManager',
  u'name': u'gke-cluster-foo-default-pool-some-group',
  u'selfLink': u'https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/zones/us-central1-a/instanceGroupManagers/gke-cluster-foo-default-pool-some-grp',
  u'targetSize': 3,
  u'zone': u'https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/zones/us-central1-a'}
</code>```

Body:
I am trying to get the instance group for a given container engine cluster. I can successfully get the container cluster object, and it has a property called instanceGroupUrls which is a list of strings where each string is the full URL to an instance group:

In [14]: gke_api = discovery.build('container', 'v1', credentials=credentials)

In [15]: cluster = gke_api.projects().zones().clusters().get(
    projectId=project_id, zone=zone, clusterId=cluster_id).execute()

In [16]: cluster['instanceGroupUrls']
Out[16]: ['https://www.googleapis.com/compute/v1/projects/{project-id}/zones/{zone-id}/instanceGroupManagers/{instanceGroupID}']

My question is: How do I get the instance group, given that I only have the full URL to the resource? Now, I could parse that URL and then use the api discovery thing to do instanceGroups.get(project='foo', instanceGroup='bar') but that seems very hacky and prone to breakage.

Does the API client has a way to provide the full URL? I have done much googling and poking around in IPython, but couldn't find much. The closest I got was the HttpRequest class (http://google.github.io/google-api-python-client/docs/epy/googleapiclient.http.HttpRequest-class.html) but I'm not sure what to pass in for the args.

Any help appreciated,
Aaron

Body:
TL;DR - The discovery for container API is independent of the discovery for compute API and neither of them can understand the type of the resource using the URL.

If you just want to view the instance group resource, you can use the httplib2.Http object authenticated with your credentials to send a request to the URL.

If you want the flexibility to access the resource using the discovery for compute API, like you mentioned you will have to extract the zone and instanceGroupName fields out of the URL and pass it to instanceGroups.get() . BTW, this is not hacky since the resource format of the URL is very unlikely to change for most Google Cloud APIs. The instance group API doc is here.

1. Just viewing the Instance Group resource

If you wish to just view the instance group resource and access its properties without any modifications, you can use an authenticated Http object from httplib2 to GET the resource corresponding to the URL.

Working Example

from googleapiclient import discovery
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
import json
import pprint

# BEGIN CONFIG
PRIVATE_KEY_JSON = '/path/to/service_account_credentials.json'
API_SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
PROJECT_NAME = 'some-arbitrary-project'
ZONE_NAME = 'us-central1-a'
# END CONFIG

# Create a ServiceAccountCredentials object by reading the credentials from
# your JSON file. If you're using a different mechanism to load credentials
# like Application Default Credentials, substitute building the
# credentials object accordingly. I've added steps in the very
# end for using Application Default Credentials.
credentials = ServiceAccountCredentials.from_json_keyfile_name(
    PRIVATE_KEY_JSON, scopes=API_SCOPES)

# Create an authorized http object which can be used for making the
# API requests. We will use this later.
http_auth = credentials.authorize(Http())

# Build the Cloud Container Engine API object which you will be using for
# invoking the corresponding APIs using the authorized Http object
# you created earlier
gke_api = discovery.build('container', 'v1', credentials=credentials)

# List all clusters for the specified project and zone
cluster_list_response = gke_api.projects().zones().clusters().list(
    projectId=PROJECT_NAME, zone=ZONE_NAME).execute()
# Pick a cluster of interest
cluster = cluster_list_response['clusters'][0]
# Pick the instance group of interest
instance_group_url = cluster['instanceGroupUrls'][0]
print 'Instance Group URL: ' + instance_group_url

# Use the authorized Http object to make the request to fetch
# the instance group resource info.
response, content = http_auth.request(instance_group_url)
# Convert the json body into a dict for easy access.
instance_group = json.loads(content)

# Display the instance group using pprint.
print 'Instance Group Info: '
pprint.PrettyPrinter(indent=2).pprint(instance_group)

Output

Instance Group URL: https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/zones/us-central1-a/instanceGroupManagers/gke-cluster-foo-some-group

Instance Group Info:
{ u'baseInstanceName': u'gke-cluster-foo-default-pool-abcdef',
  u'creationTimestamp': u'2017-07-07T10:11:12.678-07:00',
  u'currentActions': { u'abandoning': 0,
                       u'creating': 0,
                       u'creatingWithoutRetries': 0,
                       u'deleting': 0,
                       u'none': 3,
                       u'recreating': 0,
                       u'refreshing': 0,
                       u'restarting': 0},
  u'fingerprint': u'AABBCCDDEFG=',
  u'id': u'12345678901234',
  u'instanceGroup': u'https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/zones/us-central1-a/instanceGroups/gke-cluster-foo-default-pool-some-group',
  u'instanceTemplate': u'https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/global/instanceTemplates/gke-cluster-foo-default-pool-abcdef',
  u'kind': u'compute#instanceGroupManager',
  u'name': u'gke-cluster-foo-default-pool-some-group',
  u'selfLink': u'https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/zones/us-central1-a/instanceGroupManagers/gke-cluster-foo-default-pool-some-grp',
  u'targetSize': 3,
  u'zone': u'https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/zones/us-central1-a'}

Application Default Credentials

Instead of a service account if you're using Application Default Credentials, you will need to make the following modifications to the above example where you build the credentials object and rest of the code remains the same:

from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()

2. Extracting the instance group name and using the Compute API

Below is a code snippet (you might need to combine with the snippet I've posted above) for extracting the instance group name and zone name components from the URL. There is no need to extract the project name since it will be the same as the project where you have your Google Container Engine cluster. The output is identical to above.

Snippet to extract the info from URL and invoke Compute Engine API

import urlparse

# Extract the path component of the URL, and using that extract instance group
# name and zone name.
instance_group_url_components = urlparse.urlsplit(
    instance_group_url).path.split('/')
instance_group_name = instance_group_url_components[-1]
zone_name = instance_group_url_components[-3]

compute_api = discovery.build('compute', 'v1', credentials=credentials)
instance_group_info = compute_api.instanceGroups().get(
    project=PROJECT_NAME, zone=zone_name,
    instanceGroup=instance_group_name).execute()

print 'Instance Group Info: '
pprint.PrettyPrinter(indent=2).pprint(instance_group)

Output

Instance Group URL: https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/zones/us-central1-a/instanceGroupManagers/gke-cluster-foo-some-group

Instance Group Info:
{ u'baseInstanceName': u'gke-cluster-foo-default-pool-abcdef',
  u'creationTimestamp': u'2017-07-07T10:11:12.678-07:00',
  u'currentActions': { u'abandoning': 0,
                       u'creating': 0,
                       u'creatingWithoutRetries': 0,
                       u'deleting': 0,
                       u'none': 3,
                       u'recreating': 0,
                       u'refreshing': 0,
                       u'restarting': 0},
  u'fingerprint': u'AABBCCDDEFG=',
  u'id': u'12345678901234',
  u'instanceGroup': u'https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/zones/us-central1-a/instanceGroups/gke-cluster-foo-default-pool-some-group',
  u'instanceTemplate': u'https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/global/instanceTemplates/gke-cluster-foo-default-pool-abcdef',
  u'kind': u'compute#instanceGroupManager',
  u'name': u'gke-cluster-foo-default-pool-some-group',
  u'selfLink': u'https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/zones/us-central1-a/instanceGroupManagers/gke-cluster-foo-default-pool-some-grp',
  u'targetSize': 3,
  u'zone': u'https://www.googleapis.com/compute/v1/projects/some-arbitrary-project/zones/us-central1-a'}


问:
Automate the generation of natural keys
I'm studying a way to serialize part of the data in database A and deserialize it in database B (a sort of save/restore between different installations) and I've had a look to Django natural keys to avoid problems due to duplicated IDs.

The only issue is that I should add a custom manager and a new method to all my models. Is there a way to make Django automatically generate natural keys by looking at unique=True or unique_togheter fields?

答: In that case you should use a GUID as your key. The database can automatically generate these for you. Google uniqueidentifier. We have 50+ warehouses all inserting data remotely and send their data up to our primary database using SQL Server replication. They all use a GUID as the primary key as this is guaranteed to be unique. It works very well.

ContentLicense: CC BY-SA 2.5

Title: Automate the generation of natural keys


问:
Bash syntax error executing command in Ruby, but it works in shell
Here is the command (the one I'm using is a slight variation of it, but this produces the same error)

```<code>HTTP_STATUS=$(curl -w "%{http_code}" -o >(cat >&3) 'http://example.org')
</code>```

As for what this does, it's mostly copied from https://superuser.com/a/862395/334171 ... the point is to print the output of a HTTP request to the terminal, but store the status code in a bash variable. This works fine if I run it in terminal.

However, I get sh: 1: Syntax error: "(" unexpected when I run it from Ruby:

```<code>cmd = <<-SH
  HTTP_STATUS=$(curl -w "%{http_code}" -o >(cat >&3) 'http://example.org')
SH
system cmd
`#{cmd}`
</code>```

both of these fail with the aformentioned error.

I suppose as a workaround I could put in a shell script and call that from Ruby. But I'm curious why it's not working in the inline fashion.

答:
bash behaves differently when you run using the name sh so /bin/bash and /bin/sh will behave differently even when /bin/sh really is /bin/bash. In particular, when bash is run as sh, it conforms as closely as possible to the POSIX specification so bash-specific extensions (such as your >(cat >&3)) won't work. Furthermore, backticks and related methods in Ruby always use the system shell (i.e. /bin/sh). In summary: if you're using a shell from within Ruby then you'll almost always end up using a strictly POSIX shell.

You could explicitly invoke /bin/bash and use -c to feed it commands. This will probably involve a nightmare of escaping though.

Better would be to bypass the shell (all of them) by using Open3 from the Ruby standard library. There are various methods in Open3 for capturing and piping the standard output and standard error and you won't have to worry about shell-quoting anything because there won't be a shell involved.

BTW, if you're really trying to set an environment variable through backticks or system, it won't work as environment variables are local to the child process so the parent (your Ruby script or whatever invoked your Ruby script) will never see them.

Body:
Here is the command (the one I'm using is a slight variation of it, but this produces the same error)

HTTP_STATUS=$(curl -w "%{http_code}" -o >(cat >&3) 'http://example.org')

As for what this does, it's mostly copied from https://superuser.com/a/862395/334171 ... the point is to print the output of a HTTP request to the terminal, but store the status code in a bash variable. This works fine if I run it in terminal.

However, I get sh: 1: Syntax error: "(" unexpected when I run it from Ruby:

cmd = <<-SH
  HTTP_STATUS=$(curl -w "%{http_code}" -o >(cat >&3) 'http://example.org')
SH
system cmd
`#{cmd}`

both of these fail with the aformentioned error.

I suppose as a workaround I could put in a shell script and call that from Ruby. But I'm curious why it's not working in the inline fashion.


问:
ISO ert inline test idiom (appending TEST_OUTPUT from multiple ert calls)
---+ BRIEF

Q: if I have multiple, separate, independent calls to ert, can I arrange to concatenate the output of these tests in the same buffer?  With the calls to ert being made at different times?

(Without a centralized thingamajig that knows about these independent tests.)

E.g. if I have two (or more) tests, e.g. in a .emacs file

```<code> (ert-deftest test1 ()(should t))
 (ert 'test1)

 ... many miles away, quite likely in a separate file ...

 (ert-deftest test2 ()(should t))
 (ert 'test2)
</code>```

Both will run - I can tell this by looking at *Messages*

```<code>...
Running 1 tests (2017-07-07 12:10:39-0700)
   passed  1/1  test_ag_non-null_and_true
...
Running 1 tests (2017-07-07 12:10:39-0700)
   passed  1/1  test-ag-code-disabling
...
</code>```

But the *ert* buffer will only contain output for the last test run.

---+ DETAIL

---++ MOTIVATION

Q: Why do I want to do this?

A: "inline testing". In particular, inline testing of stuff in my .emacs file (and in files it loads and/or requires).

Tests that are run every time .emacs or similar file is loaded.  (There may be other tests that I run in batch mode - but here I am talking about tests that I want to run right away, every time .emacs is loaded (and convenient for edit/debug while modifying .emacs).

I.e. I am looking for an idiom for inline tests.

I have been putting code in my .emacs and ~/lib/gnu-emacs/**.el files that looks like this:

```<code>;; some blob of code
(defun foo (arg) ... )

(ert-deftest test-foo () ... )
(ert 'test-foo)
</code>```

i.e. I define the function, the test, and run the test, right next to each other.

... I might as well admit that I often wrap a `progn' around,

```<code>(progn
   ;; some blob of code
   (defun foo (arg) ... )
   (ert-deftest test-foo () ... )
   (ert 'test-foo)
)
</code>```

because this makes it easy to make an edit to function foo or the test, and then jump to the end of the progn and do eval-last-sexp (which I have bound to C-j).  And I often also wrap an if or and and around, to make it easy to disable a feature that is in development. Sometimes with let* in then mix, if the feature has variables.

(I have used other ert- family runners, like ert-run-tests-batch and ert-run-tests-interactively. But plain old ert seems enough.)

(Putting defun and deftest inside a progn or other breaks some tools that expect defun to always be at top level. And it makes multiline docstrings even uglier. But it is darn convenient, and IMHO tools that operate on programming language files should parse the programming language.)

So, later, I will do the same thing for another module. Far away. Possibly in a separate file, possibly a library file.

```<code>(progn
   ;; some blob of code
   (defun bar (arg) ... )
   (ert-deftest test-bar () ... )
   (ert 'test-bar)
)
</code>```

Neither module should know about the other.

Nor should there be a centralized module that has a list of all such tests, that get run at the end.

If only because there may be a failure partway through loading the file. And it is convenient to know what tests up to that point passed or failed.

(Whereas collecting and running all tests at the end loses that incremental test running ability.)

---++ Should be a macro

I hate repetition. E.g. in the stuff below, I hate having to type BAR three times.

```<code>(progn
   ;; some blob of code
   (defun BAR (arg) ... )
   (ert-deftest test-BAR () ... )
   (ert 'test-BAR)
)
</code>```

Therefore, of course I will create a macro that reduces this repetition. Although then folks looking for the ert-deftest will get confused...

---++ MEDIUM LENGTH SIMPLE EXAMPLE

If I have

```<code>  (ert-deftest test1 ()(should t))
  (ert 'test1)
</code>```

I will get a nice *ert* buffer

```<code>Selector: test1
Passed:  1
Failed:  0
Skipped: 0
Total:   1/1

Started at:   2017-07-07 14:16:06-0700
Finished.
Finished at:  2017-07-07 14:16:07-0700

.
</code>```

and if later I have

```<code>(ert-deftest test2 () (should t))
(ert 'test2)
</code>```

It will erase the output of test1 in the *ert* buffer, and replace it with

```<code>Selector: test2
Passed:  1
Failed:  0
Skipped: 0
Total:   1/1

Started at:   2017-07-07 14:15:47-0700
Finished.
Finished at:  2017-07-07 14:15:47-0700

.
</code>```

What I would like is to have the output of both tests concatenated:

```<code>...
Running 1 tests (2017-07-07 12:10:39-0700)
   passed  1/1  test_ag_non-null_and_true
...
Running 1 tests (2017-07-07 12:10:39-0700)
   passed  1/1  test-ag-code-disabling
...
</code>```0

答:
As so often happens, the act of posting the question suggests the answer.

Although it is somewhat ugly, and certainly non-standard.  So if anyone posts a concise standard-ish way, I will accept such an answer.

The IMHO ugly way:

When I do

```<code>(progn
   ;; some blob of code
   (defun foo (arg) ... )
   (ert-deftest test-foo () ... )
   (ert 'test-foo)
)
</code>```

I can add more code to manipulate the ert output buffer:

```<code>(progn
   ;; some blob of code
   (defun foo (arg) ... )
   (ert-deftest test-foo () ... )
   (ert 'test-foo)
   ...append `*ert*' contents to `*ert-multiple-independent-tests*'
)
</code>```

(Less to type if macro-fied)

This is obvious.  I was hoping that the "automated self-test" arguments of `ert' might accomplish something similar.

```<code>ert is an alias for ‘ert-run-tests-interactively’ in ‘ert.el’.

(ert SELECTOR &optional OUTPUT-BUFFER-NAME MESSAGE-FN)

Run the tests specified by SELECTOR and display the results in a buffer.

SELECTOR works as described in ‘ert-select-tests’.
OUTPUT-BUFFER-NAME and MESSAGE-FN should normally be nil; they
are used for automated self-tests and specify which buffer to use
and how to display message.
</code>```

Perfunctory investigation has so far yielded little.

I would love a better way, if only because it might have worked out the details of whether to do this in batch mode, etc.

Or if somebody has managed not just to concatenate the ert buffers from independent tests, but has managed to create a fused buffer that reports all concisely.

ContentLicense: CC BY-SA 4.0

Body:
---+ BRIEF

Q: if I have multiple, separate, independent calls to ert, can I arrange to concatenate the output of these tests in the same buffer?  With the calls to ert being made at different times?

(Without a centralized thingamajig that knows about these independent tests.)

E.g. if I have two (or more) tests, e.g. in a .emacs file

 (ert-deftest test1 ()(should t))
 (ert 'test1)

 ... many miles away, quite likely in a separate file ...

 (ert-deftest test2 ()(should t))
 (ert 'test2)

Both will run - I can tell this by looking at *Messages*

...
Running 1 tests (2017-07-07 12:10:39-0700)
   passed  1/1  test_ag_non-null_and_true
...
Running 1 tests (2017-07-07 12:10:39-0700)
   passed  1/1  test-ag-code-disabling
...

But the *ert* buffer will only contain output for the last test run.

---+ DETAIL

---++ MOTIVATION

Q: Why do I want to do this?

A: "inline testing". In particular, inline testing of stuff in my .emacs file (and in files it loads and/or requires).

Tests that are run every time .emacs or similar file is loaded.  (There may be other tests that I run in batch mode - but here I am talking about tests that I want to run right away, every time .emacs is loaded (and convenient for edit/debug while modifying .emacs).

I.e. I am looking for an idiom for inline tests.

I have been putting code in my .emacs and ~/lib/gnu-emacs/**.el files that looks like this:

;; some blob of code
(defun foo (arg) ... )

(ert-deftest test-foo () ... )
(ert 'test-foo)

i.e. I define the function, the test, and run the test, right next to each other.

... I might as well admit that I often wrap a `progn' around,

(progn
   ;; some blob of code
   (defun foo (arg) ... )
   (ert-deftest test-foo () ... )
   (ert 'test-foo)
)

because this makes it easy to make an edit to function foo or the test, and then jump to the end of the progn and do eval-last-sexp (which I have bound to C-j).  And I often also wrap an if or and and around, to make it easy to disable a feature that is in development. Sometimes with let* in then mix, if the feature has variables.

(I have used other ert- family runners, like ert-run-tests-batch and ert-run-tests-interactively. But plain old ert seems enough.)

(Putting defun and deftest inside a progn or other breaks some tools that expect defun to always be at top level. And it makes multiline docstrings even uglier. But it is darn convenient, and IMHO tools that operate on programming language files should parse the programming language.)

So, later, I will do the same thing for another module. Far away. Possibly in a separate file, possibly a library file.

(progn
   ;; some blob of code
   (defun bar (arg) ... )
   (ert-deftest test-bar () ... )
   (ert 'test-bar)
)

Neither module should know about the other.

Nor should there be a centralized module that has a list of all such tests, that get run at the end.

If only because there may be a failure partway through loading the file. And it is convenient to know what tests up to that point passed or failed.

(Whereas collecting and running all tests at the end loses that incremental test running ability.)

---++ Should be a macro

I hate repetition. E.g. in the stuff below, I hate having to type BAR three times.

(progn
   ;; some blob of code
   (defun BAR (arg) ... )
   (ert-deftest test-BAR () ... )
   (ert 'test-BAR)
)

Therefore, of course I will create a macro that reduces this repetition. Although then folks looking for the ert-deftest will get confused...

---++ MEDIUM LENGTH SIMPLE EXAMPLE

If I have

  (ert-deftest test1 ()(should t))
  (ert 'test1)

I will get a nice *ert* buffer

Selector: test1
Passed:  1
Failed:  0
Skipped: 0
Total:   1/1

Started at:   2017-07-07 14:16:06-0700
Finished.
Finished at:  2017-07-07 14:16:07-0700

.

and if later I have

(ert-deftest test2 () (should t))
(ert 'test2)

It will erase the output of test1 in the *ert* buffer, and replace it with

Selector: test2
Passed:  1
Failed:  0
Skipped: 0
Total:   1/1

Started at:   2017-07-07 14:15:47-0700
Finished.
Finished at:  2017-07-07 14:15:47-0700

.

What I would like is to have the output of both tests concatenated:

Selector: test1
Passed:  1
Failed:  0
Skipped: 0
Total:   1/1

Started at:   2017-07-07 14:16:06-0700
Finished.
Finished at:  2017-07-07 14:16:07-0700

.

Selector: test2
Passed:  1
Failed:  0
Skipped: 0
Total:   1/1

Started at:   2017-07-07 14:15:47-0700
Finished.
Finished at:  2017-07-07 14:15:47-0700

.

Body:
As so often happens, the act of posting the question suggests the answer.

Although it is somewhat ugly, and certainly non-standard.  So if anyone posts a concise standard-ish way, I will accept such an answer.

The IMHO ugly way:

When I do

(progn
   ;; some blob of code
   (defun foo (arg) ... )
   (ert-deftest test-foo () ... )
   (ert 'test-foo)
)

I can add more code to manipulate the ert output buffer:

(progn
   ;; some blob of code
   (defun foo (arg) ... )
   (ert-deftest test-foo () ... )
   (ert 'test-foo)
   ...append `*ert*' contents to `*ert-multiple-independent-tests*'
)

(Less to type if macro-fied)

This is obvious.  I was hoping that the "automated self-test" arguments of `ert' might accomplish something similar.

ert is an alias for ‘ert-run-tests-interactively’ in ‘ert.el’.

(ert SELECTOR &optional OUTPUT-BUFFER-NAME MESSAGE-FN)

Run the tests specified by SELECTOR and display the results in a buffer.

SELECTOR works as described in ‘ert-select-tests’.
OUTPUT-BUFFER-NAME and MESSAGE-FN should normally be nil; they
are used for automated self-tests and specify which buffer to use
and how to display message.

Perfunctory investigation has so far yielded little.

I would love a better way, if only because it might have worked out the details of whether to do this in batch mode, etc.

Or if somebody has managed not just to concatenate the ert buffers from independent tests, but has managed to create a fused buffer that reports all concisely.


问:
samy Query display different rows in different server
executing same query in different server (both server are having same records)
please check query below

```<code>SELECT  id,NAME,parent_id
FROM
(SELECT * FROM projects
ORDER BY parent_id) AS res,
(SELECT @pv := '944')AS res_b
WHERE   FIND_IN_SET(parent_id, @pv)
AND     @pv := CONCAT(@pv, ',', id)
</code>```

Result in my local

return 45 rows

Result in my server

return 42 rows

in my local using innoDB but in server mariaDB.please help me to slove this issue.

答:
A subquery returns an unordered set of rows, in spite of the ORDER BY.  That's the standard.

You can perhaps trick it by adding LIMIT 99999999 after the ORDER BY parent_id.

Body:
executing same query in different server (both server are having same records)
please check query below

SELECT  id,NAME,parent_id
FROM
(SELECT * FROM projects
ORDER BY parent_id) AS res,
(SELECT @pv := '944')AS res_b
WHERE   FIND_IN_SET(parent_id, @pv)
AND     @pv := CONCAT(@pv, ',', id)

Result in my local

return 45 rows

Result in my server

return 42 rows

in my local using innoDB but in server mariaDB.please help me to slove this issue.


问:
How do you load specific columns formatted in parquet into Redshift spectrum?
I'm trying to load specific columns into Redshift Spectrum, but it appears that the data is being loaded positionally, which means it doesn't matter what I put for the column names.

To make this more concrete:

Let's say the data I want to load is stored positionally in parquet as columns A, B, C. I only want column B, so I write:

```<code>create external table spectrum.Foo(
  B varchar(500)
)
STORED AS PARQUET
LOCATION 's3://data/';
</code>```

Unfortunately, when I do that, it actually loads the data of A into Foo.B

Is there some extra syntax I need. I scoured the documentation but couldn't find anything.

Thanks!

答:
Defining the external table does not load data into Redshift -- it simply enables you to query it. If you want to ingest only a subset of the columns you can try the following set of queries:

```<code>create external table spectrum.Foo(
  A varchar(100), B varchar(100), C varchar(100)
) stored as parquet location 's3://data/';
</code>```

This defines the external schema:

```<code>create table local_data as select A, C from spectrum.Foo;
</code>```

This will essentially load only the specified columns from the external table into a local table in Redshift. However, you don't need to do that: The advantage of Redshift Spectrum and Parquet is that when you run the query:

```<code>select A, C from spectrum.Foo;
</code>```

it will only load the data from S3 for the accessed columns, reducing the number of IO operations to S3 and reducing the cost.

Body:
I'm trying to load specific columns into Redshift Spectrum, but it appears that the data is being loaded positionally, which means it doesn't matter what I put for the column names.

To make this more concrete:

Let's say the data I want to load is stored positionally in parquet as columns A, B, C. I only want column B, so I write:

create external table spectrum.Foo(
  B varchar(500)
)
STORED AS PARQUET
LOCATION 's3://data/';

Unfortunately, when I do that, it actually loads the data of A into Foo.B

Is there some extra syntax I need. I scoured the documentation but couldn't find anything.

Thanks!

Body:
Defining the external table does not load data into Redshift -- it simply enables you to query it. If you want to ingest only a subset of the columns you can try the following set of queries:

create external table spectrum.Foo(
  A varchar(100), B varchar(100), C varchar(100)
) stored as parquet location 's3://data/';

This defines the external schema:

create table local_data as select A, C from spectrum.Foo;

This will essentially load only the specified columns from the external table into a local table in Redshift. However, you don't need to do that: The advantage of Redshift Spectrum and Parquet is that when you run the query:

select A, C from spectrum.Foo;

it will only load the data from S3 for the accessed columns, reducing the number of IO operations to S3 and reducing the cost.


问:
Unable to get correct output from tsv file using pandas
I have a tsv file which I am trying to read by the help of pandas. The first two rows of the files are of no use and needs to be ignored. Although, when I get the output, I get it in the form of two columns. The name of the first column is Index and the name of second column is a random row from the csv file.

```<code>import pandas as pd

data = pd.read_csv('zahlen.csv', sep='\t', skiprows=2)
</code>```

Please refer to the screenshot below.

The second column name is in bold black, which is one of the row from the file. Moreover, using '\t' as delimiter does not separate the values in different column. I am using Spyder IDE for this. Am I doing something wrong here?

答:
Try this:

```<code>data = pd.read_table('zahlen.csv', header=None, skiprows=2)
</code>```

read_table() is more suited for tsv files and read_csv() is a more specialized version of it. Then header=None will make first row data, instead of header.

Body:
I have a tsv file which I am trying to read by the help of pandas. The first two rows of the files are of no use and needs to be ignored. Although, when I get the output, I get it in the form of two columns. The name of the first column is Index and the name of second column is a random row from the csv file.

import pandas as pd

data = pd.read_csv('zahlen.csv', sep='\t', skiprows=2)

Please refer to the screenshot below.

The second column name is in bold black, which is one of the row from the file. Moreover, using '\t' as delimiter does not separate the values in different column. I am using Spyder IDE for this. Am I doing something wrong here?

Body:
Try this:

data = pd.read_table('zahlen.csv', header=None, skiprows=2)

read_table() is more suited for tsv files and read_csv() is a more specialized version of it. Then header=None will make first row data, instead of header.


问:
blank file created by program
The program runs in a loop and generates file for the no of records listed in  info list. But for the last record in that list it's generating a blank file. The final_list is never blank, i check that but still every time the last file which is being created is empty. Can someone please tell what i did wrong? </p>

```<code>outputC = net_connect.send_command("show int desc | i xe")
outputC1 = net_connect.send_command("show int desc | i xt")
final_list = capture_op(outputC,outputC1)
length = len(info[count][1])
name = info[count][1]
name = name[0:length]+".txt"
for path,dirname,filename in os.walk("."):
    for file in filename:
        if file == name:
            os.remove(name)
            break
fo=open(name , 'w')
for i in final_list:
    print (i)
    fo.write(i)
    fo.write('\n')
fo.close
count+=1
</code>```

答:
As DeepSpace suggested you should really always use with open()

```<code>with open(name, 'w') as fo:

    for i in final_list:
        print (i)
        fo.write(i)
        fo.write('\n')
count+=1
</code>```

Python Reference:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

Title: blank file created by program

Body:
The program runs in a loop and generates file for the no of records listed in  info list. But for the last record in that list it's generating a blank file. The final_list is never blank, i check that but still every time the last file which is being created is empty. Can someone please tell what i did wrong?

outputC = net_connect.send_command("show int desc | i xe")
outputC1 = net_connect.send_command("show int desc | i xt")
final_list = capture_op(outputC,outputC1)
length = len(info[count][1])
name = info[count][1]
name = name[0:length]+".txt"
for path,dirname,filename in os.walk("."):
    for file in filename:
        if file == name:
            os.remove(name)
            break
fo=open(name , 'w')
for i in final_list:
    print (i)
    fo.write(i)
    fo.write('\n')
fo.close
count+=1

Body:
As DeepSpace suggested you should really always use with open()

with open(name, 'w') as fo:

    for i in final_list:
        print (i)
        fo.write(i)
        fo.write('\n')
count+=1

Python Reference:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files


问:
Calling MySQL Arithmetic Operators in one function?
I have been trying to make and call all MySQL Arithmetic Operators ( +, -, /, *) in one function, but I'm facing one problem with the parameter m1. I'm getting an error message that is saying:

```<code>Syntax error: unexpected 'm1' (Identifier)?
</code>```

I already declared it as a numeric, and it is still showing me the same error. Does anyone have any idea how to solve it and run this function successfully on MySQL Workbench 5.7

This is the code, and the error is in the 5th line:

```<code>CREATE FUNCTION `Calculator`

(m1 numeric (10,4), m2 numeric (10,4), m3  numeric (10,4), s  varchar (20))

RETURNS INTEGER

BEGIN

m1:=&m1

m2:=&m2

s:=&s

if s = '+' then

m3:=m1+m2

dbms_output.put_line(m1||s||m2||'='||m3)

else if s = '-' then

m3:=m1-m2

dbms_output.put_line(m1||s||m2||'='||m3)

else if s = '*' then

m3:=m1*m2

dbms_output.put_line(m1||s||m2||'='||m3)

else if s = '/' then

m3:=m1/m2

dbms_output.put_line(m1||s||m2||'='||m3);

end if

  exception

  when zero_divide then

  dbms_output.put_line('cant divide by zero')

end

/

RETURN 1;
END
</code>```

答:
You have multiple cases of trying to use Oracle database syntax in your code.

Oracle and MySQL are two different products, and you can't use the same syntax for both.

In MySQL:

You must use SET to do assignment statements. https://dev.mysql.com/doc/refman/5.7/en/set-variable.html

You don't need := where = would be sufficient to do an assignment in MySQL. It does no harm, but it's another clue that you're trying to use Oracle syntax.

exception is Oracle syntax, not MySQL. You might have meant to use SIGNAL to throw an exception in MySQL. https://dev.mysql.com/doc/refman/5.7/en/signal.html

dbms_output.put_line() is for Oracle database, not MySQL (https://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_output.htm). You can't write output inside a MySQL function.

You should study MySQL syntax before you go any further.

Body:
I have been trying to make and call all MySQL Arithmetic Operators ( +, -, /, *) in one function, but I'm facing one problem with the parameter m1. I'm getting an error message that is saying:

Syntax error: unexpected 'm1' (Identifier)?

I already declared it as a numeric, and it is still showing me the same error. Does anyone have any idea how to solve it and run this function successfully on MySQL Workbench 5.7

This is the code, and the error is in the 5th line:

CREATE FUNCTION `Calculator`

(m1 numeric (10,4), m2 numeric (10,4), m3  numeric (10,4), s  varchar (20))

RETURNS INTEGER

BEGIN

m1:=&m1

m2:=&m2

s:=&s

if s = '+' then

m3:=m1+m2

dbms_output.put_line(m1||s||m2||'='||m3)

else if s = '-' then

m3:=m1-m2

dbms_output.put_line(m1||s||m2||'='||m3)

else if s = '*' then

m3:=m1*m2

dbms_output.put_line(m1||s||m2||'='||m3)

else if s = '/' then

m3:=m1/m2

dbms_output.put_line(m1||s||m2||'='||m3);

end if

  exception

  when zero_divide then

  dbms_output.put_line('cant divide by zero')

end

/

RETURN 1;
END


问:
Efficient way of merging data frames on custom conditions
Below are the below data frames i have esh -> earnings surprise history
and sph-> stock price history.

earnings surprise history

```<code>    ticker   reported_date reported_time_code  eps_actual
0    ABC     2017-10-05       AMC                1.01
1    ABC     2017-07-04       BMO                0.91
2    ABC     2017-03-03       BMO                1.08
3    ABC     2016-10-02       AMC                0.5
</code>```

stock price history

```<code>    ticker       date    adj_open   ad_close
0    ABC     2017-10-06   12.10      13.11
1    ABC     2017-12-05   11.11      11.87
2    ABC     2017-12-04   12.08      11.40
3    ABC     2017-12-03   12.01      13.03
..
101  ABC     2017-07-04   9.01        9.59
102  ABC     2017-07-03   7.89        8.19
</code>```

I like to build a new dataframe by merging two datasets which shall have the following columns as shown below and also if the reported_time_code from the earnings surprise history is AMC  then the record to be referred from stock price history should be the next day.if the reported_time_code is BM0  then record to be referred from stock price history should be the same day. if i used straight merge function on the actual_reported column of esh and data column of sph it will break the above conditions. looking for efficient way of transforming the data

Here is the resultant transformed data set

```<code>    ticker       date     adj_open   ad_close  eps_actual
0    ABC     2017-10-06    12.10      13.11      1.01
101  ABC     2017-07-04    9.01        9.59      0.91
</code>```

答:
It is it is great that your offset is only one day. Then you can do something like the following:</p>

```<code>mask = esh['reported_time_code'] == 'AMC'
# The mask is basically an array of 0 and 1's \
  all we have to do is to convert them into timedelta objects standing for \
  the number of days to offset

offset = mask.values.astype('timedelta64[D]')
# The D inside the bracket stands for the unit of time to which \
  you want to attach your number. In this case, we want [D]ays.

esh['date'] = esh['reported_date'] + offset
esh.merge(sph, on=['ticker', 'date']).drop(['reported_date', 'reported_time_code'], \
                                           axis=1, inplace=True)
</code>```

Body:
Below are the below data frames i have esh -> earnings surprise history
and sph-> stock price history.

earnings surprise history

    ticker   reported_date reported_time_code  eps_actual
0    ABC     2017-10-05       AMC                1.01
1    ABC     2017-07-04       BMO                0.91
2    ABC     2017-03-03       BMO                1.08
3    ABC     2016-10-02       AMC                0.5

stock price history

    ticker       date    adj_open   ad_close
0    ABC     2017-10-06   12.10      13.11
1    ABC     2017-12-05   11.11      11.87
2    ABC     2017-12-04   12.08      11.40
3    ABC     2017-12-03   12.01      13.03
..
101  ABC     2017-07-04   9.01        9.59
102  ABC     2017-07-03   7.89        8.19

I like to build a new dataframe by merging two datasets which shall have the following columns as shown below and also if the reported_time_code from the earnings surprise history is AMC  then the record to be referred from stock price history should be the next day.if the reported_time_code is BM0  then record to be referred from stock price history should be the same day. if i used straight merge function on the actual_reported column of esh and data column of sph it will break the above conditions. looking for efficient way of transforming the data

Here is the resultant transformed data set

    ticker       date     adj_open   ad_close  eps_actual
0    ABC     2017-10-06    12.10      13.11      1.01
101  ABC     2017-07-04    9.01        9.59      0.91

Body:
It is it is great that your offset is only one day. Then you can do something like the following:

mask = esh['reported_time_code'] == 'AMC'
# The mask is basically an array of 0 and 1's \
  all we have to do is to convert them into timedelta objects standing for \
  the number of days to offset

offset = mask.values.astype('timedelta64[D]')
# The D inside the bracket stands for the unit of time to which \
  you want to attach your number. In this case, we want [D]ays.

esh['date'] = esh['reported_date'] + offset
esh.merge(sph, on=['ticker', 'date']).drop(['reported_date', 'reported_time_code'], \
                                           axis=1, inplace=True)


问:
How can I convert a date from the format "dd/mm/yyyy" to "yyyy/dd/mm"?
I have a Textbox in which the user is supposed to enter a date in the format dd/mm/yyyy, this date is stored as yyyy/mm/dd in the database.

So I want the user to enter the date in dd/mm/yyyy format and later I want to convert to yyyy/mm/dd so that I can query database.

How can I convert the user input date dd/mm/yyyy to yyyy/mm/dd?

答:
I would have a look at

DateTime.TryParseExact Method

and

DateTime.ToString Method  Somthing like dateTimeval.ToString("yyyy/MM/dd");

```<code>string dateString = "30/01/2010";
DateTime dateTimeVal;
if (DateTime.TryParseExact(dateString,"dd/MM/yyyy", null,DateTimeStyles.None,out dateTimeVal))
{
    string newFormat = dateTimeVal.ToString("yyyy/MM/dd");
}
</code>```

Body:
I would have a look at

DateTime.TryParseExact Method

and

DateTime.ToString Method  Somthing like dateTimeval.ToString("yyyy/MM/dd");

string dateString = "30/01/2010";
DateTime dateTimeVal;
if (DateTime.TryParseExact(dateString,"dd/MM/yyyy", null,DateTimeStyles.None,out dateTimeVal))
{
    string newFormat = dateTimeVal.ToString("yyyy/MM/dd");
}


问:
How to split string in ruby
I have a string:

```<code>"1 chocolate bar at 25"
</code>```

and I want to split this string into:

```<code> [1, "chocolate bar", 25]
</code>```

I don't know how to write a regex for this split. And I wanted to know whether there are any other functions to accomplish it.

答:
I would do:

```<code>> s="1 chocolate bar at 25"
> s.scan(/[\d ]+|[[:alpha:] ]+/)
=> ["1 ", "chocolate bar at ", "25"]
</code>```

Then to get the integers and the stripped string:

```<code>> s.scan(/[\d ]+|[[:alpha:] ]+/).map {|s| Integer(s) rescue s.strip}
=> [1, "chocolate bar at", 25]
</code>```

And to remove the " at":

```<code>> s.scan(/[\d ]+|[[:alpha:] ]+/).map {|s| Integer(s) rescue s[/.*(?=\s+at\s*)/]}
=> [1, "chocolate bar", 25]
</code>```

Title: How to split string in ruby

Body:
I have a string:

"1 chocolate bar at 25"

and I want to split this string into:

 [1, "chocolate bar", 25]

I don't know how to write a regex for this split. And I wanted to know whether there are any other functions to accomplish it.

Body:
I would do:

> s="1 chocolate bar at 25"
> s.scan(/[\d ]+|[[:alpha:] ]+/)
=> ["1 ", "chocolate bar at ", "25"]

Then to get the integers and the stripped string:

> s.scan(/[\d ]+|[[:alpha:] ]+/).map {|s| Integer(s) rescue s.strip}
=> [1, "chocolate bar at", 25]

And to remove the " at":

> s.scan(/[\d ]+|[[:alpha:] ]+/).map {|s| Integer(s) rescue s[/.*(?=\s+at\s*)/]}
=> [1, "chocolate bar", 25]


问:
Build React app as modular JS library

Background

I have a React app that was generated with create-react-app.
It is a set of UI forms that are intended to be presented modally inside a hosting website. The hosting website provides a JS callback to be invoked upon completion.

Motivation

I want to be able to distribute this small React app as a standalone "vanilla" JS module, that can then embedded in any HTML page.
What I have now is running npm run build and getting a full website with my app - but that's not what I need. A desirable output should be a simple .js file, that can be imported to a other's websites (that are not necessarily built with React). Braintree's JS SDK is a very good example of what I need.

Example usage in hosting website

```<code><head>
    <!-- loading MyModule -->
    <script src='https://cdn.mydomain.com/mymodule.js' some-parameter='param-provided-by-hosting-website'></script>
</head>

<body>
    <div id="mymodule-container"></div>

    <!-- rest of hosting website... -->

    <script>
        // this will present a "full screen" UI component and call callback upon completion
        MyModule.presentUI(
            function callback() {
                console.log('MyModule completed');
            }
        );
    </script>
</body>
</code>```

Putting aside all of the internal structure and consideration, how do I bundle my React app (including its .css files) as one .js file that runs inside another website?

UPDATE

So apparently running npm run build outputs, among other things, a static/main*****.js file, which is all of the JS contents. The index.html file is actually a good example of how to use that .js file as a module:

```<code><!DOCTYPE html><html lang="en">
<head>
    <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="shortcut icon" href="/favicon.ico">
    <title>My Hosting App</title>
    <link href="/static/css/main.1695e3be.css" rel="stylesheet">
</head>
<body>
    <div id="my-module-container"></div><script type="text/javascript" src="/static/js/main.0b4c7736.js"></script>
</body></html>
</code>```

Now what's left to ask is how to load the .css (from built-generated static/main******.css file with the .js file, without making the hosting website also add a <link> tag to the RSS (like in the output index.html. Basically making this happen inside the generated .js file.

Title: Build React app as modular JS library

Body:
Background

I have a React app that was generated with create-react-app.
It is a set of UI forms that are intended to be presented modally inside a hosting website. The hosting website provides a JS callback to be invoked upon completion.

Motivation

I want to be able to distribute this small React app as a standalone "vanilla" JS module, that can then embedded in any HTML page.
What I have now is running npm run build and getting a full website with my app - but that's not what I need. A desirable output should be a simple .js file, that can be imported to a other's websites (that are not necessarily built with React). Braintree's JS SDK is a very good example of what I need.

Example usage in hosting website

Putting aside all of the internal structure and consideration, how do I bundle my React app (including its .css files) as one .js file that runs inside another website?

UPDATE

So apparently running npm run build outputs, among other things, a static/main*****.js file, which is all of the JS contents. The index.html file is actually a good example of how to use that .js file as a module:

<!DOCTYPE html>

    <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="shortcut icon" href="/favicon.ico">
    <title>My Hosting App</title>
    <link href="/static/css/main.1695e3be.css" rel="stylesheet">

Now what's left to ask is how to load the .css (from built-generated static/main******.css file with the .js file, without making the hosting website also add a <link> tag to the RSS (like in the output index.html. Basically making this happen inside the generated .js file.

Body:
I cannot say how this can be achieved without having some sort of 'standard' API, that all your modules can follow.

We have tried to do something similar with FrintJS (https://frint.js.org), with the concept of 'regions'.

You define certain areas where you want your Apps (modules according to your question) to mount themselves on, and they can be loaded asynchronously on demand via separate <script> tags.

You can read more here:

https://frint.js.org/guides/regions/

https://frint.js.org/guides/code-splitting/


问:
How to replace extra spaces in text file with comma in linux
my text file has 3 or more than 3 spaces, now I want to replace the 3 or more than 3 spaces with a comma and it should not replace if the file has less than 3 spaces</p>

```<code>ex:
input:
a b  3   c     d      6        9
output:
a b,3,c,d,6,9
</code>```

答:
You can do it easily with sed:

```<code>$ sed -r 's/ {3,}/,/g' file
a b  3,c,d,6,9
</code>```

The -r flag instructs the sed to use the extended regular expression syntax which we need for the {min,max} interval operator in the s/// search/replace command. With it we say: for each occurrence (note the g, or global flag in the end) of the space character which is repeated 3 or more times (no upper limit), replace it with ,. Pass through all other characters.

Body:
my text file has 3 or more than 3 spaces, now I want to replace the 3 or more than 3 spaces with a comma and it should not replace if the file has less than 3 spaces

ex:
input:
a b  3   c     d      6        9
output:
a b,3,c,d,6,9

Body:
You can do it easily with sed:

$ sed -r 's/ {3,}/,/g' file
a b  3,c,d,6,9

The -r flag instructs the sed to use the extended regular expression syntax which we need for the {min,max} interval operator in the s/// search/replace command. With it we say: for each occurrence (note the g, or global flag in the end) of the space character which is repeated 3 or more times (no upper limit), replace it with ,. Pass through all other characters.


问:
How get the items from an object that comes from another list with JSF
i have this entity Cliente, and have a relation OneToMany with Telefonos.

```<code>@Entity
public class Cliente implements Serializable {

  @Id
  @GeneratedValue(generator = "uuid")
  @Column(name = "id", unique = true)
  private String id;

  private String nombre;

  private String direccion;

  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "idTipoCliente")
  @NotNull
  private ClienteTipo tipo;

  @OneToMany
  @JoinColumn(name="idCliente", referencedColumnName="id")
  private List<Telefono> telefonos;

    public List<Telefono> getTelefonos() {
       return telefonos;
   }

public void setTelefonos(List<Telefono> telefonos) {
    this.telefonos = telefonos;
}

public Cliente() {
}

public Cliente(String id) {
    this.id = id;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getNombre() {
    return nombre;
}

public void setNombre(String nombre) {
    this.nombre = nombre;
}

public String getDireccion() {
    return direccion;
}

public void setDireccion(String direccion) {
    this.direccion = direccion;
}

public ClienteTipo getTipo() {
    return tipo;
}

public void setTipo(ClienteTipo tipo) {
    this.tipo = tipo;
}
}
</code>```

i get the items in my dataTable like this.

```<code> <html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:h="http://xmlns.jcp.org/jsf/html"
          xmlns:f="http://xmlns.jcp.org/jsf/core"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets">

    <h:head>
         <title>Catalogo de Clientes</title>
     </h:head>
<h:body>

    <label>Nombre:</label>
    <h:inputText value=""/>
    <h:dataTable value="${clientesView.getClientes()}" var="cliente">
        <h:column>
            <f:facet name="header">Nombre</f:facet>
           ${cliente.nombre}
        </h:column>
        <h:column>
            <f:facet name="header">Direccion</f:facet>
             ${cliente.direccion}
        </h:column>
        <h:column>
            <f:facet name="header">Tipo Cliente</f:facet>
             ${cliente.tipo.descripcion}
        </h:column>
    </h:dataTable>
</h:body>
</html>
</code>```

Each Cliente have a list of telefonos, how could i print it in the same column, i tried to create a new h:dataTable into the h:column but doesnt reconoize the list.

```<code>  <h:column>
            <f:facet name="header">Telefonos</f:facet>
            <h:dataTable value="${cliente.telefonos}" var="tel">

             <h:column>
                 <f:facet name="hader">Descripcion</f:facet>
                 ${tel.descripcion}
             </h:column>
            </h:dataTable>
             ${cliente.tipo.descripcion}
        </h:column>
</code>```

答:
The telephone entity must have the customer id
So:
You can have a post construct in the bean:

```<code>Private List <Telefono> phones; // getters & setters
@PostConstruct
Public void init () {
phones = // dao to get the phone list
}
public String sendPhone (String idClient) {
    for (Phone t: this.getPhones()) {
      If (t.idCliente.equals (idClient)) {
        return t.description // or phone
      }
    }
}
</code>```

The code xhtml:

```<code><h:dataTable value = "$ {clientsView.getCustomers()}" var = "client">
             <h:column>
                 <f:facet name = "header"> Phone</f:facet>
                $ {clientsView.sendPhone (client.id)}
             </h:column>
</h:datatable>
</code>```

Note:The telephone must belong to a customer through a relationship

Body:
i have this entity Cliente, and have a relation OneToMany with Telefonos.

@Entity
public class Cliente implements Serializable {

  @Id
  @GeneratedValue(generator = "uuid")
  @Column(name = "id", unique = true)
  private String id;

  private String nombre;

  private String direccion;

  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "idTipoCliente")
  @NotNull
  private ClienteTipo tipo;

  @OneToMany
  @JoinColumn(name="idCliente", referencedColumnName="id")
  private List<Telefono> telefonos;

    public List<Telefono> getTelefonos() {
       return telefonos;
   }

public void setTelefonos(List<Telefono> telefonos) {
    this.telefonos = telefonos;
}

public Cliente() {
}

public Cliente(String id) {
    this.id = id;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getNombre() {
    return nombre;
}

public void setNombre(String nombre) {
    this.nombre = nombre;
}

public String getDireccion() {
    return direccion;
}

public void setDireccion(String direccion) {
    this.direccion = direccion;
}

public ClienteTipo getTipo() {
    return tipo;
}

public void setTipo(ClienteTipo tipo) {
    this.tipo = tipo;
}
}

i get the items in my dataTable like this.

    <h:head>
         <title>Catalogo de Clientes</title>
     </h:head>
<h:body>

    Nombre:
    <h:inputText value=""/>
    <h:dataTable value="${clientesView.getClientes()}" var="cliente">
        <h:column>
            <f:facet name="header">Nombre</f:facet>
           ${cliente.nombre}
        </h:column>
        <h:column>
            <f:facet name="header">Direccion</f:facet>
             ${cliente.direccion}
        </h:column>
        <h:column>
            <f:facet name="header">Tipo Cliente</f:facet>
             ${cliente.tipo.descripcion}
        </h:column>
    </h:dataTable>
</h:body>

Each Cliente have a list of telefonos, how could i print it in the same column, i tried to create a new h:dataTable into the h:column but doesnt reconoize the list.

  <h:column>
            <f:facet name="header">Telefonos</f:facet>
            <h:dataTable value="${cliente.telefonos}" var="tel">

             <h:column>
                 <f:facet name="hader">Descripcion</f:facet>
                 ${tel.descripcion}
             </h:column>
            </h:dataTable>
             ${cliente.tipo.descripcion}
        </h:column>

Body:
The telephone entity must have the customer id
So:
You can have a post construct in the bean:

Private List <Telefono> phones; // getters & setters
@PostConstruct
Public void init () {
phones = // dao to get the phone list
}
public String sendPhone (String idClient) {
    for (Phone t: this.getPhones()) {
      If (t.idCliente.equals (idClient)) {
        return t.description // or phone
      }
    }
}

The code xhtml:

<h:dataTable value = "$ {clientsView.getCustomers()}" var = "client">
             <h:column>
                 <f:facet name = "header"> Phone</f:facet>
                $ {clientsView.sendPhone (client.id)}
             </h:column>
</h:datatable>

Note:The telephone must belong to a customer through a relationship


问:
Listener to map touch outside of the markers
I am using the google map api with some markers. I also overrode the infoWindow as below to show custom text.

```<code>public void setUpMap() {
    final GoogleMap map = mMapView.getMap();
    map.clear();
    map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
        private View mHolder;

        @Override
        public View getInfoWindow(final Marker marker) {
            Log.d("MAP", "Map clicked on marker = " + maker);
            etc....
</code>```

this works fine and I change the icon of each marker when clicked making them visually selected. However, I want to "unselect" all markers. The problem is that I don't know how to add a listener that gets triggered from outside of the markers.

In other words, my listener "getInfoWindow" gets trigger only when a marker is touched. I want the opposite. Some sort of listener that tells me that the user touched the map but not the markers.

Can this be done easily? Any pointers are greatly appreciated.

thx!

答:
This is useful only when working with the Info Window.
In my case, when the user clicks the marker, the corresponding Info window appears. So when the user clicks in the map outside the marker, the Info Window closes and that event is detected by the map.

```<code>// Detect when Marker's Info Window is closed
    googleMap.setOnInfoWindowCloseListener(new GoogleMap.OnInfoWindowCloseListener() {
        @Override
        public void onInfoWindowClose(Marker marker) {
            // Do whatever you want to do here...
        }
    });
</code>```

Body:
I am using the google map api with some markers. I also overrode the infoWindow as below to show custom text.

public void setUpMap() {
    final GoogleMap map = mMapView.getMap();
    map.clear();
    map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
        private View mHolder;

        @Override
        public View getInfoWindow(final Marker marker) {
            Log.d("MAP", "Map clicked on marker = " + maker);
            etc....

this works fine and I change the icon of each marker when clicked making them visually selected. However, I want to "unselect" all markers. The problem is that I don't know how to add a listener that gets triggered from outside of the markers.

In other words, my listener "getInfoWindow" gets trigger only when a marker is touched. I want the opposite. Some sort of listener that tells me that the user touched the map but not the markers.

Can this be done easily? Any pointers are greatly appreciated.

thx!

Body:
This is useful only when working with the Info Window.
In my case, when the user clicks the marker, the corresponding Info window appears. So when the user clicks in the map outside the marker, the Info Window closes and that event is detected by the map.

// Detect when Marker's Info Window is closed
    googleMap.setOnInfoWindowCloseListener(new GoogleMap.OnInfoWindowCloseListener() {
        @Override
        public void onInfoWindowClose(Marker marker) {
            // Do whatever you want to do here...
        }
    });


问:
Update unique table SQL
Hello i have this table.

```<code>ADDR      | STATE  |  ID
CRA.20 15 |  REP   |  (null)
CRA.20 15 |  REP   |  (null)
CRA.20 15 |  REP   |   (null)
CRA.20 15 |  PRI   |   RR_88_JK
</code>```

I need transform this table ..

```<code>ADDR      | STATE |   ID
CRA.20 15 |  REP  |   RR_88_JK
CRA.20 15 |  REP  |   RR_88_JK
CRA.20 15 |  REP  |   RR_88_JK
CRA.20 15 |  PRI  |   RR_88_JK
</code>```

I have this QRY but not function. You have a one idea?.

```<code>UPDATE TABLE_A A
   SET a.ID = b.ID
 WHERE EXISTS
           (SELECT b.ID
              FROM TABLE_A B
             WHERE a.ADDR = B.ADDR  AND b.STATE = 'PRI')
 and  A.STATE = 'REP';
</code>```

Thanks.

答:
You need a subquery to set the value:

```<code>UPDATE TABLE_A A
   SET a.ID = (SELECT b.ID
               FROM TABLE_A B
               WHERE a.ADDR = B.ADDR AND b.STATE = 'PRI' AND rownum = 1
              )
   WHERE EXISTS (SELECT b.ID
                 FROM TABLE_A B
                 WHERE a.ADDR = B.ADDR AND b.STATE = 'PRI'
                ) AND
         A.STATE = 'REP';
</code>```

B is only known in the subquery, not in the outer query.

Title: Update unique table SQL

Body:
Hello i have this table.

ADDR      | STATE  |  ID
CRA.20 15 |  REP   |  (null)
CRA.20 15 |  REP   |  (null)
CRA.20 15 |  REP   |   (null)
CRA.20 15 |  PRI   |   RR_88_JK

I need transform this table ..

ADDR      | STATE |   ID
CRA.20 15 |  REP  |   RR_88_JK
CRA.20 15 |  REP  |   RR_88_JK
CRA.20 15 |  REP  |   RR_88_JK
CRA.20 15 |  PRI  |   RR_88_JK

I have this QRY but not function. You have a one idea?.

UPDATE TABLE_A A
   SET a.ID = b.ID
 WHERE EXISTS
           (SELECT b.ID
              FROM TABLE_A B
             WHERE a.ADDR = B.ADDR  AND b.STATE = 'PRI')
 and  A.STATE = 'REP';

Thanks.

Body:
You need a subquery to set the value:

UPDATE TABLE_A A
   SET a.ID = (SELECT b.ID
               FROM TABLE_A B
               WHERE a.ADDR = B.ADDR AND b.STATE = 'PRI' AND rownum = 1
              )
   WHERE EXISTS (SELECT b.ID
                 FROM TABLE_A B
                 WHERE a.ADDR = B.ADDR AND b.STATE = 'PRI'
                ) AND
         A.STATE = 'REP';

B is only known in the subquery, not in the outer query.


问:
How do I use third party JS modules in my Angular project?
I'm currently working on an Angular (Angular 4.2.5) project and have been able to add a few third party modules. However, in most cases, if the third party module required me to include a script (like a .js file), I had to add it to my index.html file.

For example, this is what is in my index.html for Bootstrap:

```<code><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</code>```

This was also the case for my CSS files but recently found that I could import them into my style.css. Here's an example of what exists in that file for bootstrap as well:

```<code>@import '~bootstrap/dist/css/bootstrap.min.css';
</code>```

Now when I look online, I see that I should be able to add the path to the script in question to my angular-cli.json file but every time I have done that, the third party component fails. Only when I add the [script] tag for that component into index.html does it work.

I've tried several online guides but none seem to work. I'm certain I'm missing some minor setting somewhere to ensure that I'm using the angular-cli.json path listed but I can't seem to find it.

Some details in the event you need it:

@angular/cli: 1.2.0

node: 6.10.0

os: win32 x64

@angular/animations: 4.2.5

@angular/common: 4.2.5

@angular/compiler: 4.2.5

@angular/core: 4.2.5

@angular/forms: 4.2.5

@angular/http: 4.2.5

@angular/material: 2.0.0-beta.7

@angular/platform-browser: 4.2.5

@angular/platform-browser-dynamic: 4.2.5

@angular/router: 4.2.5

@angular/compiler-cli: 4.2.5

[Edit 07/08/2017]
To be clear, I do have the following in my angular-cli.json but it still doesn't work unless I have it included in my index.html.

```<code>"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.json",
      "prefix": "ang2-crm",
      "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.css",
        "../node_modules/font-awesome/css/font-awesome.css",
        "styles.css"
      ],
      "scripts": [
        "../node_modules/bootstrap/dist/bootstrap.min.js"
      ],
      "environments": {
        "source": "environments/environment.ts",
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
</code>```

答:
You can add all scripts in scripts array in .angular-cli.jaon and css files in styles array.

For example if you want to add jquery.min.js.:-

Install jquery package by npm install jquery --save

Then add entry in scripts array as:-

scripts:[../node-modules/jquery/dist/jquery.min.js]

Body:
I'm currently working on an Angular (Angular 4.2.5) project and have been able to add a few third party modules. However, in most cases, if the third party module required me to include a script (like a .js file), I had to add it to my index.html file.

For example, this is what is in my index.html for Bootstrap:

This was also the case for my CSS files but recently found that I could import them into my style.css. Here's an example of what exists in that file for bootstrap as well:

@import '~bootstrap/dist/css/bootstrap.min.css';

Now when I look online, I see that I should be able to add the path to the script in question to my angular-cli.json file but every time I have done that, the third party component fails. Only when I add the [script] tag for that component into index.html does it work.

I've tried several online guides but none seem to work. I'm certain I'm missing some minor setting somewhere to ensure that I'm using the angular-cli.json path listed but I can't seem to find it.

Some details in the event you need it:

@angular/cli: 1.2.0

node: 6.10.0

os: win32 x64

@angular/animations: 4.2.5

@angular/common: 4.2.5

@angular/compiler: 4.2.5

@angular/core: 4.2.5

@angular/forms: 4.2.5

@angular/http: 4.2.5

@angular/material: 2.0.0-beta.7

@angular/platform-browser: 4.2.5

@angular/platform-browser-dynamic: 4.2.5

@angular/router: 4.2.5

@angular/compiler-cli: 4.2.5

[Edit 07/08/2017]
To be clear, I do have the following in my angular-cli.json but it still doesn't work unless I have it included in my index.html.

"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.json",
      "prefix": "ang2-crm",
      "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.css",
        "../node_modules/font-awesome/css/font-awesome.css",
        "styles.css"
      ],
      "scripts": [
        "../node_modules/bootstrap/dist/bootstrap.min.js"
      ],
      "environments": {
        "source": "environments/environment.ts",
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],


问:
Build React Components Incrementally based on conditions
I have an array of objects prjLvlData. This array contains information that I use to conditionally render a component.

In my .jsx file I have

```<code>{
  prjLvlData.map(ele => {

    if (ele.fields.level_exp === 'portfolio' && ele.fields.has_experience) {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn active" id={`btnPortfolio${id}`}>Portfolio</div>
    } else {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn" id={`btnPortfolio${id}`}>Portfolio</div>
    }
    if (ele.fields.level_exp === 'program' && ele.fields.has_experience) {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn active" id={`btnProgram{id}`}>Program</div>
    } else {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn " id={`btnProgram{id}`}>Program</div>
    }
    if (ele.fields.level_exp === 'project' && ele.fields.has_experience) {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn active" id={`btnProject${id}`}>Project</div>
    } else {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn" id={`btnProject${id}`}>Project</div>
    }
  })
}
</code>```

How can I build them so that by the end of the 3 if statements, I return the built-up component, instead of returning inside every if statement?

I want something like this, in pseudo code

```<code>var component = <div>

if (...)
  component += thing1
if (...)
  component += thing2

return component + <div>
</code>```

答:
You can use switch statement to calculate detect needed title and then use just one return statement:</p>

```<code>{prjLvlData.map(ele => {
    const active = ele.fields.has_experience ? 'active' : '';
    let title = '';

    switch (ele.fields.level_exp) {
        case 'portfolio':
            title = 'Portfolio';
            break;

        case 'program':
            title = 'Program';
            break;

        case 'project':
            title = 'Project';
            break;
    }

    return <div className={`btn btnAddBadge button noCursor projectLevelBtn ${active}`} id={`btnProject${id}`}>{title}</div>;
})}
</code>```

Body:
I have an array of objects prjLvlData. This array contains information that I use to conditionally render a component.

In my .jsx file I have

{
  prjLvlData.map(ele => {

    if (ele.fields.level_exp === 'portfolio' && ele.fields.has_experience) {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn active" id={`btnPortfolio${id}`}>Portfolio

    } else {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn" id={`btnPortfolio${id}`}>Portfolio

    }
    if (ele.fields.level_exp === 'program' && ele.fields.has_experience) {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn active" id={`btnProgram{id}`}>Program

    } else {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn " id={`btnProgram{id}`}>Program

    }
    if (ele.fields.level_exp === 'project' && ele.fields.has_experience) {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn active" id={`btnProject${id}`}>Project

    } else {
      return <div className="btn btnAddBadge button noCursor projectLevelBtn" id={`btnProject${id}`}>Project

    }
  })
}

How can I build them so that by the end of the 3 if statements, I return the built-up component, instead of returning inside every if statement?

I want something like this, in pseudo code

var component =

if (...)
  component += thing1
if (...)
  component += thing2

return component +

Body:
You can use switch statement to calculate detect needed title and then use just one return statement:

{prjLvlData.map(ele => {
    const active = ele.fields.has_experience ? 'active' : '';
    let title = '';

    switch (ele.fields.level_exp) {
        case 'portfolio':
            title = 'Portfolio';
            break;

        case 'program':
            title = 'Program';
            break;

        case 'project':
            title = 'Project';
            break;
    }

    return <div className={`btn btnAddBadge button noCursor projectLevelBtn ${active}`} id={`btnProject${id}`}>{title}</div>;
})}


问:
Autofill input separated by comma or space
This my code to autofill input:

```<code> $(document).ready(function(){
     $(document).on("change keyup mouseup", "#tag_content", function(){
     $("#tag_keyword").val($("#tag_content").val());
   });
 });
</code>```

https://jsfiddle.net/javasalden/urxhv486/4/

How to change keyup mouseup to show in 2 input from input paste, separated by comma or space?

答:
Firstly, you're assigning the same ID to two elements. IDs in HTML must be unique.

Secondly, you're assigning the entered value as is without processing. Split it by comma and that will give you an array of two items, so you can assign each of them to the two result boxes.

Try this:

$(document).ready(function() {
  $(document).on("change keyup mouseup", "#tag_content", function() {
    var longlat = $("#tag_content").val();
    if (longlat) {
      longlat = longlat.split(",");
      $("#tag_keyword_lat").val(longlat[0]);
      if (longlat.length > 1)
        $("#tag_keyword_long").val(longlat[1]);
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="form-group">
  <label class="col-lg-2 control-label">Data</label>
  <div class="col-lg-10">
    <input type="text" name="tag_content" id="tag_content" class="form-control" />
  </div>
</div>

<br>
<br>
<div class="dker bg-info form-group">
  <label class="col-lg-2 control-label">Latitude</label>
  <div class="col-lg-10">
    <input type="text" name="tag_keyword" id="tag_keyword_lat" class="form-control" />
  </div>
</div>

<br>

<div class="dker bg-info form-group">
  <label class="col-lg-2 control-label">Long Latitude</label>
  <div class="col-lg-10">
    <input type="text" name="tag_keyword" id="tag_keyword_long" class="form-control" />
  </div>
</div>

<br>
<br> if i paste on field data like this -7.972649,112.65860099999998
<br> that data will auto fill on field latitude and long latitude
<br>
<br> like this :
<br> latitude -7.972649
<br> longlatitude 112.65860099999998
<br>

<br>
<br> data separated by coma OR space</code>```

Body:
This my code to autofill input:

 $(document).ready(function(){
     $(document).on("change keyup mouseup", "#tag_content", function(){
     $("#tag_keyword").val($("#tag_content").val());
   });
 });

https://jsfiddle.net/javasalden/urxhv486/4/

How to change keyup mouseup to show in 2 input from input paste, separated by comma or space?

Body:
Firstly, you're assigning the same ID to two elements. IDs in HTML must be unique.

Secondly, you're assigning the entered value as is without processing. Split it by comma and that will give you an array of two items, so you can assign each of them to the two result boxes.

Try this:

$(document).ready(function() {
  $(document).on("change keyup mouseup", "#tag_content", function() {
    var longlat = $("#tag_content").val();
    if (longlat) {
      longlat = longlat.split(",");
      $("#tag_keyword_lat").val(longlat[0]);
      if (longlat.length > 1)
        $("#tag_keyword_long").val(longlat[1]);
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="form-group">
  <label class="col-lg-2 control-label">Data</label>
  <div class="col-lg-10">
    <input type="text" name="tag_content" id="tag_content" class="form-control" />
  </div>
</div>

<br>
<br>
<div class="dker bg-info form-group">
  <label class="col-lg-2 control-label">Latitude</label>
  <div class="col-lg-10">
    <input type="text" name="tag_keyword" id="tag_keyword_lat" class="form-control" />
  </div>
</div>

<br>

<div class="dker bg-info form-group">
  <label class="col-lg-2 control-label">Long Latitude</label>
  <div class="col-lg-10">
    <input type="text" name="tag_keyword" id="tag_keyword_long" class="form-control" />
  </div>
</div>

<br>
<br> if i paste on field data like this -7.972649,112.65860099999998
<br> that data will auto fill on field latitude and long latitude
<br>
<br> like this :
<br> latitude -7.972649
<br> longlatitude 112.65860099999998
<br>

<br>
<br> data separated by coma OR space