repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
projectatomic/atomic-reactor | atomic_reactor/plugins/exit_sendmail.py | SendMailPlugin._render_mail | def _render_mail(self, rebuild, success, auto_canceled, manual_canceled):
"""Render and return subject and body of the mail to send."""
subject_template = '%(endstate)s building image %(image_name)s'
body_template = '\n'.join([
'Image Name: %(image_name)s',
'Repositories: %(repositories)s',
'Status: %(endstate)s',
'Submitted by: %(user)s',
])
# Failed autorebuilds include logs as attachments.
# Koji integration stores logs in successful Koji Builds.
# Don't include logs in these cases.
if self.session and not rebuild:
body_template += '\nLogs: %(logs)s'
endstate = None
if auto_canceled or manual_canceled:
endstate = 'Canceled'
else:
endstate = 'Succeeded' if success else 'Failed'
url = self._get_logs_url()
image_name, repos = self._get_image_name_and_repos()
repositories = ''
for repo in repos:
repositories += '\n ' + repo
formatting_dict = {
'repositories': repositories,
'image_name': image_name,
'endstate': endstate,
'user': '<autorebuild>' if rebuild else self.submitter,
'logs': url
}
vcs = self.workflow.source.get_vcs_info()
if vcs:
body_template = '\n'.join([
body_template,
'Source url: %(vcs-url)s',
'Source ref: %(vcs-ref)s',
])
formatting_dict['vcs-url'] = vcs.vcs_url
formatting_dict['vcs-ref'] = vcs.vcs_ref
log_files = None
if rebuild and endstate == 'Failed':
log_files = self._fetch_log_files()
return (subject_template % formatting_dict, body_template % formatting_dict, log_files) | python | def _render_mail(self, rebuild, success, auto_canceled, manual_canceled):
"""Render and return subject and body of the mail to send."""
subject_template = '%(endstate)s building image %(image_name)s'
body_template = '\n'.join([
'Image Name: %(image_name)s',
'Repositories: %(repositories)s',
'Status: %(endstate)s',
'Submitted by: %(user)s',
])
# Failed autorebuilds include logs as attachments.
# Koji integration stores logs in successful Koji Builds.
# Don't include logs in these cases.
if self.session and not rebuild:
body_template += '\nLogs: %(logs)s'
endstate = None
if auto_canceled or manual_canceled:
endstate = 'Canceled'
else:
endstate = 'Succeeded' if success else 'Failed'
url = self._get_logs_url()
image_name, repos = self._get_image_name_and_repos()
repositories = ''
for repo in repos:
repositories += '\n ' + repo
formatting_dict = {
'repositories': repositories,
'image_name': image_name,
'endstate': endstate,
'user': '<autorebuild>' if rebuild else self.submitter,
'logs': url
}
vcs = self.workflow.source.get_vcs_info()
if vcs:
body_template = '\n'.join([
body_template,
'Source url: %(vcs-url)s',
'Source ref: %(vcs-ref)s',
])
formatting_dict['vcs-url'] = vcs.vcs_url
formatting_dict['vcs-ref'] = vcs.vcs_ref
log_files = None
if rebuild and endstate == 'Failed':
log_files = self._fetch_log_files()
return (subject_template % formatting_dict, body_template % formatting_dict, log_files) | [
"def",
"_render_mail",
"(",
"self",
",",
"rebuild",
",",
"success",
",",
"auto_canceled",
",",
"manual_canceled",
")",
":",
"subject_template",
"=",
"'%(endstate)s building image %(image_name)s'",
"body_template",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"'Image Name: %(i... | Render and return subject and body of the mail to send. | [
"Render",
"and",
"return",
"subject",
"and",
"body",
"of",
"the",
"mail",
"to",
"send",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/exit_sendmail.py#L244-L296 | train | 28,600 |
projectatomic/atomic-reactor | atomic_reactor/plugins/exit_sendmail.py | SendMailPlugin._send_mail | def _send_mail(self, receivers_list, subject, body, log_files=None):
if not receivers_list:
self.log.info('no valid addresses in requested addresses. Doing nothing')
return
self.log.info('sending notification to %s ...', receivers_list)
"""Actually sends the mail with `subject` and `body` and optionanl log_file attachements
to all members of `receivers_list`."""
if log_files:
msg = MIMEMultipart()
msg.attach(MIMEText(body))
for entry in log_files:
log_mime = MIMEBase('application', "octet-stream")
log_file = entry[0] # Output.file
log_file.seek(0)
log_mime.set_payload(log_file.read())
encoders.encode_base64(log_mime)
log_mime.add_header('Content-Disposition',
'attachment; filename="{}"'.format(entry[1]['filename']))
msg.attach(log_mime)
else:
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = self.from_address
msg['To'] = ', '.join([x.strip() for x in receivers_list])
s = None
try:
s = get_smtp_session(self.workflow, self.smtp_fallback)
s.sendmail(self.from_address, receivers_list, msg.as_string())
except (socket.gaierror, smtplib.SMTPException):
self.log.error('Error communicating with SMTP server')
raise
finally:
if s is not None:
s.quit() | python | def _send_mail(self, receivers_list, subject, body, log_files=None):
if not receivers_list:
self.log.info('no valid addresses in requested addresses. Doing nothing')
return
self.log.info('sending notification to %s ...', receivers_list)
"""Actually sends the mail with `subject` and `body` and optionanl log_file attachements
to all members of `receivers_list`."""
if log_files:
msg = MIMEMultipart()
msg.attach(MIMEText(body))
for entry in log_files:
log_mime = MIMEBase('application', "octet-stream")
log_file = entry[0] # Output.file
log_file.seek(0)
log_mime.set_payload(log_file.read())
encoders.encode_base64(log_mime)
log_mime.add_header('Content-Disposition',
'attachment; filename="{}"'.format(entry[1]['filename']))
msg.attach(log_mime)
else:
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = self.from_address
msg['To'] = ', '.join([x.strip() for x in receivers_list])
s = None
try:
s = get_smtp_session(self.workflow, self.smtp_fallback)
s.sendmail(self.from_address, receivers_list, msg.as_string())
except (socket.gaierror, smtplib.SMTPException):
self.log.error('Error communicating with SMTP server')
raise
finally:
if s is not None:
s.quit() | [
"def",
"_send_mail",
"(",
"self",
",",
"receivers_list",
",",
"subject",
",",
"body",
",",
"log_files",
"=",
"None",
")",
":",
"if",
"not",
"receivers_list",
":",
"self",
".",
"log",
".",
"info",
"(",
"'no valid addresses in requested addresses. Doing nothing'",
... | Actually sends the mail with `subject` and `body` and optionanl log_file attachements
to all members of `receivers_list`. | [
"Actually",
"sends",
"the",
"mail",
"with",
"subject",
"and",
"body",
"and",
"optionanl",
"log_file",
"attachements",
"to",
"all",
"members",
"of",
"receivers_list",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/exit_sendmail.py#L298-L334 | train | 28,601 |
projectatomic/atomic-reactor | atomic_reactor/plugins/post_fetch_worker_metadata.py | FetchWorkerMetadataPlugin.get_platform_metadata | def get_platform_metadata(self, platform, build_annotations):
"""
Return the metadata for the given platform.
"""
# retrieve all the workspace data
build_info = get_worker_build_info(self.workflow, platform)
osbs = build_info.osbs
kind = "configmap/"
cmlen = len(kind)
cm_key_tmp = build_annotations['metadata_fragment']
cm_frag_key = build_annotations['metadata_fragment_key']
if not cm_key_tmp or not cm_frag_key or cm_key_tmp[:cmlen] != kind:
msg = "Bad ConfigMap annotations for platform {}".format(platform)
self.log.warning(msg)
raise BadConfigMapError(msg)
# use the key to get the configmap data and then use the
# fragment_key to get the build metadata inside the configmap data
# save the worker_build metadata
cm_key = cm_key_tmp[cmlen:]
try:
cm_data = osbs.get_config_map(cm_key)
except Exception:
self.log.error("Failed to get ConfigMap for platform %s",
platform)
raise
metadata = cm_data.get_data_by_key(cm_frag_key)
defer_removal(self.workflow, cm_key, osbs)
return metadata | python | def get_platform_metadata(self, platform, build_annotations):
"""
Return the metadata for the given platform.
"""
# retrieve all the workspace data
build_info = get_worker_build_info(self.workflow, platform)
osbs = build_info.osbs
kind = "configmap/"
cmlen = len(kind)
cm_key_tmp = build_annotations['metadata_fragment']
cm_frag_key = build_annotations['metadata_fragment_key']
if not cm_key_tmp or not cm_frag_key or cm_key_tmp[:cmlen] != kind:
msg = "Bad ConfigMap annotations for platform {}".format(platform)
self.log.warning(msg)
raise BadConfigMapError(msg)
# use the key to get the configmap data and then use the
# fragment_key to get the build metadata inside the configmap data
# save the worker_build metadata
cm_key = cm_key_tmp[cmlen:]
try:
cm_data = osbs.get_config_map(cm_key)
except Exception:
self.log.error("Failed to get ConfigMap for platform %s",
platform)
raise
metadata = cm_data.get_data_by_key(cm_frag_key)
defer_removal(self.workflow, cm_key, osbs)
return metadata | [
"def",
"get_platform_metadata",
"(",
"self",
",",
"platform",
",",
"build_annotations",
")",
":",
"# retrieve all the workspace data",
"build_info",
"=",
"get_worker_build_info",
"(",
"self",
".",
"workflow",
",",
"platform",
")",
"osbs",
"=",
"build_info",
".",
"os... | Return the metadata for the given platform. | [
"Return",
"the",
"metadata",
"for",
"the",
"given",
"platform",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_fetch_worker_metadata.py#L32-L64 | train | 28,602 |
projectatomic/atomic-reactor | atomic_reactor/plugins/exit_koji_import.py | KojiImportPlugin.get_output | def get_output(self, worker_metadatas):
"""
Build the output entry of the metadata.
:return: list, containing dicts of partial metadata
"""
outputs = []
has_pulp_pull = PLUGIN_PULP_PULL_KEY in self.workflow.exit_results
try:
pulp_sync_results = self.workflow.postbuild_results[PLUGIN_PULP_SYNC_KEY]
crane_registry = pulp_sync_results[0]
except (KeyError, IndexError):
crane_registry = None
for platform in worker_metadatas:
for instance in worker_metadatas[platform]['output']:
instance['buildroot_id'] = '{}-{}'.format(platform, instance['buildroot_id'])
if instance['type'] == 'docker-image':
# update image ID with pulp_pull results;
# necessary when using Pulp < 2.14. Only do this
# when building for a single architecture -- if
# building for many, we know Pulp has schema 2
# support.
if len(worker_metadatas) == 1 and has_pulp_pull:
if self.workflow.builder.image_id is not None:
instance['extra']['docker']['id'] = self.workflow.builder.image_id
# update repositories to point to Crane
if crane_registry:
pulp_pullspecs = []
docker = instance['extra']['docker']
for pullspec in docker['repositories']:
image = ImageName.parse(pullspec)
image.registry = crane_registry.registry
pulp_pullspecs.append(image.to_str())
docker['repositories'] = pulp_pullspecs
outputs.append(instance)
return outputs | python | def get_output(self, worker_metadatas):
"""
Build the output entry of the metadata.
:return: list, containing dicts of partial metadata
"""
outputs = []
has_pulp_pull = PLUGIN_PULP_PULL_KEY in self.workflow.exit_results
try:
pulp_sync_results = self.workflow.postbuild_results[PLUGIN_PULP_SYNC_KEY]
crane_registry = pulp_sync_results[0]
except (KeyError, IndexError):
crane_registry = None
for platform in worker_metadatas:
for instance in worker_metadatas[platform]['output']:
instance['buildroot_id'] = '{}-{}'.format(platform, instance['buildroot_id'])
if instance['type'] == 'docker-image':
# update image ID with pulp_pull results;
# necessary when using Pulp < 2.14. Only do this
# when building for a single architecture -- if
# building for many, we know Pulp has schema 2
# support.
if len(worker_metadatas) == 1 and has_pulp_pull:
if self.workflow.builder.image_id is not None:
instance['extra']['docker']['id'] = self.workflow.builder.image_id
# update repositories to point to Crane
if crane_registry:
pulp_pullspecs = []
docker = instance['extra']['docker']
for pullspec in docker['repositories']:
image = ImageName.parse(pullspec)
image.registry = crane_registry.registry
pulp_pullspecs.append(image.to_str())
docker['repositories'] = pulp_pullspecs
outputs.append(instance)
return outputs | [
"def",
"get_output",
"(",
"self",
",",
"worker_metadatas",
")",
":",
"outputs",
"=",
"[",
"]",
"has_pulp_pull",
"=",
"PLUGIN_PULP_PULL_KEY",
"in",
"self",
".",
"workflow",
".",
"exit_results",
"try",
":",
"pulp_sync_results",
"=",
"self",
".",
"workflow",
".",... | Build the output entry of the metadata.
:return: list, containing dicts of partial metadata | [
"Build",
"the",
"output",
"entry",
"of",
"the",
"metadata",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/exit_koji_import.py#L128-L169 | train | 28,603 |
projectatomic/atomic-reactor | atomic_reactor/auth.py | HTTPBearerAuth.handle_401 | def handle_401(self, response, repo, **kwargs):
"""Fetch Bearer token and retry."""
if response.status_code != requests.codes.unauthorized:
return response
auth_info = response.headers.get('www-authenticate', '')
if 'bearer' not in auth_info.lower():
return response
self._token_cache[repo] = self._get_token(auth_info, repo)
# Consume content and release the original connection
# to allow our new request to reuse the same one.
# This pattern was inspired by the source code of requests.auth.HTTPDigestAuth
response.content
response.close()
retry_request = response.request.copy()
extract_cookies_to_jar(retry_request._cookies, response.request, response.raw)
retry_request.prepare_cookies(retry_request._cookies)
self._set_header(retry_request, repo)
retry_response = response.connection.send(retry_request, **kwargs)
retry_response.history.append(response)
retry_response.request = retry_request
return retry_response | python | def handle_401(self, response, repo, **kwargs):
"""Fetch Bearer token and retry."""
if response.status_code != requests.codes.unauthorized:
return response
auth_info = response.headers.get('www-authenticate', '')
if 'bearer' not in auth_info.lower():
return response
self._token_cache[repo] = self._get_token(auth_info, repo)
# Consume content and release the original connection
# to allow our new request to reuse the same one.
# This pattern was inspired by the source code of requests.auth.HTTPDigestAuth
response.content
response.close()
retry_request = response.request.copy()
extract_cookies_to_jar(retry_request._cookies, response.request, response.raw)
retry_request.prepare_cookies(retry_request._cookies)
self._set_header(retry_request, repo)
retry_response = response.connection.send(retry_request, **kwargs)
retry_response.history.append(response)
retry_response.request = retry_request
return retry_response | [
"def",
"handle_401",
"(",
"self",
",",
"response",
",",
"repo",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"response",
".",
"status_code",
"!=",
"requests",
".",
"codes",
".",
"unauthorized",
":",
"return",
"response",
"auth_info",
"=",
"response",
".",
"h... | Fetch Bearer token and retry. | [
"Fetch",
"Bearer",
"token",
"and",
"retry",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/auth.py#L70-L96 | train | 28,604 |
projectatomic/atomic-reactor | atomic_reactor/plugins/input_osv3.py | OSv3InputPlugin.remove_plugins_without_parameters | def remove_plugins_without_parameters(self):
"""
This used to be handled in BuildRequest, but with REACTOR_CONFIG, osbs-client doesn't have
enough information.
"""
# Compatibility code for dockerfile_content plugin
self.remove_plugin('prebuild_plugins', PLUGIN_DOCKERFILE_CONTENT_KEY,
'dockerfile_content is deprecated, please remove from config')
if not self.reactor_env:
return
self.remove_koji_plugins()
self.remove_pulp_plugins()
if not self.get_value('odcs'):
self.remove_plugin('prebuild_plugins', PLUGIN_RESOLVE_COMPOSES_KEY,
'no odcs available')
if not self.get_value('smtp'):
self.remove_plugin('exit_plugins', PLUGIN_SENDMAIL_KEY, 'no mailhost available')
if not self.get_value('sources_command'):
self.remove_plugin('prebuild_plugins', PLUGIN_DISTGIT_FETCH_KEY, 'no sources command') | python | def remove_plugins_without_parameters(self):
"""
This used to be handled in BuildRequest, but with REACTOR_CONFIG, osbs-client doesn't have
enough information.
"""
# Compatibility code for dockerfile_content plugin
self.remove_plugin('prebuild_plugins', PLUGIN_DOCKERFILE_CONTENT_KEY,
'dockerfile_content is deprecated, please remove from config')
if not self.reactor_env:
return
self.remove_koji_plugins()
self.remove_pulp_plugins()
if not self.get_value('odcs'):
self.remove_plugin('prebuild_plugins', PLUGIN_RESOLVE_COMPOSES_KEY,
'no odcs available')
if not self.get_value('smtp'):
self.remove_plugin('exit_plugins', PLUGIN_SENDMAIL_KEY, 'no mailhost available')
if not self.get_value('sources_command'):
self.remove_plugin('prebuild_plugins', PLUGIN_DISTGIT_FETCH_KEY, 'no sources command') | [
"def",
"remove_plugins_without_parameters",
"(",
"self",
")",
":",
"# Compatibility code for dockerfile_content plugin",
"self",
".",
"remove_plugin",
"(",
"'prebuild_plugins'",
",",
"PLUGIN_DOCKERFILE_CONTENT_KEY",
",",
"'dockerfile_content is deprecated, please remove from config'",
... | This used to be handled in BuildRequest, but with REACTOR_CONFIG, osbs-client doesn't have
enough information. | [
"This",
"used",
"to",
"be",
"handled",
"in",
"BuildRequest",
"but",
"with",
"REACTOR_CONFIG",
"osbs",
"-",
"client",
"doesn",
"t",
"have",
"enough",
"information",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/input_osv3.py#L154-L173 | train | 28,605 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_resolve_composes.py | ResolveComposesPlugin.adjust_for_autorebuild | def adjust_for_autorebuild(self):
"""Ignore pre-filled signing_intent and compose_ids for autorebuids
Auto rebuilds are expected to use a known configuration. The parameters
signing_intent and compose_ids are meant for one-off build calls. This
method ensure that these parameters are ignored for autorebuilds.
"""
if not is_rebuild(self.workflow):
return
if self.signing_intent:
self.log.info('Autorebuild detected: Ignoring signing_intent plugin parameter')
self.signing_intent = None
if self.compose_ids:
self.log.info('Autorebuild detected: Ignoring compose_ids plugin parameter')
self.compose_ids = tuple()
self.all_compose_ids = [] | python | def adjust_for_autorebuild(self):
"""Ignore pre-filled signing_intent and compose_ids for autorebuids
Auto rebuilds are expected to use a known configuration. The parameters
signing_intent and compose_ids are meant for one-off build calls. This
method ensure that these parameters are ignored for autorebuilds.
"""
if not is_rebuild(self.workflow):
return
if self.signing_intent:
self.log.info('Autorebuild detected: Ignoring signing_intent plugin parameter')
self.signing_intent = None
if self.compose_ids:
self.log.info('Autorebuild detected: Ignoring compose_ids plugin parameter')
self.compose_ids = tuple()
self.all_compose_ids = [] | [
"def",
"adjust_for_autorebuild",
"(",
"self",
")",
":",
"if",
"not",
"is_rebuild",
"(",
"self",
".",
"workflow",
")",
":",
"return",
"if",
"self",
".",
"signing_intent",
":",
"self",
".",
"log",
".",
"info",
"(",
"'Autorebuild detected: Ignoring signing_intent p... | Ignore pre-filled signing_intent and compose_ids for autorebuids
Auto rebuilds are expected to use a known configuration. The parameters
signing_intent and compose_ids are meant for one-off build calls. This
method ensure that these parameters are ignored for autorebuilds. | [
"Ignore",
"pre",
"-",
"filled",
"signing_intent",
"and",
"compose_ids",
"for",
"autorebuids"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_resolve_composes.py#L131-L148 | train | 28,606 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_resolve_composes.py | ResolveComposesPlugin.resolve_signing_intent | def resolve_signing_intent(self):
"""Determine the correct signing intent
Regardless of what was requested, or provided as signing_intent plugin parameter,
consult sigkeys of the actual composes used to guarantee information accuracy.
"""
all_signing_intents = [
self.odcs_config.get_signing_intent_by_keys(compose_info.get('sigkeys', []))
for compose_info in self.composes_info
]
# Because composes_info may contain composes that were passed as
# plugin parameters, add the parent signing intent to avoid the
# overall signing intent from surpassing parent's.
if self._parent_signing_intent:
all_signing_intents.append(self._parent_signing_intent)
# Calculate the least restrictive signing intent
signing_intent = min(all_signing_intents, key=lambda x: x['restrictiveness'])
self.log.info('Signing intent for build is %s', signing_intent['name'])
self.compose_config.set_signing_intent(signing_intent['name']) | python | def resolve_signing_intent(self):
"""Determine the correct signing intent
Regardless of what was requested, or provided as signing_intent plugin parameter,
consult sigkeys of the actual composes used to guarantee information accuracy.
"""
all_signing_intents = [
self.odcs_config.get_signing_intent_by_keys(compose_info.get('sigkeys', []))
for compose_info in self.composes_info
]
# Because composes_info may contain composes that were passed as
# plugin parameters, add the parent signing intent to avoid the
# overall signing intent from surpassing parent's.
if self._parent_signing_intent:
all_signing_intents.append(self._parent_signing_intent)
# Calculate the least restrictive signing intent
signing_intent = min(all_signing_intents, key=lambda x: x['restrictiveness'])
self.log.info('Signing intent for build is %s', signing_intent['name'])
self.compose_config.set_signing_intent(signing_intent['name']) | [
"def",
"resolve_signing_intent",
"(",
"self",
")",
":",
"all_signing_intents",
"=",
"[",
"self",
".",
"odcs_config",
".",
"get_signing_intent_by_keys",
"(",
"compose_info",
".",
"get",
"(",
"'sigkeys'",
",",
"[",
"]",
")",
")",
"for",
"compose_info",
"in",
"se... | Determine the correct signing intent
Regardless of what was requested, or provided as signing_intent plugin parameter,
consult sigkeys of the actual composes used to guarantee information accuracy. | [
"Determine",
"the",
"correct",
"signing",
"intent"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_resolve_composes.py#L281-L303 | train | 28,607 |
projectatomic/atomic-reactor | atomic_reactor/plugins/pre_resolve_composes.py | ComposeConfig.validate_for_request | def validate_for_request(self):
"""Verify enough information is available for requesting compose."""
if not self.use_packages and not self.modules and not self.pulp:
raise ValueError("Nothing to compose (no packages, modules, or enabled pulp repos)")
if self.packages and not self.koji_tag:
raise ValueError('koji_tag is required when packages are used') | python | def validate_for_request(self):
"""Verify enough information is available for requesting compose."""
if not self.use_packages and not self.modules and not self.pulp:
raise ValueError("Nothing to compose (no packages, modules, or enabled pulp repos)")
if self.packages and not self.koji_tag:
raise ValueError('koji_tag is required when packages are used') | [
"def",
"validate_for_request",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"use_packages",
"and",
"not",
"self",
".",
"modules",
"and",
"not",
"self",
".",
"pulp",
":",
"raise",
"ValueError",
"(",
"\"Nothing to compose (no packages, modules, or enabled pulp rep... | Verify enough information is available for requesting compose. | [
"Verify",
"enough",
"information",
"is",
"available",
"for",
"requesting",
"compose",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_resolve_composes.py#L452-L458 | train | 28,608 |
projectatomic/atomic-reactor | atomic_reactor/plugins/input_path.py | PathInputPlugin.run | def run(self):
"""
get json with build config from path
"""
path = self.path or CONTAINER_BUILD_JSON_PATH
try:
with open(path, 'r') as build_cfg_fd:
build_cfg_json = json.load(build_cfg_fd)
except ValueError:
self.log.error("couldn't decode json from file '%s'", path)
return None
except IOError:
self.log.error("couldn't read json from file '%s'", path)
return None
else:
return self.substitute_configuration(build_cfg_json) | python | def run(self):
"""
get json with build config from path
"""
path = self.path or CONTAINER_BUILD_JSON_PATH
try:
with open(path, 'r') as build_cfg_fd:
build_cfg_json = json.load(build_cfg_fd)
except ValueError:
self.log.error("couldn't decode json from file '%s'", path)
return None
except IOError:
self.log.error("couldn't read json from file '%s'", path)
return None
else:
return self.substitute_configuration(build_cfg_json) | [
"def",
"run",
"(",
"self",
")",
":",
"path",
"=",
"self",
".",
"path",
"or",
"CONTAINER_BUILD_JSON_PATH",
"try",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"build_cfg_fd",
":",
"build_cfg_json",
"=",
"json",
".",
"load",
"(",
"build_cfg_fd"... | get json with build config from path | [
"get",
"json",
"with",
"build",
"config",
"from",
"path"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/input_path.py#L32-L47 | train | 28,609 |
projectatomic/atomic-reactor | atomic_reactor/plugins/post_export_operator_manifests.py | ExportOperatorManifestsPlugin.has_operator_manifest | def has_operator_manifest(self):
"""
Check if Dockerfile sets the operator manifest label
:return: bool
"""
dockerfile = df_parser(self.workflow.builder.df_path, workflow=self.workflow)
labels = Labels(dockerfile.labels)
try:
_, operator_label = labels.get_name_and_value(Labels.LABEL_TYPE_OPERATOR_MANIFESTS)
except KeyError:
operator_label = 'false'
return operator_label.lower() == 'true' | python | def has_operator_manifest(self):
"""
Check if Dockerfile sets the operator manifest label
:return: bool
"""
dockerfile = df_parser(self.workflow.builder.df_path, workflow=self.workflow)
labels = Labels(dockerfile.labels)
try:
_, operator_label = labels.get_name_and_value(Labels.LABEL_TYPE_OPERATOR_MANIFESTS)
except KeyError:
operator_label = 'false'
return operator_label.lower() == 'true' | [
"def",
"has_operator_manifest",
"(",
"self",
")",
":",
"dockerfile",
"=",
"df_parser",
"(",
"self",
".",
"workflow",
".",
"builder",
".",
"df_path",
",",
"workflow",
"=",
"self",
".",
"workflow",
")",
"labels",
"=",
"Labels",
"(",
"dockerfile",
".",
"label... | Check if Dockerfile sets the operator manifest label
:return: bool | [
"Check",
"if",
"Dockerfile",
"sets",
"the",
"operator",
"manifest",
"label"
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_export_operator_manifests.py#L49-L61 | train | 28,610 |
projectatomic/atomic-reactor | atomic_reactor/plugins/post_export_operator_manifests.py | ExportOperatorManifestsPlugin.should_run | def should_run(self):
"""
Check if the plugin should run or skip execution.
:return: bool, False if plugin should skip execution
"""
if self.is_orchestrator():
self.log.warning("%s plugin set to run on orchestrator. Skipping", self.key)
return False
if self.operator_manifests_extract_platform != self.platform:
self.log.info("Only platform [%s] will upload operators metadata. Skipping",
self.operator_manifests_extract_platform)
return False
if is_scratch_build():
self.log.info("Scratch build. Skipping")
return False
if not self.has_operator_manifest():
self.log.info("Operator manifests label not set in Dockerfile. Skipping")
return False
return True | python | def should_run(self):
"""
Check if the plugin should run or skip execution.
:return: bool, False if plugin should skip execution
"""
if self.is_orchestrator():
self.log.warning("%s plugin set to run on orchestrator. Skipping", self.key)
return False
if self.operator_manifests_extract_platform != self.platform:
self.log.info("Only platform [%s] will upload operators metadata. Skipping",
self.operator_manifests_extract_platform)
return False
if is_scratch_build():
self.log.info("Scratch build. Skipping")
return False
if not self.has_operator_manifest():
self.log.info("Operator manifests label not set in Dockerfile. Skipping")
return False
return True | [
"def",
"should_run",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_orchestrator",
"(",
")",
":",
"self",
".",
"log",
".",
"warning",
"(",
"\"%s plugin set to run on orchestrator. Skipping\"",
",",
"self",
".",
"key",
")",
"return",
"False",
"if",
"self",
"."... | Check if the plugin should run or skip execution.
:return: bool, False if plugin should skip execution | [
"Check",
"if",
"the",
"plugin",
"should",
"run",
"or",
"skip",
"execution",
"."
] | fd31c01b964097210bf169960d051e5f04019a80 | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_export_operator_manifests.py#L73-L92 | train | 28,611 |
mpetazzoni/sseclient | sseclient/__init__.py | SSEClient._read | def _read(self):
"""Read the incoming event source stream and yield event chunks.
Unfortunately it is possible for some servers to decide to break an
event into multiple HTTP chunks in the response. It is thus necessary
to correctly stitch together consecutive response chunks and find the
SSE delimiter (empty new line) to yield full, correct event chunks."""
data = b''
for chunk in self._event_source:
for line in chunk.splitlines(True):
data += line
if data.endswith((b'\r\r', b'\n\n', b'\r\n\r\n')):
yield data
data = b''
if data:
yield data | python | def _read(self):
"""Read the incoming event source stream and yield event chunks.
Unfortunately it is possible for some servers to decide to break an
event into multiple HTTP chunks in the response. It is thus necessary
to correctly stitch together consecutive response chunks and find the
SSE delimiter (empty new line) to yield full, correct event chunks."""
data = b''
for chunk in self._event_source:
for line in chunk.splitlines(True):
data += line
if data.endswith((b'\r\r', b'\n\n', b'\r\n\r\n')):
yield data
data = b''
if data:
yield data | [
"def",
"_read",
"(",
"self",
")",
":",
"data",
"=",
"b''",
"for",
"chunk",
"in",
"self",
".",
"_event_source",
":",
"for",
"line",
"in",
"chunk",
".",
"splitlines",
"(",
"True",
")",
":",
"data",
"+=",
"line",
"if",
"data",
".",
"endswith",
"(",
"(... | Read the incoming event source stream and yield event chunks.
Unfortunately it is possible for some servers to decide to break an
event into multiple HTTP chunks in the response. It is thus necessary
to correctly stitch together consecutive response chunks and find the
SSE delimiter (empty new line) to yield full, correct event chunks. | [
"Read",
"the",
"incoming",
"event",
"source",
"stream",
"and",
"yield",
"event",
"chunks",
"."
] | ee274733cdfaef38ec97ea32b4a55b79ec71a8fd | https://github.com/mpetazzoni/sseclient/blob/ee274733cdfaef38ec97ea32b4a55b79ec71a8fd/sseclient/__init__.py#L40-L55 | train | 28,612 |
caffeinehit/django-oauth2-provider | provider/scope.py | check | def check(wants, has):
"""
Check if a desired scope ``wants`` is part of an available scope ``has``.
Returns ``False`` if not, return ``True`` if yes.
:example:
If a list of scopes such as
::
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
SCOPES = (
(READ, 'read'),
(WRITE, 'write'),
(READ_WRITE, 'read+write'),
)
is defined, we can check if a given scope is part of another:
::
>>> from provider import scope
>>> scope.check(READ, READ)
True
>>> scope.check(WRITE, READ)
False
>>> scope.check(WRITE, WRITE)
True
>>> scope.check(READ, WRITE)
False
>>> scope.check(READ, READ_WRITE)
True
>>> scope.check(WRITE, READ_WRITE)
True
"""
if wants & has == 0:
return False
if wants & has < wants:
return False
return True | python | def check(wants, has):
"""
Check if a desired scope ``wants`` is part of an available scope ``has``.
Returns ``False`` if not, return ``True`` if yes.
:example:
If a list of scopes such as
::
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
SCOPES = (
(READ, 'read'),
(WRITE, 'write'),
(READ_WRITE, 'read+write'),
)
is defined, we can check if a given scope is part of another:
::
>>> from provider import scope
>>> scope.check(READ, READ)
True
>>> scope.check(WRITE, READ)
False
>>> scope.check(WRITE, WRITE)
True
>>> scope.check(READ, WRITE)
False
>>> scope.check(READ, READ_WRITE)
True
>>> scope.check(WRITE, READ_WRITE)
True
"""
if wants & has == 0:
return False
if wants & has < wants:
return False
return True | [
"def",
"check",
"(",
"wants",
",",
"has",
")",
":",
"if",
"wants",
"&",
"has",
"==",
"0",
":",
"return",
"False",
"if",
"wants",
"&",
"has",
"<",
"wants",
":",
"return",
"False",
"return",
"True"
] | Check if a desired scope ``wants`` is part of an available scope ``has``.
Returns ``False`` if not, return ``True`` if yes.
:example:
If a list of scopes such as
::
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
SCOPES = (
(READ, 'read'),
(WRITE, 'write'),
(READ_WRITE, 'read+write'),
)
is defined, we can check if a given scope is part of another:
::
>>> from provider import scope
>>> scope.check(READ, READ)
True
>>> scope.check(WRITE, READ)
False
>>> scope.check(WRITE, WRITE)
True
>>> scope.check(READ, WRITE)
False
>>> scope.check(READ, READ_WRITE)
True
>>> scope.check(WRITE, READ_WRITE)
True | [
"Check",
"if",
"a",
"desired",
"scope",
"wants",
"is",
"part",
"of",
"an",
"available",
"scope",
"has",
"."
] | 6b5bc0d3ad706d2aaa47fa476f38406cddd01236 | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/scope.py#L18-L63 | train | 28,613 |
caffeinehit/django-oauth2-provider | provider/scope.py | to_int | def to_int(*names, **kwargs):
"""
Turns a list of scope names into an integer value.
::
>>> scope.to_int('read')
2
>>> scope.to_int('write')
6
>>> scope.to_int('read', 'write')
6
>>> scope.to_int('invalid')
0
>>> scope.to_int('invalid', default = 1)
1
"""
return reduce(lambda prev, next: (prev | SCOPE_NAME_DICT.get(next, 0)),
names, kwargs.pop('default', 0)) | python | def to_int(*names, **kwargs):
"""
Turns a list of scope names into an integer value.
::
>>> scope.to_int('read')
2
>>> scope.to_int('write')
6
>>> scope.to_int('read', 'write')
6
>>> scope.to_int('invalid')
0
>>> scope.to_int('invalid', default = 1)
1
"""
return reduce(lambda prev, next: (prev | SCOPE_NAME_DICT.get(next, 0)),
names, kwargs.pop('default', 0)) | [
"def",
"to_int",
"(",
"*",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"reduce",
"(",
"lambda",
"prev",
",",
"next",
":",
"(",
"prev",
"|",
"SCOPE_NAME_DICT",
".",
"get",
"(",
"next",
",",
"0",
")",
")",
",",
"names",
",",
"kwargs",
"."... | Turns a list of scope names into an integer value.
::
>>> scope.to_int('read')
2
>>> scope.to_int('write')
6
>>> scope.to_int('read', 'write')
6
>>> scope.to_int('invalid')
0
>>> scope.to_int('invalid', default = 1)
1 | [
"Turns",
"a",
"list",
"of",
"scope",
"names",
"into",
"an",
"integer",
"value",
"."
] | 6b5bc0d3ad706d2aaa47fa476f38406cddd01236 | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/scope.py#L84-L104 | train | 28,614 |
caffeinehit/django-oauth2-provider | provider/views.py | Mixin.get_data | def get_data(self, request, key='params'):
"""
Return stored data from the session store.
:param key: `str` The key under which the data was stored.
"""
return request.session.get('%s:%s' % (constants.SESSION_KEY, key)) | python | def get_data(self, request, key='params'):
"""
Return stored data from the session store.
:param key: `str` The key under which the data was stored.
"""
return request.session.get('%s:%s' % (constants.SESSION_KEY, key)) | [
"def",
"get_data",
"(",
"self",
",",
"request",
",",
"key",
"=",
"'params'",
")",
":",
"return",
"request",
".",
"session",
".",
"get",
"(",
"'%s:%s'",
"%",
"(",
"constants",
".",
"SESSION_KEY",
",",
"key",
")",
")"
] | Return stored data from the session store.
:param key: `str` The key under which the data was stored. | [
"Return",
"stored",
"data",
"from",
"the",
"session",
"store",
"."
] | 6b5bc0d3ad706d2aaa47fa476f38406cddd01236 | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/views.py#L52-L58 | train | 28,615 |
caffeinehit/django-oauth2-provider | provider/views.py | Mixin.cache_data | def cache_data(self, request, data, key='params'):
"""
Cache data in the session store.
:param request: :attr:`django.http.HttpRequest`
:param data: Arbitrary data to store.
:param key: `str` The key under which to store the data.
"""
request.session['%s:%s' % (constants.SESSION_KEY, key)] = data | python | def cache_data(self, request, data, key='params'):
"""
Cache data in the session store.
:param request: :attr:`django.http.HttpRequest`
:param data: Arbitrary data to store.
:param key: `str` The key under which to store the data.
"""
request.session['%s:%s' % (constants.SESSION_KEY, key)] = data | [
"def",
"cache_data",
"(",
"self",
",",
"request",
",",
"data",
",",
"key",
"=",
"'params'",
")",
":",
"request",
".",
"session",
"[",
"'%s:%s'",
"%",
"(",
"constants",
".",
"SESSION_KEY",
",",
"key",
")",
"]",
"=",
"data"
] | Cache data in the session store.
:param request: :attr:`django.http.HttpRequest`
:param data: Arbitrary data to store.
:param key: `str` The key under which to store the data. | [
"Cache",
"data",
"in",
"the",
"session",
"store",
"."
] | 6b5bc0d3ad706d2aaa47fa476f38406cddd01236 | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/views.py#L60-L68 | train | 28,616 |
caffeinehit/django-oauth2-provider | provider/views.py | Mixin.clear_data | def clear_data(self, request):
"""
Clear all OAuth related data from the session store.
"""
for key in request.session.keys():
if key.startswith(constants.SESSION_KEY):
del request.session[key] | python | def clear_data(self, request):
"""
Clear all OAuth related data from the session store.
"""
for key in request.session.keys():
if key.startswith(constants.SESSION_KEY):
del request.session[key] | [
"def",
"clear_data",
"(",
"self",
",",
"request",
")",
":",
"for",
"key",
"in",
"request",
".",
"session",
".",
"keys",
"(",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"constants",
".",
"SESSION_KEY",
")",
":",
"del",
"request",
".",
"session",
"... | Clear all OAuth related data from the session store. | [
"Clear",
"all",
"OAuth",
"related",
"data",
"from",
"the",
"session",
"store",
"."
] | 6b5bc0d3ad706d2aaa47fa476f38406cddd01236 | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/views.py#L70-L76 | train | 28,617 |
caffeinehit/django-oauth2-provider | provider/views.py | Authorize.error_response | def error_response(self, request, error, **kwargs):
"""
Return an error to be displayed to the resource owner if anything goes
awry. Errors can include invalid clients, authorization denials and
other edge cases such as a wrong ``redirect_uri`` in the authorization
request.
:param request: :attr:`django.http.HttpRequest`
:param error: ``dict``
The different types of errors are outlined in :rfc:`4.2.2.1`
"""
ctx = {}
ctx.update(error)
# If we got a malicious redirect_uri or client_id, remove all the
# cached data and tell the resource owner. We will *not* redirect back
# to the URL.
if error['error'] in ['redirect_uri', 'unauthorized_client']:
ctx.update(next='/')
return self.render_to_response(ctx, **kwargs)
ctx.update(next=self.get_redirect_url(request))
return self.render_to_response(ctx, **kwargs) | python | def error_response(self, request, error, **kwargs):
"""
Return an error to be displayed to the resource owner if anything goes
awry. Errors can include invalid clients, authorization denials and
other edge cases such as a wrong ``redirect_uri`` in the authorization
request.
:param request: :attr:`django.http.HttpRequest`
:param error: ``dict``
The different types of errors are outlined in :rfc:`4.2.2.1`
"""
ctx = {}
ctx.update(error)
# If we got a malicious redirect_uri or client_id, remove all the
# cached data and tell the resource owner. We will *not* redirect back
# to the URL.
if error['error'] in ['redirect_uri', 'unauthorized_client']:
ctx.update(next='/')
return self.render_to_response(ctx, **kwargs)
ctx.update(next=self.get_redirect_url(request))
return self.render_to_response(ctx, **kwargs) | [
"def",
"error_response",
"(",
"self",
",",
"request",
",",
"error",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"{",
"}",
"ctx",
".",
"update",
"(",
"error",
")",
"# If we got a malicious redirect_uri or client_id, remove all the",
"# cached data and tell the res... | Return an error to be displayed to the resource owner if anything goes
awry. Errors can include invalid clients, authorization denials and
other edge cases such as a wrong ``redirect_uri`` in the authorization
request.
:param request: :attr:`django.http.HttpRequest`
:param error: ``dict``
The different types of errors are outlined in :rfc:`4.2.2.1` | [
"Return",
"an",
"error",
"to",
"be",
"displayed",
"to",
"the",
"resource",
"owner",
"if",
"anything",
"goes",
"awry",
".",
"Errors",
"can",
"include",
"invalid",
"clients",
"authorization",
"denials",
"and",
"other",
"edge",
"cases",
"such",
"as",
"a",
"wron... | 6b5bc0d3ad706d2aaa47fa476f38406cddd01236 | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/views.py#L222-L246 | train | 28,618 |
caffeinehit/django-oauth2-provider | provider/views.py | AccessToken.get_handler | def get_handler(self, grant_type):
"""
Return a function or method that is capable handling the ``grant_type``
requested by the client or return ``None`` to indicate that this type
of grant type is not supported, resulting in an error response.
"""
if grant_type == 'authorization_code':
return self.authorization_code
elif grant_type == 'refresh_token':
return self.refresh_token
elif grant_type == 'password':
return self.password
return None | python | def get_handler(self, grant_type):
"""
Return a function or method that is capable handling the ``grant_type``
requested by the client or return ``None`` to indicate that this type
of grant type is not supported, resulting in an error response.
"""
if grant_type == 'authorization_code':
return self.authorization_code
elif grant_type == 'refresh_token':
return self.refresh_token
elif grant_type == 'password':
return self.password
return None | [
"def",
"get_handler",
"(",
"self",
",",
"grant_type",
")",
":",
"if",
"grant_type",
"==",
"'authorization_code'",
":",
"return",
"self",
".",
"authorization_code",
"elif",
"grant_type",
"==",
"'refresh_token'",
":",
"return",
"self",
".",
"refresh_token",
"elif",
... | Return a function or method that is capable handling the ``grant_type``
requested by the client or return ``None`` to indicate that this type
of grant type is not supported, resulting in an error response. | [
"Return",
"a",
"function",
"or",
"method",
"that",
"is",
"capable",
"handling",
"the",
"grant_type",
"requested",
"by",
"the",
"client",
"or",
"return",
"None",
"to",
"indicate",
"that",
"this",
"type",
"of",
"grant",
"type",
"is",
"not",
"supported",
"resul... | 6b5bc0d3ad706d2aaa47fa476f38406cddd01236 | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/views.py#L547-L559 | train | 28,619 |
caffeinehit/django-oauth2-provider | provider/oauth2/models.py | AccessToken.get_expire_delta | def get_expire_delta(self, reference=None):
"""
Return the number of seconds until this token expires.
"""
if reference is None:
reference = now()
expiration = self.expires
if timezone:
if timezone.is_aware(reference) and timezone.is_naive(expiration):
# MySQL doesn't support timezone for datetime fields
# so we assume that the date was stored in the UTC timezone
expiration = timezone.make_aware(expiration, timezone.utc)
elif timezone.is_naive(reference) and timezone.is_aware(expiration):
reference = timezone.make_aware(reference, timezone.utc)
timedelta = expiration - reference
return timedelta.days*86400 + timedelta.seconds | python | def get_expire_delta(self, reference=None):
"""
Return the number of seconds until this token expires.
"""
if reference is None:
reference = now()
expiration = self.expires
if timezone:
if timezone.is_aware(reference) and timezone.is_naive(expiration):
# MySQL doesn't support timezone for datetime fields
# so we assume that the date was stored in the UTC timezone
expiration = timezone.make_aware(expiration, timezone.utc)
elif timezone.is_naive(reference) and timezone.is_aware(expiration):
reference = timezone.make_aware(reference, timezone.utc)
timedelta = expiration - reference
return timedelta.days*86400 + timedelta.seconds | [
"def",
"get_expire_delta",
"(",
"self",
",",
"reference",
"=",
"None",
")",
":",
"if",
"reference",
"is",
"None",
":",
"reference",
"=",
"now",
"(",
")",
"expiration",
"=",
"self",
".",
"expires",
"if",
"timezone",
":",
"if",
"timezone",
".",
"is_aware",... | Return the number of seconds until this token expires. | [
"Return",
"the",
"number",
"of",
"seconds",
"until",
"this",
"token",
"expires",
"."
] | 6b5bc0d3ad706d2aaa47fa476f38406cddd01236 | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/oauth2/models.py#L149-L166 | train | 28,620 |
caffeinehit/django-oauth2-provider | provider/forms.py | OAuthForm._clean_fields | def _clean_fields(self):
"""
Overriding the default cleaning behaviour to exit early on errors
instead of validating each field.
"""
try:
super(OAuthForm, self)._clean_fields()
except OAuthValidationError, e:
self._errors.update(e.args[0]) | python | def _clean_fields(self):
"""
Overriding the default cleaning behaviour to exit early on errors
instead of validating each field.
"""
try:
super(OAuthForm, self)._clean_fields()
except OAuthValidationError, e:
self._errors.update(e.args[0]) | [
"def",
"_clean_fields",
"(",
"self",
")",
":",
"try",
":",
"super",
"(",
"OAuthForm",
",",
"self",
")",
".",
"_clean_fields",
"(",
")",
"except",
"OAuthValidationError",
",",
"e",
":",
"self",
".",
"_errors",
".",
"update",
"(",
"e",
".",
"args",
"[",
... | Overriding the default cleaning behaviour to exit early on errors
instead of validating each field. | [
"Overriding",
"the",
"default",
"cleaning",
"behaviour",
"to",
"exit",
"early",
"on",
"errors",
"instead",
"of",
"validating",
"each",
"field",
"."
] | 6b5bc0d3ad706d2aaa47fa476f38406cddd01236 | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/forms.py#L47-L55 | train | 28,621 |
caffeinehit/django-oauth2-provider | provider/sphinx.py | rfclink | def rfclink(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Link to the OAuth2 draft.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called us.
:param options: Directive options for customization.
:param content: The directive content for customization.
"""
node = nodes.reference(rawtext, "Section " + text, refuri="%s#section-%s" % (base_url, text))
return [node], [] | python | def rfclink(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Link to the OAuth2 draft.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called us.
:param options: Directive options for customization.
:param content: The directive content for customization.
"""
node = nodes.reference(rawtext, "Section " + text, refuri="%s#section-%s" % (base_url, text))
return [node], [] | [
"def",
"rfclink",
"(",
"name",
",",
"rawtext",
",",
"text",
",",
"lineno",
",",
"inliner",
",",
"options",
"=",
"{",
"}",
",",
"content",
"=",
"[",
"]",
")",
":",
"node",
"=",
"nodes",
".",
"reference",
"(",
"rawtext",
",",
"\"Section \"",
"+",
"te... | Link to the OAuth2 draft.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:param rawtext: The entire markup snippet, with role.
:param text: The text marked with the role.
:param lineno: The line number where rawtext appears in the input.
:param inliner: The inliner instance that called us.
:param options: Directive options for customization.
:param content: The directive content for customization. | [
"Link",
"to",
"the",
"OAuth2",
"draft",
"."
] | 6b5bc0d3ad706d2aaa47fa476f38406cddd01236 | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/sphinx.py#L8-L26 | train | 28,622 |
caffeinehit/django-oauth2-provider | provider/oauth2/forms.py | ScopeChoiceField.validate | def validate(self, value):
"""
Validates that the input is a list or tuple.
"""
if self.required and not value:
raise OAuthValidationError({'error': 'invalid_request'})
# Validate that each value in the value list is in self.choices.
for val in value:
if not self.valid_value(val):
raise OAuthValidationError({
'error': 'invalid_request',
'error_description': _("'%s' is not a valid scope.") % \
val}) | python | def validate(self, value):
"""
Validates that the input is a list or tuple.
"""
if self.required and not value:
raise OAuthValidationError({'error': 'invalid_request'})
# Validate that each value in the value list is in self.choices.
for val in value:
if not self.valid_value(val):
raise OAuthValidationError({
'error': 'invalid_request',
'error_description': _("'%s' is not a valid scope.") % \
val}) | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"required",
"and",
"not",
"value",
":",
"raise",
"OAuthValidationError",
"(",
"{",
"'error'",
":",
"'invalid_request'",
"}",
")",
"# Validate that each value in the value list is in self.choi... | Validates that the input is a list or tuple. | [
"Validates",
"that",
"the",
"input",
"is",
"a",
"list",
"or",
"tuple",
"."
] | 6b5bc0d3ad706d2aaa47fa476f38406cddd01236 | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/oauth2/forms.py#L70-L83 | train | 28,623 |
caffeinehit/django-oauth2-provider | provider/oauth2/forms.py | ScopeMixin.clean_scope | def clean_scope(self):
"""
The scope is assembled by combining all the set flags into a single
integer value which we can later check again for set bits.
If *no* scope is set, we return the default scope which is the first
defined scope in :attr:`provider.constants.SCOPES`.
"""
default = SCOPES[0][0]
flags = self.cleaned_data.get('scope', [])
return scope.to_int(default=default, *flags) | python | def clean_scope(self):
"""
The scope is assembled by combining all the set flags into a single
integer value which we can later check again for set bits.
If *no* scope is set, we return the default scope which is the first
defined scope in :attr:`provider.constants.SCOPES`.
"""
default = SCOPES[0][0]
flags = self.cleaned_data.get('scope', [])
return scope.to_int(default=default, *flags) | [
"def",
"clean_scope",
"(",
"self",
")",
":",
"default",
"=",
"SCOPES",
"[",
"0",
"]",
"[",
"0",
"]",
"flags",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"'scope'",
",",
"[",
"]",
")",
"return",
"scope",
".",
"to_int",
"(",
"default",
"=",
... | The scope is assembled by combining all the set flags into a single
integer value which we can later check again for set bits.
If *no* scope is set, we return the default scope which is the first
defined scope in :attr:`provider.constants.SCOPES`. | [
"The",
"scope",
"is",
"assembled",
"by",
"combining",
"all",
"the",
"set",
"flags",
"into",
"a",
"single",
"integer",
"value",
"which",
"we",
"can",
"later",
"check",
"again",
"for",
"set",
"bits",
"."
] | 6b5bc0d3ad706d2aaa47fa476f38406cddd01236 | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/oauth2/forms.py#L90-L103 | train | 28,624 |
caffeinehit/django-oauth2-provider | provider/oauth2/forms.py | RefreshTokenGrantForm.clean | def clean(self):
"""
Make sure that the scope is less or equal to the previous scope!
"""
data = self.cleaned_data
want_scope = data.get('scope') or 0
refresh_token = data.get('refresh_token')
access_token = getattr(refresh_token, 'access_token', None) if \
refresh_token else \
None
has_scope = access_token.scope if access_token else 0
# Only check if we've actually got a scope in the data
# (read: All fields have been cleaned)
if want_scope is not 0 and not scope.check(want_scope, has_scope):
raise OAuthValidationError({'error': 'invalid_scope'})
return data | python | def clean(self):
"""
Make sure that the scope is less or equal to the previous scope!
"""
data = self.cleaned_data
want_scope = data.get('scope') or 0
refresh_token = data.get('refresh_token')
access_token = getattr(refresh_token, 'access_token', None) if \
refresh_token else \
None
has_scope = access_token.scope if access_token else 0
# Only check if we've actually got a scope in the data
# (read: All fields have been cleaned)
if want_scope is not 0 and not scope.check(want_scope, has_scope):
raise OAuthValidationError({'error': 'invalid_scope'})
return data | [
"def",
"clean",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"cleaned_data",
"want_scope",
"=",
"data",
".",
"get",
"(",
"'scope'",
")",
"or",
"0",
"refresh_token",
"=",
"data",
".",
"get",
"(",
"'refresh_token'",
")",
"access_token",
"=",
"getattr",... | Make sure that the scope is less or equal to the previous scope! | [
"Make",
"sure",
"that",
"the",
"scope",
"is",
"less",
"or",
"equal",
"to",
"the",
"previous",
"scope!"
] | 6b5bc0d3ad706d2aaa47fa476f38406cddd01236 | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/oauth2/forms.py#L215-L232 | train | 28,625 |
caffeinehit/django-oauth2-provider | provider/oauth2/forms.py | AuthorizationCodeGrantForm.clean | def clean(self):
"""
Make sure that the scope is less or equal to the scope allowed on the
grant!
"""
data = self.cleaned_data
want_scope = data.get('scope') or 0
grant = data.get('grant')
has_scope = grant.scope if grant else 0
# Only check if we've actually got a scope in the data
# (read: All fields have been cleaned)
if want_scope is not 0 and not scope.check(want_scope, has_scope):
raise OAuthValidationError({'error': 'invalid_scope'})
return data | python | def clean(self):
"""
Make sure that the scope is less or equal to the scope allowed on the
grant!
"""
data = self.cleaned_data
want_scope = data.get('scope') or 0
grant = data.get('grant')
has_scope = grant.scope if grant else 0
# Only check if we've actually got a scope in the data
# (read: All fields have been cleaned)
if want_scope is not 0 and not scope.check(want_scope, has_scope):
raise OAuthValidationError({'error': 'invalid_scope'})
return data | [
"def",
"clean",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"cleaned_data",
"want_scope",
"=",
"data",
".",
"get",
"(",
"'scope'",
")",
"or",
"0",
"grant",
"=",
"data",
".",
"get",
"(",
"'grant'",
")",
"has_scope",
"=",
"grant",
".",
"scope",
... | Make sure that the scope is less or equal to the scope allowed on the
grant! | [
"Make",
"sure",
"that",
"the",
"scope",
"is",
"less",
"or",
"equal",
"to",
"the",
"scope",
"allowed",
"on",
"the",
"grant!"
] | 6b5bc0d3ad706d2aaa47fa476f38406cddd01236 | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/oauth2/forms.py#L256-L271 | train | 28,626 |
caffeinehit/django-oauth2-provider | provider/utils.py | short_token | def short_token():
"""
Generate a hash that can be used as an application identifier
"""
hash = hashlib.sha1(shortuuid.uuid())
hash.update(settings.SECRET_KEY)
return hash.hexdigest()[::2] | python | def short_token():
"""
Generate a hash that can be used as an application identifier
"""
hash = hashlib.sha1(shortuuid.uuid())
hash.update(settings.SECRET_KEY)
return hash.hexdigest()[::2] | [
"def",
"short_token",
"(",
")",
":",
"hash",
"=",
"hashlib",
".",
"sha1",
"(",
"shortuuid",
".",
"uuid",
"(",
")",
")",
"hash",
".",
"update",
"(",
"settings",
".",
"SECRET_KEY",
")",
"return",
"hash",
".",
"hexdigest",
"(",
")",
"[",
":",
":",
"2"... | Generate a hash that can be used as an application identifier | [
"Generate",
"a",
"hash",
"that",
"can",
"be",
"used",
"as",
"an",
"application",
"identifier"
] | 6b5bc0d3ad706d2aaa47fa476f38406cddd01236 | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/utils.py#L30-L36 | train | 28,627 |
caffeinehit/django-oauth2-provider | provider/utils.py | deserialize_instance | def deserialize_instance(model, data={}):
"Translate raw data into a model instance."
ret = model()
for k, v in data.items():
if v is not None:
try:
f = model._meta.get_field(k)
if isinstance(f, DateTimeField):
v = dateparse.parse_datetime(v)
elif isinstance(f, TimeField):
v = dateparse.parse_time(v)
elif isinstance(f, DateField):
v = dateparse.parse_date(v)
except FieldDoesNotExist:
pass
setattr(ret, k, v)
return ret | python | def deserialize_instance(model, data={}):
"Translate raw data into a model instance."
ret = model()
for k, v in data.items():
if v is not None:
try:
f = model._meta.get_field(k)
if isinstance(f, DateTimeField):
v = dateparse.parse_datetime(v)
elif isinstance(f, TimeField):
v = dateparse.parse_time(v)
elif isinstance(f, DateField):
v = dateparse.parse_date(v)
except FieldDoesNotExist:
pass
setattr(ret, k, v)
return ret | [
"def",
"deserialize_instance",
"(",
"model",
",",
"data",
"=",
"{",
"}",
")",
":",
"ret",
"=",
"model",
"(",
")",
"for",
"k",
",",
"v",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"v",
"is",
"not",
"None",
":",
"try",
":",
"f",
"=",
"mod... | Translate raw data into a model instance. | [
"Translate",
"raw",
"data",
"into",
"a",
"model",
"instance",
"."
] | 6b5bc0d3ad706d2aaa47fa476f38406cddd01236 | https://github.com/caffeinehit/django-oauth2-provider/blob/6b5bc0d3ad706d2aaa47fa476f38406cddd01236/provider/utils.py#L84-L100 | train | 28,628 |
twitterdev/tweet_parser | tweet_parser/getter_methods/tweet_entities.py | get_media_urls | def get_media_urls(tweet):
"""
Gets the https links to each media entity in the tweet.
Args:
tweet (Tweet or dict): tweet
Returns:
list: list of urls. Will be an empty list if there are no urls present.
Example:
>>> from tweet_parser.getter_methods.tweet_entities import get_media_urls
>>> tweet = {'created_at': '2017-21-23T15:21:21.000Z',
... 'entities': {'user_mentions': [{'id': 2382763597,
... 'id_str': '2382763597',
... 'indices': [14, 26],
... 'name': 'Fiona',
... 'screen_name': 'notFromShrek'}]},
... 'extended_entities': {'media': [{'display_url': 'pic.twitter.com/something',
... 'expanded_url': 'https://twitter.com/something',
... 'id': 4242,
... 'id_str': '4242',
... 'indices': [88, 111],
... 'media_url': 'http://pbs.twimg.com/media/something.jpg',
... 'media_url_https': 'https://pbs.twimg.com/media/something.jpg',
... 'sizes': {'large': {'h': 1065, 'resize': 'fit', 'w': 1600},
... 'medium': {'h': 799, 'resize': 'fit', 'w': 1200},
... 'small': {'h': 453, 'resize': 'fit', 'w': 680},
... 'thumb': {'h': 150, 'resize': 'crop', 'w': 150}},
... 'type': 'photo',
... 'url': 'https://t.co/something'},
... {'display_url': 'pic.twitter.com/something_else',
... 'expanded_url': 'https://twitter.com/user/status/something/photo/1',
... 'id': 4243,
... 'id_str': '4243',
... 'indices': [88, 111],
... 'media_url': 'http://pbs.twimg.com/media/something_else.jpg',
... 'media_url_https': 'https://pbs.twimg.com/media/something_else.jpg',
... 'sizes': {'large': {'h': 1065, 'resize': 'fit', 'w': 1600},
... 'medium': {'h': 799, 'resize': 'fit', 'w': 1200},
... 'small': {'h': 453, 'resize': 'fit', 'w': 680},
... 'thumb': {'h': 150, 'resize': 'crop', 'w': 150}},
... 'type': 'photo',
... 'url': 'https://t.co/something_else'}]}
... }
>>> get_media_urls(tweet)
['https://pbs.twimg.com/media/something.jpg', 'https://pbs.twimg.com/media/something_else.jpg']
"""
media = get_media_entities(tweet)
urls = [m.get("media_url_https") for m in media] if media else []
return urls | python | def get_media_urls(tweet):
"""
Gets the https links to each media entity in the tweet.
Args:
tweet (Tweet or dict): tweet
Returns:
list: list of urls. Will be an empty list if there are no urls present.
Example:
>>> from tweet_parser.getter_methods.tweet_entities import get_media_urls
>>> tweet = {'created_at': '2017-21-23T15:21:21.000Z',
... 'entities': {'user_mentions': [{'id': 2382763597,
... 'id_str': '2382763597',
... 'indices': [14, 26],
... 'name': 'Fiona',
... 'screen_name': 'notFromShrek'}]},
... 'extended_entities': {'media': [{'display_url': 'pic.twitter.com/something',
... 'expanded_url': 'https://twitter.com/something',
... 'id': 4242,
... 'id_str': '4242',
... 'indices': [88, 111],
... 'media_url': 'http://pbs.twimg.com/media/something.jpg',
... 'media_url_https': 'https://pbs.twimg.com/media/something.jpg',
... 'sizes': {'large': {'h': 1065, 'resize': 'fit', 'w': 1600},
... 'medium': {'h': 799, 'resize': 'fit', 'w': 1200},
... 'small': {'h': 453, 'resize': 'fit', 'w': 680},
... 'thumb': {'h': 150, 'resize': 'crop', 'w': 150}},
... 'type': 'photo',
... 'url': 'https://t.co/something'},
... {'display_url': 'pic.twitter.com/something_else',
... 'expanded_url': 'https://twitter.com/user/status/something/photo/1',
... 'id': 4243,
... 'id_str': '4243',
... 'indices': [88, 111],
... 'media_url': 'http://pbs.twimg.com/media/something_else.jpg',
... 'media_url_https': 'https://pbs.twimg.com/media/something_else.jpg',
... 'sizes': {'large': {'h': 1065, 'resize': 'fit', 'w': 1600},
... 'medium': {'h': 799, 'resize': 'fit', 'w': 1200},
... 'small': {'h': 453, 'resize': 'fit', 'w': 680},
... 'thumb': {'h': 150, 'resize': 'crop', 'w': 150}},
... 'type': 'photo',
... 'url': 'https://t.co/something_else'}]}
... }
>>> get_media_urls(tweet)
['https://pbs.twimg.com/media/something.jpg', 'https://pbs.twimg.com/media/something_else.jpg']
"""
media = get_media_entities(tweet)
urls = [m.get("media_url_https") for m in media] if media else []
return urls | [
"def",
"get_media_urls",
"(",
"tweet",
")",
":",
"media",
"=",
"get_media_entities",
"(",
"tweet",
")",
"urls",
"=",
"[",
"m",
".",
"get",
"(",
"\"media_url_https\"",
")",
"for",
"m",
"in",
"media",
"]",
"if",
"media",
"else",
"[",
"]",
"return",
"urls... | Gets the https links to each media entity in the tweet.
Args:
tweet (Tweet or dict): tweet
Returns:
list: list of urls. Will be an empty list if there are no urls present.
Example:
>>> from tweet_parser.getter_methods.tweet_entities import get_media_urls
>>> tweet = {'created_at': '2017-21-23T15:21:21.000Z',
... 'entities': {'user_mentions': [{'id': 2382763597,
... 'id_str': '2382763597',
... 'indices': [14, 26],
... 'name': 'Fiona',
... 'screen_name': 'notFromShrek'}]},
... 'extended_entities': {'media': [{'display_url': 'pic.twitter.com/something',
... 'expanded_url': 'https://twitter.com/something',
... 'id': 4242,
... 'id_str': '4242',
... 'indices': [88, 111],
... 'media_url': 'http://pbs.twimg.com/media/something.jpg',
... 'media_url_https': 'https://pbs.twimg.com/media/something.jpg',
... 'sizes': {'large': {'h': 1065, 'resize': 'fit', 'w': 1600},
... 'medium': {'h': 799, 'resize': 'fit', 'w': 1200},
... 'small': {'h': 453, 'resize': 'fit', 'w': 680},
... 'thumb': {'h': 150, 'resize': 'crop', 'w': 150}},
... 'type': 'photo',
... 'url': 'https://t.co/something'},
... {'display_url': 'pic.twitter.com/something_else',
... 'expanded_url': 'https://twitter.com/user/status/something/photo/1',
... 'id': 4243,
... 'id_str': '4243',
... 'indices': [88, 111],
... 'media_url': 'http://pbs.twimg.com/media/something_else.jpg',
... 'media_url_https': 'https://pbs.twimg.com/media/something_else.jpg',
... 'sizes': {'large': {'h': 1065, 'resize': 'fit', 'w': 1600},
... 'medium': {'h': 799, 'resize': 'fit', 'w': 1200},
... 'small': {'h': 453, 'resize': 'fit', 'w': 680},
... 'thumb': {'h': 150, 'resize': 'crop', 'w': 150}},
... 'type': 'photo',
... 'url': 'https://t.co/something_else'}]}
... }
>>> get_media_urls(tweet)
['https://pbs.twimg.com/media/something.jpg', 'https://pbs.twimg.com/media/something_else.jpg'] | [
"Gets",
"the",
"https",
"links",
"to",
"each",
"media",
"entity",
"in",
"the",
"tweet",
"."
] | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/getter_methods/tweet_entities.py#L117-L168 | train | 28,629 |
twitterdev/tweet_parser | tweet_parser/getter_methods/tweet_entities.py | get_hashtags | def get_hashtags(tweet):
"""
Get a list of hashtags in the Tweet
Note that in the case of a quote-tweet, this does not return the
hashtags in the quoted status.
Args:
tweet (Tweet or dict): A Tweet object or dictionary
Returns:
list (a list of strings): list of all of the hashtags in the Tweet
Example:
>>> from tweet_parser.getter_methods.tweet_entities import get_hashtags
>>> original = {"created_at": "Wed May 24 20:17:19 +0000 2017",
... "entities": {"hashtags": [{"text":"1hashtag"}]}}
>>> get_hashtags(original)
['1hashtag']
>>> activity = {"postedTime": "2017-05-24T20:17:19.000Z",
... "verb": "post",
... "twitter_entities": {"hashtags": [
... {"text":"1hashtag"},
... {"text": "moreHashtags"}]}}
>>> get_hashtags(activity)
['1hashtag', 'moreHashtags']
"""
entities = get_entities(tweet)
hashtags = entities.get("hashtags")
hashtags = [tag["text"] for tag in hashtags] if hashtags else []
return hashtags | python | def get_hashtags(tweet):
"""
Get a list of hashtags in the Tweet
Note that in the case of a quote-tweet, this does not return the
hashtags in the quoted status.
Args:
tweet (Tweet or dict): A Tweet object or dictionary
Returns:
list (a list of strings): list of all of the hashtags in the Tweet
Example:
>>> from tweet_parser.getter_methods.tweet_entities import get_hashtags
>>> original = {"created_at": "Wed May 24 20:17:19 +0000 2017",
... "entities": {"hashtags": [{"text":"1hashtag"}]}}
>>> get_hashtags(original)
['1hashtag']
>>> activity = {"postedTime": "2017-05-24T20:17:19.000Z",
... "verb": "post",
... "twitter_entities": {"hashtags": [
... {"text":"1hashtag"},
... {"text": "moreHashtags"}]}}
>>> get_hashtags(activity)
['1hashtag', 'moreHashtags']
"""
entities = get_entities(tweet)
hashtags = entities.get("hashtags")
hashtags = [tag["text"] for tag in hashtags] if hashtags else []
return hashtags | [
"def",
"get_hashtags",
"(",
"tweet",
")",
":",
"entities",
"=",
"get_entities",
"(",
"tweet",
")",
"hashtags",
"=",
"entities",
".",
"get",
"(",
"\"hashtags\"",
")",
"hashtags",
"=",
"[",
"tag",
"[",
"\"text\"",
"]",
"for",
"tag",
"in",
"hashtags",
"]",
... | Get a list of hashtags in the Tweet
Note that in the case of a quote-tweet, this does not return the
hashtags in the quoted status.
Args:
tweet (Tweet or dict): A Tweet object or dictionary
Returns:
list (a list of strings): list of all of the hashtags in the Tweet
Example:
>>> from tweet_parser.getter_methods.tweet_entities import get_hashtags
>>> original = {"created_at": "Wed May 24 20:17:19 +0000 2017",
... "entities": {"hashtags": [{"text":"1hashtag"}]}}
>>> get_hashtags(original)
['1hashtag']
>>> activity = {"postedTime": "2017-05-24T20:17:19.000Z",
... "verb": "post",
... "twitter_entities": {"hashtags": [
... {"text":"1hashtag"},
... {"text": "moreHashtags"}]}}
>>> get_hashtags(activity)
['1hashtag', 'moreHashtags'] | [
"Get",
"a",
"list",
"of",
"hashtags",
"in",
"the",
"Tweet",
"Note",
"that",
"in",
"the",
"case",
"of",
"a",
"quote",
"-",
"tweet",
"this",
"does",
"not",
"return",
"the",
"hashtags",
"in",
"the",
"quoted",
"status",
"."
] | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/getter_methods/tweet_entities.py#L215-L245 | train | 28,630 |
twitterdev/tweet_parser | tweet_parser/getter_methods/tweet_embeds.py | get_embedded_tweet | def get_embedded_tweet(tweet):
"""
Get the retweeted Tweet OR the quoted Tweet and return it as a dictionary
Args:
tweet (Tweet): A Tweet object (not simply a dict)
Returns:
dict (or None, if the Tweet is neither a quote tweet or a Retweet):
a dictionary representing the quote Tweet or the Retweet
"""
if tweet.retweeted_tweet is not None:
return tweet.retweeted_tweet
elif tweet.quoted_tweet is not None:
return tweet.quoted_tweet
else:
return None | python | def get_embedded_tweet(tweet):
"""
Get the retweeted Tweet OR the quoted Tweet and return it as a dictionary
Args:
tweet (Tweet): A Tweet object (not simply a dict)
Returns:
dict (or None, if the Tweet is neither a quote tweet or a Retweet):
a dictionary representing the quote Tweet or the Retweet
"""
if tweet.retweeted_tweet is not None:
return tweet.retweeted_tweet
elif tweet.quoted_tweet is not None:
return tweet.quoted_tweet
else:
return None | [
"def",
"get_embedded_tweet",
"(",
"tweet",
")",
":",
"if",
"tweet",
".",
"retweeted_tweet",
"is",
"not",
"None",
":",
"return",
"tweet",
".",
"retweeted_tweet",
"elif",
"tweet",
".",
"quoted_tweet",
"is",
"not",
"None",
":",
"return",
"tweet",
".",
"quoted_t... | Get the retweeted Tweet OR the quoted Tweet and return it as a dictionary
Args:
tweet (Tweet): A Tweet object (not simply a dict)
Returns:
dict (or None, if the Tweet is neither a quote tweet or a Retweet):
a dictionary representing the quote Tweet or the Retweet | [
"Get",
"the",
"retweeted",
"Tweet",
"OR",
"the",
"quoted",
"Tweet",
"and",
"return",
"it",
"as",
"a",
"dictionary"
] | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/getter_methods/tweet_embeds.py#L55-L71 | train | 28,631 |
twitterdev/tweet_parser | tweet_parser/getter_methods/tweet_user.py | get_bio | def get_bio(tweet):
"""
Get the bio text of the user who posted the Tweet
Args:
tweet (Tweet): A Tweet object (or a dictionary)
Returns:
str: the bio text of the user who posted the Tweet
In a payload the abscence of a bio seems to be represented by an
empty string or a None, this getter always returns a string (so, empty
string if no bio is available).
Example:
>>> from tweet_parser.getter_methods.tweet_user import get_bio
>>> original_format_dict = {
... "created_at": "Wed May 24 20:17:19 +0000 2017",
... "user":
... {"description": "Niche millenial content aggregator"}
... }
>>> get_bio(original_format_dict)
'Niche millenial content aggregator'
>>> activity_streams_format_dict = {
... "postedTime": "2017-05-24T20:17:19.000Z",
... "actor":
... {"summary": "Niche millenial content aggregator"}
... }
>>> get_bio(activity_streams_format_dict)
'Niche millenial content aggregator'
"""
if is_original_format(tweet):
bio_or_none = tweet["user"].get("description", "")
else:
bio_or_none = tweet["actor"].get("summary", "")
if bio_or_none is None:
return ""
else:
return bio_or_none | python | def get_bio(tweet):
"""
Get the bio text of the user who posted the Tweet
Args:
tweet (Tweet): A Tweet object (or a dictionary)
Returns:
str: the bio text of the user who posted the Tweet
In a payload the abscence of a bio seems to be represented by an
empty string or a None, this getter always returns a string (so, empty
string if no bio is available).
Example:
>>> from tweet_parser.getter_methods.tweet_user import get_bio
>>> original_format_dict = {
... "created_at": "Wed May 24 20:17:19 +0000 2017",
... "user":
... {"description": "Niche millenial content aggregator"}
... }
>>> get_bio(original_format_dict)
'Niche millenial content aggregator'
>>> activity_streams_format_dict = {
... "postedTime": "2017-05-24T20:17:19.000Z",
... "actor":
... {"summary": "Niche millenial content aggregator"}
... }
>>> get_bio(activity_streams_format_dict)
'Niche millenial content aggregator'
"""
if is_original_format(tweet):
bio_or_none = tweet["user"].get("description", "")
else:
bio_or_none = tweet["actor"].get("summary", "")
if bio_or_none is None:
return ""
else:
return bio_or_none | [
"def",
"get_bio",
"(",
"tweet",
")",
":",
"if",
"is_original_format",
"(",
"tweet",
")",
":",
"bio_or_none",
"=",
"tweet",
"[",
"\"user\"",
"]",
".",
"get",
"(",
"\"description\"",
",",
"\"\"",
")",
"else",
":",
"bio_or_none",
"=",
"tweet",
"[",
"\"actor... | Get the bio text of the user who posted the Tweet
Args:
tweet (Tweet): A Tweet object (or a dictionary)
Returns:
str: the bio text of the user who posted the Tweet
In a payload the abscence of a bio seems to be represented by an
empty string or a None, this getter always returns a string (so, empty
string if no bio is available).
Example:
>>> from tweet_parser.getter_methods.tweet_user import get_bio
>>> original_format_dict = {
... "created_at": "Wed May 24 20:17:19 +0000 2017",
... "user":
... {"description": "Niche millenial content aggregator"}
... }
>>> get_bio(original_format_dict)
'Niche millenial content aggregator'
>>> activity_streams_format_dict = {
... "postedTime": "2017-05-24T20:17:19.000Z",
... "actor":
... {"summary": "Niche millenial content aggregator"}
... }
>>> get_bio(activity_streams_format_dict)
'Niche millenial content aggregator' | [
"Get",
"the",
"bio",
"text",
"of",
"the",
"user",
"who",
"posted",
"the",
"Tweet"
] | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/getter_methods/tweet_user.py#L114-L153 | train | 28,632 |
twitterdev/tweet_parser | tweet_parser/tweet_checking.py | is_original_format | def is_original_format(tweet):
"""
Simple checker to flag the format of a tweet.
Args:
tweet (Tweet): tweet in qustion
Returns:
Bool
Example:
>>> import tweet_parser.tweet_checking as tc
>>> tweet = {"created_at": 124125125125,
... "text": "just setting up my twttr",
... "nested_field": {"nested_1": "field", "nested_2": "field2"}}
>>> tc.is_original_format(tweet)
True
"""
# deleted due to excess checking; it's a key lookup and does not need any
# operational optimization
if "created_at" in tweet:
original_format = True
elif "postedTime" in tweet:
original_format = False
else:
raise NotATweetError("This dict has neither 'created_at' or 'postedTime' as keys")
return original_format | python | def is_original_format(tweet):
"""
Simple checker to flag the format of a tweet.
Args:
tweet (Tweet): tweet in qustion
Returns:
Bool
Example:
>>> import tweet_parser.tweet_checking as tc
>>> tweet = {"created_at": 124125125125,
... "text": "just setting up my twttr",
... "nested_field": {"nested_1": "field", "nested_2": "field2"}}
>>> tc.is_original_format(tweet)
True
"""
# deleted due to excess checking; it's a key lookup and does not need any
# operational optimization
if "created_at" in tweet:
original_format = True
elif "postedTime" in tweet:
original_format = False
else:
raise NotATweetError("This dict has neither 'created_at' or 'postedTime' as keys")
return original_format | [
"def",
"is_original_format",
"(",
"tweet",
")",
":",
"# deleted due to excess checking; it's a key lookup and does not need any",
"# operational optimization",
"if",
"\"created_at\"",
"in",
"tweet",
":",
"original_format",
"=",
"True",
"elif",
"\"postedTime\"",
"in",
"tweet",
... | Simple checker to flag the format of a tweet.
Args:
tweet (Tweet): tweet in qustion
Returns:
Bool
Example:
>>> import tweet_parser.tweet_checking as tc
>>> tweet = {"created_at": 124125125125,
... "text": "just setting up my twttr",
... "nested_field": {"nested_1": "field", "nested_2": "field2"}}
>>> tc.is_original_format(tweet)
True | [
"Simple",
"checker",
"to",
"flag",
"the",
"format",
"of",
"a",
"tweet",
"."
] | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/tweet_checking.py#L17-L43 | train | 28,633 |
twitterdev/tweet_parser | tweet_parser/tweet_checking.py | get_all_keys | def get_all_keys(tweet, parent_key=''):
"""
Takes a tweet object and recursively returns a list of all keys contained
in this level and all nexstted levels of the tweet.
Args:
tweet (Tweet): the tweet dict
parent_key (str): key from which this process will start, e.g., you can
get keys only under some key that is not the top-level key.
Returns:
list of all keys in nested dicts.
Example:
>>> import tweet_parser.tweet_checking as tc
>>> tweet = {"created_at": 124125125125, "text": "just setting up my twttr",
... "nested_field": {"nested_1": "field", "nested_2": "field2"}}
>>> tc.get_all_keys(tweet)
['created_at', 'text', 'nested_field nested_1', 'nested_field nested_2']
"""
items = []
for k, v in tweet.items():
new_key = parent_key + " " + k
if isinstance(v, dict):
items.extend(get_all_keys(v, parent_key=new_key))
else:
items.append(new_key.strip(" "))
return items | python | def get_all_keys(tweet, parent_key=''):
"""
Takes a tweet object and recursively returns a list of all keys contained
in this level and all nexstted levels of the tweet.
Args:
tweet (Tweet): the tweet dict
parent_key (str): key from which this process will start, e.g., you can
get keys only under some key that is not the top-level key.
Returns:
list of all keys in nested dicts.
Example:
>>> import tweet_parser.tweet_checking as tc
>>> tweet = {"created_at": 124125125125, "text": "just setting up my twttr",
... "nested_field": {"nested_1": "field", "nested_2": "field2"}}
>>> tc.get_all_keys(tweet)
['created_at', 'text', 'nested_field nested_1', 'nested_field nested_2']
"""
items = []
for k, v in tweet.items():
new_key = parent_key + " " + k
if isinstance(v, dict):
items.extend(get_all_keys(v, parent_key=new_key))
else:
items.append(new_key.strip(" "))
return items | [
"def",
"get_all_keys",
"(",
"tweet",
",",
"parent_key",
"=",
"''",
")",
":",
"items",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"tweet",
".",
"items",
"(",
")",
":",
"new_key",
"=",
"parent_key",
"+",
"\" \"",
"+",
"k",
"if",
"isinstance",
"(",
... | Takes a tweet object and recursively returns a list of all keys contained
in this level and all nexstted levels of the tweet.
Args:
tweet (Tweet): the tweet dict
parent_key (str): key from which this process will start, e.g., you can
get keys only under some key that is not the top-level key.
Returns:
list of all keys in nested dicts.
Example:
>>> import tweet_parser.tweet_checking as tc
>>> tweet = {"created_at": 124125125125, "text": "just setting up my twttr",
... "nested_field": {"nested_1": "field", "nested_2": "field2"}}
>>> tc.get_all_keys(tweet)
['created_at', 'text', 'nested_field nested_1', 'nested_field nested_2'] | [
"Takes",
"a",
"tweet",
"object",
"and",
"recursively",
"returns",
"a",
"list",
"of",
"all",
"keys",
"contained",
"in",
"this",
"level",
"and",
"all",
"nexstted",
"levels",
"of",
"the",
"tweet",
"."
] | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/tweet_checking.py#L46-L73 | train | 28,634 |
twitterdev/tweet_parser | tweet_parser/tweet_checking.py | key_validation_check | def key_validation_check(tweet_keys_list, superset_keys, minset_keys):
"""
Validates the keys present in a Tweet.
Args:
tweet_keys_list (list): the keys present in a tweet
superset_keys (set): the set of all possible keys for a tweet
minset_keys (set): the set of minimal keys expected in a tweet.
Returns:
0 if no errors
Raises:
UnexpectedFormatError on any mismatch of keys.
"""
# check for keys that must be present
tweet_keys = set(tweet_keys_list)
minset_overlap = tweet_keys & minset_keys
if minset_overlap != minset_keys:
raise UnexpectedFormatError("keys ({}) missing from Tweet (Public API data is not supported)"
.format(minset_keys - tweet_keys))
# check for keys that could be present
unexpected_keys = tweet_keys - superset_keys
if len(unexpected_keys) > 0:
raise UnexpectedFormatError("Unexpected keys ({}) are in this Tweet"
.format(unexpected_keys))
return 0 | python | def key_validation_check(tweet_keys_list, superset_keys, minset_keys):
"""
Validates the keys present in a Tweet.
Args:
tweet_keys_list (list): the keys present in a tweet
superset_keys (set): the set of all possible keys for a tweet
minset_keys (set): the set of minimal keys expected in a tweet.
Returns:
0 if no errors
Raises:
UnexpectedFormatError on any mismatch of keys.
"""
# check for keys that must be present
tweet_keys = set(tweet_keys_list)
minset_overlap = tweet_keys & minset_keys
if minset_overlap != minset_keys:
raise UnexpectedFormatError("keys ({}) missing from Tweet (Public API data is not supported)"
.format(minset_keys - tweet_keys))
# check for keys that could be present
unexpected_keys = tweet_keys - superset_keys
if len(unexpected_keys) > 0:
raise UnexpectedFormatError("Unexpected keys ({}) are in this Tweet"
.format(unexpected_keys))
return 0 | [
"def",
"key_validation_check",
"(",
"tweet_keys_list",
",",
"superset_keys",
",",
"minset_keys",
")",
":",
"# check for keys that must be present",
"tweet_keys",
"=",
"set",
"(",
"tweet_keys_list",
")",
"minset_overlap",
"=",
"tweet_keys",
"&",
"minset_keys",
"if",
"min... | Validates the keys present in a Tweet.
Args:
tweet_keys_list (list): the keys present in a tweet
superset_keys (set): the set of all possible keys for a tweet
minset_keys (set): the set of minimal keys expected in a tweet.
Returns:
0 if no errors
Raises:
UnexpectedFormatError on any mismatch of keys. | [
"Validates",
"the",
"keys",
"present",
"in",
"a",
"Tweet",
"."
] | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/tweet_checking.py#L76-L102 | train | 28,635 |
twitterdev/tweet_parser | tweet_parser/tweet_checking.py | check_tweet | def check_tweet(tweet, validation_checking=False):
"""
Ensures a tweet is valid and determines the type of format for the tweet.
Args:
tweet (dict/Tweet): the tweet payload
validation_checking (bool): check for valid key structure in a tweet.
"""
if "id" not in tweet:
raise NotATweetError("This text has no 'id' key")
original_format = is_original_format(tweet)
if original_format:
_check_original_format_tweet(tweet, validation_checking=validation_checking)
else:
_check_activity_streams_tweet(tweet, validation_checking=validation_checking)
return original_format | python | def check_tweet(tweet, validation_checking=False):
"""
Ensures a tweet is valid and determines the type of format for the tweet.
Args:
tweet (dict/Tweet): the tweet payload
validation_checking (bool): check for valid key structure in a tweet.
"""
if "id" not in tweet:
raise NotATweetError("This text has no 'id' key")
original_format = is_original_format(tweet)
if original_format:
_check_original_format_tweet(tweet, validation_checking=validation_checking)
else:
_check_activity_streams_tweet(tweet, validation_checking=validation_checking)
return original_format | [
"def",
"check_tweet",
"(",
"tweet",
",",
"validation_checking",
"=",
"False",
")",
":",
"if",
"\"id\"",
"not",
"in",
"tweet",
":",
"raise",
"NotATweetError",
"(",
"\"This text has no 'id' key\"",
")",
"original_format",
"=",
"is_original_format",
"(",
"tweet",
")"... | Ensures a tweet is valid and determines the type of format for the tweet.
Args:
tweet (dict/Tweet): the tweet payload
validation_checking (bool): check for valid key structure in a tweet. | [
"Ensures",
"a",
"tweet",
"is",
"valid",
"and",
"determines",
"the",
"type",
"of",
"format",
"for",
"the",
"tweet",
"."
] | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/tweet_checking.py#L129-L148 | train | 28,636 |
twitterdev/tweet_parser | tweet_parser/getter_methods/tweet_text.py | get_lang | def get_lang(tweet):
"""
Get the language that the Tweet is written in.
Args:
tweet (Tweet or dict): A Tweet object or dictionary
Returns:
str: 2-letter BCP 47 language code (or None if undefined)
Example:
>>> from tweet_parser.getter_methods.tweet_text import get_lang
>>> original = {"created_at": "Wed May 24 20:17:19 +0000 2017",
... "lang": "en"}
>>> get_lang(original)
'en'
>>> activity = {"postedTime": "2017-05-24T20:17:19.000Z",
... "twitter_lang": "en"}
>>> get_lang(activity)
'en'
"""
if is_original_format(tweet):
lang_field = "lang"
else:
lang_field = "twitter_lang"
if tweet[lang_field] is not None and tweet[lang_field] != "und":
return tweet[lang_field]
else:
return None | python | def get_lang(tweet):
"""
Get the language that the Tweet is written in.
Args:
tweet (Tweet or dict): A Tweet object or dictionary
Returns:
str: 2-letter BCP 47 language code (or None if undefined)
Example:
>>> from tweet_parser.getter_methods.tweet_text import get_lang
>>> original = {"created_at": "Wed May 24 20:17:19 +0000 2017",
... "lang": "en"}
>>> get_lang(original)
'en'
>>> activity = {"postedTime": "2017-05-24T20:17:19.000Z",
... "twitter_lang": "en"}
>>> get_lang(activity)
'en'
"""
if is_original_format(tweet):
lang_field = "lang"
else:
lang_field = "twitter_lang"
if tweet[lang_field] is not None and tweet[lang_field] != "und":
return tweet[lang_field]
else:
return None | [
"def",
"get_lang",
"(",
"tweet",
")",
":",
"if",
"is_original_format",
"(",
"tweet",
")",
":",
"lang_field",
"=",
"\"lang\"",
"else",
":",
"lang_field",
"=",
"\"twitter_lang\"",
"if",
"tweet",
"[",
"lang_field",
"]",
"is",
"not",
"None",
"and",
"tweet",
"[... | Get the language that the Tweet is written in.
Args:
tweet (Tweet or dict): A Tweet object or dictionary
Returns:
str: 2-letter BCP 47 language code (or None if undefined)
Example:
>>> from tweet_parser.getter_methods.tweet_text import get_lang
>>> original = {"created_at": "Wed May 24 20:17:19 +0000 2017",
... "lang": "en"}
>>> get_lang(original)
'en'
>>> activity = {"postedTime": "2017-05-24T20:17:19.000Z",
... "twitter_lang": "en"}
>>> get_lang(activity)
'en' | [
"Get",
"the",
"language",
"that",
"the",
"Tweet",
"is",
"written",
"in",
"."
] | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/getter_methods/tweet_text.py#L136-L165 | train | 28,637 |
twitterdev/tweet_parser | tweet_parser/getter_methods/tweet_text.py | get_poll_options | def get_poll_options(tweet):
"""
Get the text in the options of a poll as a list
- If there is no poll in the Tweet, return an empty list
- If the Tweet is in activity-streams format, raise 'NotAvailableError'
Args:
tweet (Tweet or dict): A Tweet object or dictionary
Returns:
list: list of strings, or, in the case where there is no poll,
an empty list
Raises:
NotAvailableError for activity-streams format
Example:
>>> from tweet_parser.getter_methods.tweet_text import get_poll_options
>>> original = {
... "created_at": "Wed May 24 20:17:19 +0000 2017",
... "entities": {"polls": [{"options": [{"text":"a"},
... {"text":"b"},
... {"text":"c"}]
... }]},
... }
>>> get_poll_options(original)
['a', 'b', 'c']
>>> activity = {"postedTime": "2017-05-24T20:17:19.000Z",
... "body": "some tweet text"}
>>> get_poll_options(activity)
Traceback (most recent call last):
...
NotAvailableError: Gnip activity-streams format does not return poll options
"""
if is_original_format(tweet):
try:
poll_options_text = []
for p in tweet["entities"]["polls"]:
for o in p["options"]:
poll_options_text.append(o["text"])
return poll_options_text
except KeyError:
return []
else:
raise NotAvailableError("Gnip activity-streams format does not" +
" return poll options") | python | def get_poll_options(tweet):
"""
Get the text in the options of a poll as a list
- If there is no poll in the Tweet, return an empty list
- If the Tweet is in activity-streams format, raise 'NotAvailableError'
Args:
tweet (Tweet or dict): A Tweet object or dictionary
Returns:
list: list of strings, or, in the case where there is no poll,
an empty list
Raises:
NotAvailableError for activity-streams format
Example:
>>> from tweet_parser.getter_methods.tweet_text import get_poll_options
>>> original = {
... "created_at": "Wed May 24 20:17:19 +0000 2017",
... "entities": {"polls": [{"options": [{"text":"a"},
... {"text":"b"},
... {"text":"c"}]
... }]},
... }
>>> get_poll_options(original)
['a', 'b', 'c']
>>> activity = {"postedTime": "2017-05-24T20:17:19.000Z",
... "body": "some tweet text"}
>>> get_poll_options(activity)
Traceback (most recent call last):
...
NotAvailableError: Gnip activity-streams format does not return poll options
"""
if is_original_format(tweet):
try:
poll_options_text = []
for p in tweet["entities"]["polls"]:
for o in p["options"]:
poll_options_text.append(o["text"])
return poll_options_text
except KeyError:
return []
else:
raise NotAvailableError("Gnip activity-streams format does not" +
" return poll options") | [
"def",
"get_poll_options",
"(",
"tweet",
")",
":",
"if",
"is_original_format",
"(",
"tweet",
")",
":",
"try",
":",
"poll_options_text",
"=",
"[",
"]",
"for",
"p",
"in",
"tweet",
"[",
"\"entities\"",
"]",
"[",
"\"polls\"",
"]",
":",
"for",
"o",
"in",
"p... | Get the text in the options of a poll as a list
- If there is no poll in the Tweet, return an empty list
- If the Tweet is in activity-streams format, raise 'NotAvailableError'
Args:
tweet (Tweet or dict): A Tweet object or dictionary
Returns:
list: list of strings, or, in the case where there is no poll,
an empty list
Raises:
NotAvailableError for activity-streams format
Example:
>>> from tweet_parser.getter_methods.tweet_text import get_poll_options
>>> original = {
... "created_at": "Wed May 24 20:17:19 +0000 2017",
... "entities": {"polls": [{"options": [{"text":"a"},
... {"text":"b"},
... {"text":"c"}]
... }]},
... }
>>> get_poll_options(original)
['a', 'b', 'c']
>>> activity = {"postedTime": "2017-05-24T20:17:19.000Z",
... "body": "some tweet text"}
>>> get_poll_options(activity)
Traceback (most recent call last):
...
NotAvailableError: Gnip activity-streams format does not return poll options | [
"Get",
"the",
"text",
"in",
"the",
"options",
"of",
"a",
"poll",
"as",
"a",
"list",
"-",
"If",
"there",
"is",
"no",
"poll",
"in",
"the",
"Tweet",
"return",
"an",
"empty",
"list",
"-",
"If",
"the",
"Tweet",
"is",
"in",
"activity",
"-",
"streams",
"f... | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/getter_methods/tweet_text.py#L168-L215 | train | 28,638 |
twitterdev/tweet_parser | tweet_parser/getter_methods/tweet_text.py | remove_links | def remove_links(text):
"""
Helper function to remove the links from the input text
Args:
text (str): A string
Returns:
str: the same text, but with any substring that matches the regex
for a link removed and replaced with a space
Example:
>>> from tweet_parser.getter_methods.tweet_text import remove_links
>>> text = "lorem ipsum dolor https://twitter.com/RobotPrincessFi"
>>> remove_links(text)
'lorem ipsum dolor '
"""
tco_link_regex = re.compile("https?://t.co/[A-z0-9].*")
generic_link_regex = re.compile("(https?://)?(\w*[.]\w+)+([/?=&]+\w+)*")
remove_tco = re.sub(tco_link_regex, " ", text)
remove_generic = re.sub(generic_link_regex, " ", remove_tco)
return remove_generic | python | def remove_links(text):
"""
Helper function to remove the links from the input text
Args:
text (str): A string
Returns:
str: the same text, but with any substring that matches the regex
for a link removed and replaced with a space
Example:
>>> from tweet_parser.getter_methods.tweet_text import remove_links
>>> text = "lorem ipsum dolor https://twitter.com/RobotPrincessFi"
>>> remove_links(text)
'lorem ipsum dolor '
"""
tco_link_regex = re.compile("https?://t.co/[A-z0-9].*")
generic_link_regex = re.compile("(https?://)?(\w*[.]\w+)+([/?=&]+\w+)*")
remove_tco = re.sub(tco_link_regex, " ", text)
remove_generic = re.sub(generic_link_regex, " ", remove_tco)
return remove_generic | [
"def",
"remove_links",
"(",
"text",
")",
":",
"tco_link_regex",
"=",
"re",
".",
"compile",
"(",
"\"https?://t.co/[A-z0-9].*\"",
")",
"generic_link_regex",
"=",
"re",
".",
"compile",
"(",
"\"(https?://)?(\\w*[.]\\w+)+([/?=&]+\\w+)*\"",
")",
"remove_tco",
"=",
"re",
"... | Helper function to remove the links from the input text
Args:
text (str): A string
Returns:
str: the same text, but with any substring that matches the regex
for a link removed and replaced with a space
Example:
>>> from tweet_parser.getter_methods.tweet_text import remove_links
>>> text = "lorem ipsum dolor https://twitter.com/RobotPrincessFi"
>>> remove_links(text)
'lorem ipsum dolor ' | [
"Helper",
"function",
"to",
"remove",
"the",
"links",
"from",
"the",
"input",
"text"
] | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/getter_methods/tweet_text.py#L285-L306 | train | 28,639 |
twitterdev/tweet_parser | tweet_parser/getter_methods/gnip_fields.py | get_matching_rules | def get_matching_rules(tweet):
"""
Retrieves the matching rules for a tweet with a gnip field enrichment.
Args:
tweet (Tweet): the tweet
Returns:
list: potential ``[{"tag": "user_tag", "value": "rule_value"}]``
pairs from standard rulesets or None if no rules or no
matching_rules field is found. \n
More information on this value at:
http://support.gnip.com/enrichments/matching_rules.html
"""
if is_original_format(tweet):
rules = tweet.get("matching_rules")
else:
gnip = tweet.get("gnip")
rules = gnip.get("matching_rules") if gnip else None
return rules | python | def get_matching_rules(tweet):
"""
Retrieves the matching rules for a tweet with a gnip field enrichment.
Args:
tweet (Tweet): the tweet
Returns:
list: potential ``[{"tag": "user_tag", "value": "rule_value"}]``
pairs from standard rulesets or None if no rules or no
matching_rules field is found. \n
More information on this value at:
http://support.gnip.com/enrichments/matching_rules.html
"""
if is_original_format(tweet):
rules = tweet.get("matching_rules")
else:
gnip = tweet.get("gnip")
rules = gnip.get("matching_rules") if gnip else None
return rules | [
"def",
"get_matching_rules",
"(",
"tweet",
")",
":",
"if",
"is_original_format",
"(",
"tweet",
")",
":",
"rules",
"=",
"tweet",
".",
"get",
"(",
"\"matching_rules\"",
")",
"else",
":",
"gnip",
"=",
"tweet",
".",
"get",
"(",
"\"gnip\"",
")",
"rules",
"=",... | Retrieves the matching rules for a tweet with a gnip field enrichment.
Args:
tweet (Tweet): the tweet
Returns:
list: potential ``[{"tag": "user_tag", "value": "rule_value"}]``
pairs from standard rulesets or None if no rules or no
matching_rules field is found. \n
More information on this value at:
http://support.gnip.com/enrichments/matching_rules.html | [
"Retrieves",
"the",
"matching",
"rules",
"for",
"a",
"tweet",
"with",
"a",
"gnip",
"field",
"enrichment",
"."
] | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/getter_methods/gnip_fields.py#L7-L27 | train | 28,640 |
twitterdev/tweet_parser | tweet_parser/getter_methods/tweet_geo.py | get_profile_location | def get_profile_location(tweet):
"""
Get user's derived location data from the profile location enrichment
If unavailable, returns None.
Args:
tweet (Tweet or dict): Tweet object or dictionary
Returns:
dict: more information on the profile locations enrichment here:
http://support.gnip.com/enrichments/profile_geo.html
Example:
>>> result = {"country": "US", # Two letter ISO-3166 country code
... "locality": "Boulder", # The locality location (~ city)
... "region": "Colorado", # The region location (~ state/province)
... "sub_region": "Boulder", # The sub-region location (~ county)
... "full_name": "Boulder, Colorado, US", # The full name (excluding sub-region)
... "geo": [40,-105] # lat/long value that coordinate that corresponds to
... # the lowest granularity location for where the user
... # who created the Tweet is from
... }
Caveats:
This only returns the first element of the 'locations' list.
I'm honestly not sure what circumstances would result in a list that
is more than one element long.
"""
if is_original_format(tweet):
try:
return tweet["user"]["derived"]["locations"][0]
except KeyError:
return None
else:
try:
location = tweet["gnip"]["profileLocations"][0]
reconstructed_original_format = {}
if location["address"].get("country", None) is not None:
reconstructed_original_format["country"] = location["address"]["country"]
if location["address"].get("countryCode", None) is not None:
reconstructed_original_format["country_code"] = location["address"]["countryCode"]
if location["address"].get("locality", None) is not None:
reconstructed_original_format["locality"] = location["address"]["locality"]
if location["address"].get("region", None) is not None:
reconstructed_original_format["region"] = location["address"]["region"]
if location["address"].get("subRegion", None) is not None:
reconstructed_original_format["sub_region"] = location["address"]["subRegion"]
if location.get("displayName", None) is not None:
reconstructed_original_format["full_name"] = location["displayName"]
if location.get("geo", None) is not None:
reconstructed_original_format["geo"] = location["geo"]
return reconstructed_original_format
except KeyError:
return None | python | def get_profile_location(tweet):
"""
Get user's derived location data from the profile location enrichment
If unavailable, returns None.
Args:
tweet (Tweet or dict): Tweet object or dictionary
Returns:
dict: more information on the profile locations enrichment here:
http://support.gnip.com/enrichments/profile_geo.html
Example:
>>> result = {"country": "US", # Two letter ISO-3166 country code
... "locality": "Boulder", # The locality location (~ city)
... "region": "Colorado", # The region location (~ state/province)
... "sub_region": "Boulder", # The sub-region location (~ county)
... "full_name": "Boulder, Colorado, US", # The full name (excluding sub-region)
... "geo": [40,-105] # lat/long value that coordinate that corresponds to
... # the lowest granularity location for where the user
... # who created the Tweet is from
... }
Caveats:
This only returns the first element of the 'locations' list.
I'm honestly not sure what circumstances would result in a list that
is more than one element long.
"""
if is_original_format(tweet):
try:
return tweet["user"]["derived"]["locations"][0]
except KeyError:
return None
else:
try:
location = tweet["gnip"]["profileLocations"][0]
reconstructed_original_format = {}
if location["address"].get("country", None) is not None:
reconstructed_original_format["country"] = location["address"]["country"]
if location["address"].get("countryCode", None) is not None:
reconstructed_original_format["country_code"] = location["address"]["countryCode"]
if location["address"].get("locality", None) is not None:
reconstructed_original_format["locality"] = location["address"]["locality"]
if location["address"].get("region", None) is not None:
reconstructed_original_format["region"] = location["address"]["region"]
if location["address"].get("subRegion", None) is not None:
reconstructed_original_format["sub_region"] = location["address"]["subRegion"]
if location.get("displayName", None) is not None:
reconstructed_original_format["full_name"] = location["displayName"]
if location.get("geo", None) is not None:
reconstructed_original_format["geo"] = location["geo"]
return reconstructed_original_format
except KeyError:
return None | [
"def",
"get_profile_location",
"(",
"tweet",
")",
":",
"if",
"is_original_format",
"(",
"tweet",
")",
":",
"try",
":",
"return",
"tweet",
"[",
"\"user\"",
"]",
"[",
"\"derived\"",
"]",
"[",
"\"locations\"",
"]",
"[",
"0",
"]",
"except",
"KeyError",
":",
... | Get user's derived location data from the profile location enrichment
If unavailable, returns None.
Args:
tweet (Tweet or dict): Tweet object or dictionary
Returns:
dict: more information on the profile locations enrichment here:
http://support.gnip.com/enrichments/profile_geo.html
Example:
>>> result = {"country": "US", # Two letter ISO-3166 country code
... "locality": "Boulder", # The locality location (~ city)
... "region": "Colorado", # The region location (~ state/province)
... "sub_region": "Boulder", # The sub-region location (~ county)
... "full_name": "Boulder, Colorado, US", # The full name (excluding sub-region)
... "geo": [40,-105] # lat/long value that coordinate that corresponds to
... # the lowest granularity location for where the user
... # who created the Tweet is from
... }
Caveats:
This only returns the first element of the 'locations' list.
I'm honestly not sure what circumstances would result in a list that
is more than one element long. | [
"Get",
"user",
"s",
"derived",
"location",
"data",
"from",
"the",
"profile",
"location",
"enrichment",
"If",
"unavailable",
"returns",
"None",
"."
] | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/getter_methods/tweet_geo.py#L36-L89 | train | 28,641 |
twitterdev/tweet_parser | tweet_parser/getter_methods/tweet_generator.py | get_generator | def get_generator(tweet):
"""
Get information about the application that generated the Tweet
Args:
tweet (Tweet): A Tweet object (or a dictionary)
Returns:
dict: keys are 'link' and 'name', the web link and the name
of the application
Example:
>>> from tweet_parser.getter_methods.tweet_generator import get_generator
>>> original_format_dict = {
... "created_at": "Wed May 24 20:17:19 +0000 2017",
... "source": '<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>'
... }
>>> get_generator(original_format_dict)
{'link': 'http://twitter.com', 'name': 'Twitter Web Client'}
>>> activity_streams_format_dict = {
... "postedTime": "2017-05-24T20:17:19.000Z",
... "generator":
... {"link": "http://twitter.com",
... "displayName": "Twitter Web Client"}
... }
>>> get_generator(activity_streams_format_dict)
{'link': 'http://twitter.com', 'name': 'Twitter Web Client'}
"""
if is_original_format(tweet):
if sys.version_info[0] == 3 and sys.version_info[1] >= 4:
parser = GeneratorHTMLParser(convert_charrefs=True)
else:
parser = GeneratorHTMLParser()
parser.feed(tweet["source"])
return {"link": parser.generator_link,
"name": parser.generator_name}
else:
return {"link": tweet["generator"]["link"],
"name": tweet["generator"]["displayName"]} | python | def get_generator(tweet):
"""
Get information about the application that generated the Tweet
Args:
tweet (Tweet): A Tweet object (or a dictionary)
Returns:
dict: keys are 'link' and 'name', the web link and the name
of the application
Example:
>>> from tweet_parser.getter_methods.tweet_generator import get_generator
>>> original_format_dict = {
... "created_at": "Wed May 24 20:17:19 +0000 2017",
... "source": '<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>'
... }
>>> get_generator(original_format_dict)
{'link': 'http://twitter.com', 'name': 'Twitter Web Client'}
>>> activity_streams_format_dict = {
... "postedTime": "2017-05-24T20:17:19.000Z",
... "generator":
... {"link": "http://twitter.com",
... "displayName": "Twitter Web Client"}
... }
>>> get_generator(activity_streams_format_dict)
{'link': 'http://twitter.com', 'name': 'Twitter Web Client'}
"""
if is_original_format(tweet):
if sys.version_info[0] == 3 and sys.version_info[1] >= 4:
parser = GeneratorHTMLParser(convert_charrefs=True)
else:
parser = GeneratorHTMLParser()
parser.feed(tweet["source"])
return {"link": parser.generator_link,
"name": parser.generator_name}
else:
return {"link": tweet["generator"]["link"],
"name": tweet["generator"]["displayName"]} | [
"def",
"get_generator",
"(",
"tweet",
")",
":",
"if",
"is_original_format",
"(",
"tweet",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"3",
"and",
"sys",
".",
"version_info",
"[",
"1",
"]",
">=",
"4",
":",
"parser",
"=",
"Generato... | Get information about the application that generated the Tweet
Args:
tweet (Tweet): A Tweet object (or a dictionary)
Returns:
dict: keys are 'link' and 'name', the web link and the name
of the application
Example:
>>> from tweet_parser.getter_methods.tweet_generator import get_generator
>>> original_format_dict = {
... "created_at": "Wed May 24 20:17:19 +0000 2017",
... "source": '<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>'
... }
>>> get_generator(original_format_dict)
{'link': 'http://twitter.com', 'name': 'Twitter Web Client'}
>>> activity_streams_format_dict = {
... "postedTime": "2017-05-24T20:17:19.000Z",
... "generator":
... {"link": "http://twitter.com",
... "displayName": "Twitter Web Client"}
... }
>>> get_generator(activity_streams_format_dict)
{'link': 'http://twitter.com', 'name': 'Twitter Web Client'} | [
"Get",
"information",
"about",
"the",
"application",
"that",
"generated",
"the",
"Tweet"
] | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/getter_methods/tweet_generator.py#L24-L63 | train | 28,642 |
twitterdev/tweet_parser | tweet_parser/lazy_property.py | lazy_property | def lazy_property(fn):
"""
Decorator that makes a property lazy-evaluated whilst preserving
docstrings.
Args:
fn (function): the property in question
Returns:
evaluated version of the property.
"""
attr_name = '_lazy_' + fn.__name__
@property
@wraps(fn)
def _lazy_property(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)
return _lazy_property | python | def lazy_property(fn):
"""
Decorator that makes a property lazy-evaluated whilst preserving
docstrings.
Args:
fn (function): the property in question
Returns:
evaluated version of the property.
"""
attr_name = '_lazy_' + fn.__name__
@property
@wraps(fn)
def _lazy_property(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)
return _lazy_property | [
"def",
"lazy_property",
"(",
"fn",
")",
":",
"attr_name",
"=",
"'_lazy_'",
"+",
"fn",
".",
"__name__",
"@",
"property",
"@",
"wraps",
"(",
"fn",
")",
"def",
"_lazy_property",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"attr_name",... | Decorator that makes a property lazy-evaluated whilst preserving
docstrings.
Args:
fn (function): the property in question
Returns:
evaluated version of the property. | [
"Decorator",
"that",
"makes",
"a",
"property",
"lazy",
"-",
"evaluated",
"whilst",
"preserving",
"docstrings",
"."
] | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/lazy_property.py#L13-L32 | train | 28,643 |
twitterdev/tweet_parser | tweet_parser/tweet.py | Tweet.quoted_tweet | def quoted_tweet(self):
"""
The quoted Tweet as a Tweet object
If the Tweet is not a quote Tweet, return None
If the quoted Tweet payload cannot be loaded as a Tweet, this will
raise a "NotATweetError"
Returns:
Tweet: A Tweet representing the quoted status (or None)
(see tweet_embeds.get_quote_tweet, this is that value as a Tweet)
Raises:
NotATweetError: if quoted tweet is malformed
"""
quote_tweet = tweet_embeds.get_quoted_tweet(self)
if quote_tweet is not None:
try:
return Tweet(quote_tweet)
except NotATweetError as nate:
raise(NotATweetError("The quote-tweet payload appears malformed." +
" Failed with '{}'".format(nate)))
else:
return None | python | def quoted_tweet(self):
"""
The quoted Tweet as a Tweet object
If the Tweet is not a quote Tweet, return None
If the quoted Tweet payload cannot be loaded as a Tweet, this will
raise a "NotATweetError"
Returns:
Tweet: A Tweet representing the quoted status (or None)
(see tweet_embeds.get_quote_tweet, this is that value as a Tweet)
Raises:
NotATweetError: if quoted tweet is malformed
"""
quote_tweet = tweet_embeds.get_quoted_tweet(self)
if quote_tweet is not None:
try:
return Tweet(quote_tweet)
except NotATweetError as nate:
raise(NotATweetError("The quote-tweet payload appears malformed." +
" Failed with '{}'".format(nate)))
else:
return None | [
"def",
"quoted_tweet",
"(",
"self",
")",
":",
"quote_tweet",
"=",
"tweet_embeds",
".",
"get_quoted_tweet",
"(",
"self",
")",
"if",
"quote_tweet",
"is",
"not",
"None",
":",
"try",
":",
"return",
"Tweet",
"(",
"quote_tweet",
")",
"except",
"NotATweetError",
"a... | The quoted Tweet as a Tweet object
If the Tweet is not a quote Tweet, return None
If the quoted Tweet payload cannot be loaded as a Tweet, this will
raise a "NotATweetError"
Returns:
Tweet: A Tweet representing the quoted status (or None)
(see tweet_embeds.get_quote_tweet, this is that value as a Tweet)
Raises:
NotATweetError: if quoted tweet is malformed | [
"The",
"quoted",
"Tweet",
"as",
"a",
"Tweet",
"object",
"If",
"the",
"Tweet",
"is",
"not",
"a",
"quote",
"Tweet",
"return",
"None",
"If",
"the",
"quoted",
"Tweet",
"payload",
"cannot",
"be",
"loaded",
"as",
"a",
"Tweet",
"this",
"will",
"raise",
"a",
"... | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/tweet.py#L505-L527 | train | 28,644 |
twitterdev/tweet_parser | tweet_parser/tweet.py | Tweet.retweeted_tweet | def retweeted_tweet(self):
"""
The retweeted Tweet as a Tweet object
If the Tweet is not a Retweet, return None
If the Retweet payload cannot be loaded as a Tweet, this will
raise a `NotATweetError`
Returns:
Tweet: A Tweet representing the retweeted status (or None)
(see tweet_embeds.get_retweet, this is that value as a Tweet)
Raises:
NotATweetError: if retweeted tweet is malformed
"""
retweet = tweet_embeds.get_retweeted_tweet(self)
if retweet is not None:
try:
return Tweet(retweet)
except NotATweetError as nate:
raise(NotATweetError("The retweet payload appears malformed." +
" Failed with '{}'".format(nate)))
else:
return None | python | def retweeted_tweet(self):
"""
The retweeted Tweet as a Tweet object
If the Tweet is not a Retweet, return None
If the Retweet payload cannot be loaded as a Tweet, this will
raise a `NotATweetError`
Returns:
Tweet: A Tweet representing the retweeted status (or None)
(see tweet_embeds.get_retweet, this is that value as a Tweet)
Raises:
NotATweetError: if retweeted tweet is malformed
"""
retweet = tweet_embeds.get_retweeted_tweet(self)
if retweet is not None:
try:
return Tweet(retweet)
except NotATweetError as nate:
raise(NotATweetError("The retweet payload appears malformed." +
" Failed with '{}'".format(nate)))
else:
return None | [
"def",
"retweeted_tweet",
"(",
"self",
")",
":",
"retweet",
"=",
"tweet_embeds",
".",
"get_retweeted_tweet",
"(",
"self",
")",
"if",
"retweet",
"is",
"not",
"None",
":",
"try",
":",
"return",
"Tweet",
"(",
"retweet",
")",
"except",
"NotATweetError",
"as",
... | The retweeted Tweet as a Tweet object
If the Tweet is not a Retweet, return None
If the Retweet payload cannot be loaded as a Tweet, this will
raise a `NotATweetError`
Returns:
Tweet: A Tweet representing the retweeted status (or None)
(see tweet_embeds.get_retweet, this is that value as a Tweet)
Raises:
NotATweetError: if retweeted tweet is malformed | [
"The",
"retweeted",
"Tweet",
"as",
"a",
"Tweet",
"object",
"If",
"the",
"Tweet",
"is",
"not",
"a",
"Retweet",
"return",
"None",
"If",
"the",
"Retweet",
"payload",
"cannot",
"be",
"loaded",
"as",
"a",
"Tweet",
"this",
"will",
"raise",
"a",
"NotATweetError"
... | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/tweet.py#L530-L552 | train | 28,645 |
twitterdev/tweet_parser | tweet_parser/tweet.py | Tweet.embedded_tweet | def embedded_tweet(self):
"""
Get the retweeted Tweet OR the quoted Tweet and return it as a Tweet object
Returns:
Tweet (or None, if the Tweet is neither a quote tweet or a Retweet):
a Tweet representing the quote Tweet or the Retweet
(see tweet_embeds.get_embedded_tweet, this is that value as a Tweet)
Raises:
NotATweetError: if embedded tweet is malformed
"""
embedded_tweet = tweet_embeds.get_embedded_tweet(self)
if embedded_tweet is not None:
try:
return Tweet(embedded_tweet)
except NotATweetError as nate:
raise(NotATweetError("The embedded tweet payload {} appears malformed." +
" Failed with '{}'".format(embedded_tweet, nate)))
else:
return None | python | def embedded_tweet(self):
"""
Get the retweeted Tweet OR the quoted Tweet and return it as a Tweet object
Returns:
Tweet (or None, if the Tweet is neither a quote tweet or a Retweet):
a Tweet representing the quote Tweet or the Retweet
(see tweet_embeds.get_embedded_tweet, this is that value as a Tweet)
Raises:
NotATweetError: if embedded tweet is malformed
"""
embedded_tweet = tweet_embeds.get_embedded_tweet(self)
if embedded_tweet is not None:
try:
return Tweet(embedded_tweet)
except NotATweetError as nate:
raise(NotATweetError("The embedded tweet payload {} appears malformed." +
" Failed with '{}'".format(embedded_tweet, nate)))
else:
return None | [
"def",
"embedded_tweet",
"(",
"self",
")",
":",
"embedded_tweet",
"=",
"tweet_embeds",
".",
"get_embedded_tweet",
"(",
"self",
")",
"if",
"embedded_tweet",
"is",
"not",
"None",
":",
"try",
":",
"return",
"Tweet",
"(",
"embedded_tweet",
")",
"except",
"NotATwee... | Get the retweeted Tweet OR the quoted Tweet and return it as a Tweet object
Returns:
Tweet (or None, if the Tweet is neither a quote tweet or a Retweet):
a Tweet representing the quote Tweet or the Retweet
(see tweet_embeds.get_embedded_tweet, this is that value as a Tweet)
Raises:
NotATweetError: if embedded tweet is malformed | [
"Get",
"the",
"retweeted",
"Tweet",
"OR",
"the",
"quoted",
"Tweet",
"and",
"return",
"it",
"as",
"a",
"Tweet",
"object"
] | 3435de8367d36b483a6cfd8d46cc28694ee8a42e | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/tweet.py#L555-L575 | train | 28,646 |
kibitzr/kibitzr | kibitzr/fetcher/loader.py | RequestsPromoter.is_applicable | def is_applicable(cls, conf):
"""Return whether this promoter is applicable for given conf"""
return all((
URLPromoter.is_applicable(conf),
not cls.needs_firefox(conf),
)) | python | def is_applicable(cls, conf):
"""Return whether this promoter is applicable for given conf"""
return all((
URLPromoter.is_applicable(conf),
not cls.needs_firefox(conf),
)) | [
"def",
"is_applicable",
"(",
"cls",
",",
"conf",
")",
":",
"return",
"all",
"(",
"(",
"URLPromoter",
".",
"is_applicable",
"(",
"conf",
")",
",",
"not",
"cls",
".",
"needs_firefox",
"(",
"conf",
")",
",",
")",
")"
] | Return whether this promoter is applicable for given conf | [
"Return",
"whether",
"this",
"promoter",
"is",
"applicable",
"for",
"given",
"conf"
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/fetcher/loader.py#L56-L61 | train | 28,647 |
kibitzr/kibitzr | kibitzr/transformer/html.py | xpath_selector | def xpath_selector(selector, html, select_all):
"""
Returns Xpath match for `selector` within `html`.
:param selector: XPath string
:param html: Unicode content
:param select_all: True to get all matches
"""
from defusedxml import lxml as dlxml
from lxml import etree
import re
# lxml requires argument to be bytes
# see https://github.com/kibitzr/kibitzr/issues/47
encoded = html.encode('utf-8')
root = dlxml.fromstring(encoded, parser=etree.HTMLParser())
xpath_results = root.xpath(selector)
if not xpath_results:
logger.warning('XPath selector not found: %r', selector)
return False, html
if isinstance(xpath_results, list):
if select_all is False:
xpath_results = xpath_results[0:1]
else:
xpath_results = [xpath_results]
# Serialize xpath_results
# see https://lxml.de/xpathxslt.html#xpath-return-values
results = []
for r in xpath_results:
# namespace declarations
if isinstance(r, tuple):
results.append("%s=\"%s\"" % (r[0], r[1]))
# an element
elif hasattr(r, 'tag'):
results.append(
re.sub(r'\s+', ' ',
dlxml.tostring(r, method='html', encoding='unicode'))
)
else:
results.append(r)
return True, u"\n".join(six.text_type(x).strip() for x in results) | python | def xpath_selector(selector, html, select_all):
"""
Returns Xpath match for `selector` within `html`.
:param selector: XPath string
:param html: Unicode content
:param select_all: True to get all matches
"""
from defusedxml import lxml as dlxml
from lxml import etree
import re
# lxml requires argument to be bytes
# see https://github.com/kibitzr/kibitzr/issues/47
encoded = html.encode('utf-8')
root = dlxml.fromstring(encoded, parser=etree.HTMLParser())
xpath_results = root.xpath(selector)
if not xpath_results:
logger.warning('XPath selector not found: %r', selector)
return False, html
if isinstance(xpath_results, list):
if select_all is False:
xpath_results = xpath_results[0:1]
else:
xpath_results = [xpath_results]
# Serialize xpath_results
# see https://lxml.de/xpathxslt.html#xpath-return-values
results = []
for r in xpath_results:
# namespace declarations
if isinstance(r, tuple):
results.append("%s=\"%s\"" % (r[0], r[1]))
# an element
elif hasattr(r, 'tag'):
results.append(
re.sub(r'\s+', ' ',
dlxml.tostring(r, method='html', encoding='unicode'))
)
else:
results.append(r)
return True, u"\n".join(six.text_type(x).strip() for x in results) | [
"def",
"xpath_selector",
"(",
"selector",
",",
"html",
",",
"select_all",
")",
":",
"from",
"defusedxml",
"import",
"lxml",
"as",
"dlxml",
"from",
"lxml",
"import",
"etree",
"import",
"re",
"# lxml requires argument to be bytes",
"# see https://github.com/kibitzr/kibitz... | Returns Xpath match for `selector` within `html`.
:param selector: XPath string
:param html: Unicode content
:param select_all: True to get all matches | [
"Returns",
"Xpath",
"match",
"for",
"selector",
"within",
"html",
"."
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/transformer/html.py#L70-L113 | train | 28,648 |
kibitzr/kibitzr | kibitzr/transformer/html.py | register | def register():
"""
Return dictionary of tranform factories
"""
registry = {
key: bake_html(key)
for key in ('css', 'css-all', 'tag', 'text')
}
registry['xpath'] = bake_parametrized(xpath_selector, select_all=False)
registry['xpath-all'] = bake_parametrized(xpath_selector, select_all=True)
return registry | python | def register():
"""
Return dictionary of tranform factories
"""
registry = {
key: bake_html(key)
for key in ('css', 'css-all', 'tag', 'text')
}
registry['xpath'] = bake_parametrized(xpath_selector, select_all=False)
registry['xpath-all'] = bake_parametrized(xpath_selector, select_all=True)
return registry | [
"def",
"register",
"(",
")",
":",
"registry",
"=",
"{",
"key",
":",
"bake_html",
"(",
"key",
")",
"for",
"key",
"in",
"(",
"'css'",
",",
"'css-all'",
",",
"'tag'",
",",
"'text'",
")",
"}",
"registry",
"[",
"'xpath'",
"]",
"=",
"bake_parametrized",
"(... | Return dictionary of tranform factories | [
"Return",
"dictionary",
"of",
"tranform",
"factories"
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/transformer/html.py#L137-L147 | train | 28,649 |
kibitzr/kibitzr | kibitzr/conf.py | ReloadableSettings.reread | def reread(self):
"""
Read configuration file and substitute references into checks conf
"""
logger.debug("Loading settings from %s",
os.path.abspath(self.filename))
conf = self.read_conf()
changed = self.creds.reread()
checks = self.parser.parse_checks(conf)
if self.checks != checks:
self.checks = checks
return True
else:
return changed | python | def reread(self):
"""
Read configuration file and substitute references into checks conf
"""
logger.debug("Loading settings from %s",
os.path.abspath(self.filename))
conf = self.read_conf()
changed = self.creds.reread()
checks = self.parser.parse_checks(conf)
if self.checks != checks:
self.checks = checks
return True
else:
return changed | [
"def",
"reread",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Loading settings from %s\"",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"filename",
")",
")",
"conf",
"=",
"self",
".",
"read_conf",
"(",
")",
"changed",
"=",
"self"... | Read configuration file and substitute references into checks conf | [
"Read",
"configuration",
"file",
"and",
"substitute",
"references",
"into",
"checks",
"conf"
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/conf.py#L55-L68 | train | 28,650 |
kibitzr/kibitzr | kibitzr/conf.py | PlainYamlCreds.reread | def reread(self):
"""
Read and parse credentials file.
If something goes wrong, log exception and continue.
"""
logger.debug("Loading credentials from %s",
os.path.abspath(self.creds_filename))
creds = {}
try:
with self.open_creds() as fp:
creds = yaml.safe_load(fp)
except IOError:
logger.info("No credentials file found at %s",
os.path.abspath(self.creds_filename))
except:
logger.exception("Error loading credentials file")
if creds != self.creds:
self.creds = creds
return True
return False | python | def reread(self):
"""
Read and parse credentials file.
If something goes wrong, log exception and continue.
"""
logger.debug("Loading credentials from %s",
os.path.abspath(self.creds_filename))
creds = {}
try:
with self.open_creds() as fp:
creds = yaml.safe_load(fp)
except IOError:
logger.info("No credentials file found at %s",
os.path.abspath(self.creds_filename))
except:
logger.exception("Error loading credentials file")
if creds != self.creds:
self.creds = creds
return True
return False | [
"def",
"reread",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Loading credentials from %s\"",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"creds_filename",
")",
")",
"creds",
"=",
"{",
"}",
"try",
":",
"with",
"self",
".",
"open... | Read and parse credentials file.
If something goes wrong, log exception and continue. | [
"Read",
"and",
"parse",
"credentials",
"file",
".",
"If",
"something",
"goes",
"wrong",
"log",
"exception",
"and",
"continue",
"."
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/conf.py#L135-L154 | train | 28,651 |
kibitzr/kibitzr | kibitzr/conf.py | SettingsParser.parse_checks | def parse_checks(self, conf):
"""
Unpack configuration from human-friendly form
to strict check definitions.
"""
checks = conf.get('checks', conf.get('pages', []))
checks = list(self.unpack_batches(checks))
checks = list(self.unpack_templates(checks, conf.get('templates', {})))
self.inject_missing_names(checks)
for check in checks:
self.inject_scenarios(check, conf.get('scenarios', {}))
self.inject_notifiers(check, conf.get('notifiers', {}))
self.expand_schedule(check)
return checks | python | def parse_checks(self, conf):
"""
Unpack configuration from human-friendly form
to strict check definitions.
"""
checks = conf.get('checks', conf.get('pages', []))
checks = list(self.unpack_batches(checks))
checks = list(self.unpack_templates(checks, conf.get('templates', {})))
self.inject_missing_names(checks)
for check in checks:
self.inject_scenarios(check, conf.get('scenarios', {}))
self.inject_notifiers(check, conf.get('notifiers', {}))
self.expand_schedule(check)
return checks | [
"def",
"parse_checks",
"(",
"self",
",",
"conf",
")",
":",
"checks",
"=",
"conf",
".",
"get",
"(",
"'checks'",
",",
"conf",
".",
"get",
"(",
"'pages'",
",",
"[",
"]",
")",
")",
"checks",
"=",
"list",
"(",
"self",
".",
"unpack_batches",
"(",
"checks... | Unpack configuration from human-friendly form
to strict check definitions. | [
"Unpack",
"configuration",
"from",
"human",
"-",
"friendly",
"form",
"to",
"strict",
"check",
"definitions",
"."
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/conf.py#L173-L186 | train | 28,652 |
kibitzr/kibitzr | kibitzr/bootstrap.py | create_boilerplate | def create_boilerplate():
"""
Create kibitzr.yml and kibitzr-creds.yml in current directory
if they do not exist.
"""
if not os.path.exists('kibitzr.yml'):
with open('kibitzr.yml', 'wt') as fp:
logger.info("Saving sample check in kibitzr.yml")
fp.write(KIBITZR_YML)
else:
logger.info("kibitzr.yml already exists. Skipping")
if not os.path.exists('kibitzr-creds.yml'):
with open('kibitzr-creds.yml', 'wt') as fp:
logger.info("Creating kibitzr-creds.yml")
fp.write(KIBITZR_CREDS_YML)
os.chmod('kibitzr-creds.yml', stat.S_IRUSR | stat.S_IWUSR)
else:
logger.info("kibitzr-creds.yml already exists. Skipping") | python | def create_boilerplate():
"""
Create kibitzr.yml and kibitzr-creds.yml in current directory
if they do not exist.
"""
if not os.path.exists('kibitzr.yml'):
with open('kibitzr.yml', 'wt') as fp:
logger.info("Saving sample check in kibitzr.yml")
fp.write(KIBITZR_YML)
else:
logger.info("kibitzr.yml already exists. Skipping")
if not os.path.exists('kibitzr-creds.yml'):
with open('kibitzr-creds.yml', 'wt') as fp:
logger.info("Creating kibitzr-creds.yml")
fp.write(KIBITZR_CREDS_YML)
os.chmod('kibitzr-creds.yml', stat.S_IRUSR | stat.S_IWUSR)
else:
logger.info("kibitzr-creds.yml already exists. Skipping") | [
"def",
"create_boilerplate",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"'kibitzr.yml'",
")",
":",
"with",
"open",
"(",
"'kibitzr.yml'",
",",
"'wt'",
")",
"as",
"fp",
":",
"logger",
".",
"info",
"(",
"\"Saving sample check in kibitz... | Create kibitzr.yml and kibitzr-creds.yml in current directory
if they do not exist. | [
"Create",
"kibitzr",
".",
"yml",
"and",
"kibitzr",
"-",
"creds",
".",
"yml",
"in",
"current",
"directory",
"if",
"they",
"do",
"not",
"exist",
"."
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/bootstrap.py#L33-L50 | train | 28,653 |
kibitzr/kibitzr | kibitzr/fetcher/browser/launcher.py | cleanup | def cleanup():
"""Must be called before exit"""
temp_dirs = []
for key in ('headless', 'headed'):
if FIREFOX_INSTANCE[key] is not None:
if FIREFOX_INSTANCE[key].profile:
temp_dirs.append(FIREFOX_INSTANCE[key].profile.profile_dir)
try:
FIREFOX_INSTANCE[key].quit()
FIREFOX_INSTANCE[key] = None
except:
logger.exception(
"Exception occurred in browser cleanup"
)
for temp_dir in temp_dirs:
shutil.rmtree(temp_dir, ignore_errors=True) | python | def cleanup():
"""Must be called before exit"""
temp_dirs = []
for key in ('headless', 'headed'):
if FIREFOX_INSTANCE[key] is not None:
if FIREFOX_INSTANCE[key].profile:
temp_dirs.append(FIREFOX_INSTANCE[key].profile.profile_dir)
try:
FIREFOX_INSTANCE[key].quit()
FIREFOX_INSTANCE[key] = None
except:
logger.exception(
"Exception occurred in browser cleanup"
)
for temp_dir in temp_dirs:
shutil.rmtree(temp_dir, ignore_errors=True) | [
"def",
"cleanup",
"(",
")",
":",
"temp_dirs",
"=",
"[",
"]",
"for",
"key",
"in",
"(",
"'headless'",
",",
"'headed'",
")",
":",
"if",
"FIREFOX_INSTANCE",
"[",
"key",
"]",
"is",
"not",
"None",
":",
"if",
"FIREFOX_INSTANCE",
"[",
"key",
"]",
".",
"profi... | Must be called before exit | [
"Must",
"be",
"called",
"before",
"exit"
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/fetcher/browser/launcher.py#L19-L34 | train | 28,654 |
kibitzr/kibitzr | kibitzr/fetcher/browser/launcher.py | firefox | def firefox(headless=True):
"""
Context manager returning Selenium webdriver.
Instance is reused and must be cleaned up on exit.
"""
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
if headless:
driver_key = 'headless'
firefox_options = Options()
firefox_options.add_argument('-headless')
else:
driver_key = 'headed'
firefox_options = None
# Load profile, if it exists:
if os.path.isdir(PROFILE_DIR):
firefox_profile = webdriver.FirefoxProfile(PROFILE_DIR)
else:
firefox_profile = None
if FIREFOX_INSTANCE[driver_key] is None:
FIREFOX_INSTANCE[driver_key] = webdriver.Firefox(
firefox_profile=firefox_profile,
firefox_options=firefox_options,
)
yield FIREFOX_INSTANCE[driver_key] | python | def firefox(headless=True):
"""
Context manager returning Selenium webdriver.
Instance is reused and must be cleaned up on exit.
"""
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
if headless:
driver_key = 'headless'
firefox_options = Options()
firefox_options.add_argument('-headless')
else:
driver_key = 'headed'
firefox_options = None
# Load profile, if it exists:
if os.path.isdir(PROFILE_DIR):
firefox_profile = webdriver.FirefoxProfile(PROFILE_DIR)
else:
firefox_profile = None
if FIREFOX_INSTANCE[driver_key] is None:
FIREFOX_INSTANCE[driver_key] = webdriver.Firefox(
firefox_profile=firefox_profile,
firefox_options=firefox_options,
)
yield FIREFOX_INSTANCE[driver_key] | [
"def",
"firefox",
"(",
"headless",
"=",
"True",
")",
":",
"from",
"selenium",
"import",
"webdriver",
"from",
"selenium",
".",
"webdriver",
".",
"firefox",
".",
"options",
"import",
"Options",
"if",
"headless",
":",
"driver_key",
"=",
"'headless'",
"firefox_opt... | Context manager returning Selenium webdriver.
Instance is reused and must be cleaned up on exit. | [
"Context",
"manager",
"returning",
"Selenium",
"webdriver",
".",
"Instance",
"is",
"reused",
"and",
"must",
"be",
"cleaned",
"up",
"on",
"exit",
"."
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/fetcher/browser/launcher.py#L38-L62 | train | 28,655 |
kibitzr/kibitzr | kibitzr/fetcher/factory.py | fetcher_factory | def fetcher_factory(conf):
"""Return initialized fetcher capable of processing given conf."""
global PROMOTERS
applicable = []
if not PROMOTERS:
PROMOTERS = load_promoters()
for promoter in PROMOTERS:
if promoter.is_applicable(conf):
applicable.append((promoter.PRIORITY, promoter))
if applicable:
best_match = sorted(applicable, reverse=True)[0][1]
return best_match(conf)
else:
raise ConfigurationError(
'No fetcher is applicable for "{0}"'.format(conf['name'])
) | python | def fetcher_factory(conf):
"""Return initialized fetcher capable of processing given conf."""
global PROMOTERS
applicable = []
if not PROMOTERS:
PROMOTERS = load_promoters()
for promoter in PROMOTERS:
if promoter.is_applicable(conf):
applicable.append((promoter.PRIORITY, promoter))
if applicable:
best_match = sorted(applicable, reverse=True)[0][1]
return best_match(conf)
else:
raise ConfigurationError(
'No fetcher is applicable for "{0}"'.format(conf['name'])
) | [
"def",
"fetcher_factory",
"(",
"conf",
")",
":",
"global",
"PROMOTERS",
"applicable",
"=",
"[",
"]",
"if",
"not",
"PROMOTERS",
":",
"PROMOTERS",
"=",
"load_promoters",
"(",
")",
"for",
"promoter",
"in",
"PROMOTERS",
":",
"if",
"promoter",
".",
"is_applicable... | Return initialized fetcher capable of processing given conf. | [
"Return",
"initialized",
"fetcher",
"capable",
"of",
"processing",
"given",
"conf",
"."
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/fetcher/factory.py#L22-L37 | train | 28,656 |
kibitzr/kibitzr | kibitzr/fetcher/browser/fetcher.py | FirefoxFetcher.fetch | def fetch(self, conf):
"""
1. Fetch URL
2. Run automation.
3. Return HTML.
4. Close the tab.
"""
url = conf['url']
# If Firefox is broken, it will raise here, causing kibitzr restart:
self.driver.set_window_size(1366, 800)
self.driver.implicitly_wait(2)
self.driver.get(url)
try:
self._run_automation(conf)
html = self._get_html()
except:
logger.exception(
"Exception occurred while fetching"
)
return False, traceback.format_exc()
finally:
self._close_tab()
return True, html | python | def fetch(self, conf):
"""
1. Fetch URL
2. Run automation.
3. Return HTML.
4. Close the tab.
"""
url = conf['url']
# If Firefox is broken, it will raise here, causing kibitzr restart:
self.driver.set_window_size(1366, 800)
self.driver.implicitly_wait(2)
self.driver.get(url)
try:
self._run_automation(conf)
html = self._get_html()
except:
logger.exception(
"Exception occurred while fetching"
)
return False, traceback.format_exc()
finally:
self._close_tab()
return True, html | [
"def",
"fetch",
"(",
"self",
",",
"conf",
")",
":",
"url",
"=",
"conf",
"[",
"'url'",
"]",
"# If Firefox is broken, it will raise here, causing kibitzr restart:",
"self",
".",
"driver",
".",
"set_window_size",
"(",
"1366",
",",
"800",
")",
"self",
".",
"driver",... | 1. Fetch URL
2. Run automation.
3. Return HTML.
4. Close the tab. | [
"1",
".",
"Fetch",
"URL",
"2",
".",
"Run",
"automation",
".",
"3",
".",
"Return",
"HTML",
".",
"4",
".",
"Close",
"the",
"tab",
"."
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/fetcher/browser/fetcher.py#L78-L100 | train | 28,657 |
kibitzr/kibitzr | kibitzr/fetcher/browser/fetcher.py | FirefoxFetcher._run_automation | def _run_automation(self, conf):
"""
1. Fill form.
2. Run scenario.
3. Delay.
"""
self._fill_form(self._find_form(conf))
self._run_scenario(conf)
self._delay(conf) | python | def _run_automation(self, conf):
"""
1. Fill form.
2. Run scenario.
3. Delay.
"""
self._fill_form(self._find_form(conf))
self._run_scenario(conf)
self._delay(conf) | [
"def",
"_run_automation",
"(",
"self",
",",
"conf",
")",
":",
"self",
".",
"_fill_form",
"(",
"self",
".",
"_find_form",
"(",
"conf",
")",
")",
"self",
".",
"_run_scenario",
"(",
"conf",
")",
"self",
".",
"_delay",
"(",
"conf",
")"
] | 1. Fill form.
2. Run scenario.
3. Delay. | [
"1",
".",
"Fill",
"form",
".",
"2",
".",
"Run",
"scenario",
".",
"3",
".",
"Delay",
"."
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/fetcher/browser/fetcher.py#L102-L110 | train | 28,658 |
kibitzr/kibitzr | kibitzr/fetcher/browser/fetcher.py | FirefoxFetcher._fill_form | def _fill_form(form):
"""
Fill all inputs with provided Jinja2 templates.
If no field had click key, submit last element.
"""
clicked = False
last_element = None
for field in form:
if field['text']:
field['element'].clear()
field['element'].send_keys(field['text'])
if field['click']:
field['element'].click()
clicked = True
last_element = field['element']
if last_element:
if not clicked:
last_element.submit() | python | def _fill_form(form):
"""
Fill all inputs with provided Jinja2 templates.
If no field had click key, submit last element.
"""
clicked = False
last_element = None
for field in form:
if field['text']:
field['element'].clear()
field['element'].send_keys(field['text'])
if field['click']:
field['element'].click()
clicked = True
last_element = field['element']
if last_element:
if not clicked:
last_element.submit() | [
"def",
"_fill_form",
"(",
"form",
")",
":",
"clicked",
"=",
"False",
"last_element",
"=",
"None",
"for",
"field",
"in",
"form",
":",
"if",
"field",
"[",
"'text'",
"]",
":",
"field",
"[",
"'element'",
"]",
".",
"clear",
"(",
")",
"field",
"[",
"'eleme... | Fill all inputs with provided Jinja2 templates.
If no field had click key, submit last element. | [
"Fill",
"all",
"inputs",
"with",
"provided",
"Jinja2",
"templates",
".",
"If",
"no",
"field",
"had",
"click",
"key",
"submit",
"last",
"element",
"."
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/fetcher/browser/fetcher.py#L113-L130 | train | 28,659 |
kibitzr/kibitzr | kibitzr/fetcher/browser/fetcher.py | FirefoxFetcher._find_element | def _find_element(self, selector, selector_type, check_displayed=False):
"""
Return first matching displayed element of non-zero size
or None if nothing found
"""
if selector_type == 'css':
elements = self.driver.find_elements_by_css_selector(selector)
elif selector_type == 'xpath':
elements = self.driver.find_elements_by_xpath(selector)
elif selector_type == 'id':
elements = self.driver.find_elements_by_css_selector('#' + selector)
else:
raise RuntimeError(
"Unknown selector_type: %s for selector: %s"
% (selector_type, selector)
)
for element in elements:
if check_displayed:
if not element.is_displayed() or sum(element.size.values()) <= 0:
continue
return element | python | def _find_element(self, selector, selector_type, check_displayed=False):
"""
Return first matching displayed element of non-zero size
or None if nothing found
"""
if selector_type == 'css':
elements = self.driver.find_elements_by_css_selector(selector)
elif selector_type == 'xpath':
elements = self.driver.find_elements_by_xpath(selector)
elif selector_type == 'id':
elements = self.driver.find_elements_by_css_selector('#' + selector)
else:
raise RuntimeError(
"Unknown selector_type: %s for selector: %s"
% (selector_type, selector)
)
for element in elements:
if check_displayed:
if not element.is_displayed() or sum(element.size.values()) <= 0:
continue
return element | [
"def",
"_find_element",
"(",
"self",
",",
"selector",
",",
"selector_type",
",",
"check_displayed",
"=",
"False",
")",
":",
"if",
"selector_type",
"==",
"'css'",
":",
"elements",
"=",
"self",
".",
"driver",
".",
"find_elements_by_css_selector",
"(",
"selector",
... | Return first matching displayed element of non-zero size
or None if nothing found | [
"Return",
"first",
"matching",
"displayed",
"element",
"of",
"non",
"-",
"zero",
"size",
"or",
"None",
"if",
"nothing",
"found"
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/fetcher/browser/fetcher.py#L259-L279 | train | 28,660 |
kibitzr/kibitzr | kibitzr/fetcher/browser/fetcher.py | FirefoxFetcher._close_tab | def _close_tab(self):
"""
Create a new tab and close the old one
to avoid idle page resource usage
"""
old_tab = self.driver.current_window_handle
self.driver.execute_script('''window.open("about:blank", "_blank");''')
self.driver.switch_to.window(old_tab)
self.driver.close()
self.driver.switch_to.window(self.driver.window_handles[0]) | python | def _close_tab(self):
"""
Create a new tab and close the old one
to avoid idle page resource usage
"""
old_tab = self.driver.current_window_handle
self.driver.execute_script('''window.open("about:blank", "_blank");''')
self.driver.switch_to.window(old_tab)
self.driver.close()
self.driver.switch_to.window(self.driver.window_handles[0]) | [
"def",
"_close_tab",
"(",
"self",
")",
":",
"old_tab",
"=",
"self",
".",
"driver",
".",
"current_window_handle",
"self",
".",
"driver",
".",
"execute_script",
"(",
"'''window.open(\"about:blank\", \"_blank\");'''",
")",
"self",
".",
"driver",
".",
"switch_to",
"."... | Create a new tab and close the old one
to avoid idle page resource usage | [
"Create",
"a",
"new",
"tab",
"and",
"close",
"the",
"old",
"one",
"to",
"avoid",
"idle",
"page",
"resource",
"usage"
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/fetcher/browser/fetcher.py#L294-L303 | train | 28,661 |
kibitzr/kibitzr | kibitzr/storage.py | PageHistory.write | def write(self, content):
"""Save content on disk"""
with io.open(self.target, 'w', encoding='utf-8') as fp:
fp.write(content)
if not content.endswith(u'\n'):
fp.write(u'\n') | python | def write(self, content):
"""Save content on disk"""
with io.open(self.target, 'w', encoding='utf-8') as fp:
fp.write(content)
if not content.endswith(u'\n'):
fp.write(u'\n') | [
"def",
"write",
"(",
"self",
",",
"content",
")",
":",
"with",
"io",
".",
"open",
"(",
"self",
".",
"target",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"content",
")",
"if",
"not",
"content",
".",... | Save content on disk | [
"Save",
"content",
"on",
"disk"
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/storage.py#L62-L67 | train | 28,662 |
kibitzr/kibitzr | kibitzr/storage.py | PageHistory.commit | def commit(self):
"""git commit and return whether there were changes"""
self.git.add('-A', '.')
try:
self.git.commit('-m', self.commit_msg)
return True
except sh.ErrorReturnCode_1:
return False | python | def commit(self):
"""git commit and return whether there were changes"""
self.git.add('-A', '.')
try:
self.git.commit('-m', self.commit_msg)
return True
except sh.ErrorReturnCode_1:
return False | [
"def",
"commit",
"(",
"self",
")",
":",
"self",
".",
"git",
".",
"add",
"(",
"'-A'",
",",
"'.'",
")",
"try",
":",
"self",
".",
"git",
".",
"commit",
"(",
"'-m'",
",",
"self",
".",
"commit_msg",
")",
"return",
"True",
"except",
"sh",
".",
"ErrorRe... | git commit and return whether there were changes | [
"git",
"commit",
"and",
"return",
"whether",
"there",
"were",
"changes"
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/storage.py#L69-L76 | train | 28,663 |
kibitzr/kibitzr | kibitzr/storage.py | PageHistory.ensure_repo_exists | def ensure_repo_exists(self):
"""Create git repo if one does not exist yet"""
if not os.path.isdir(self.cwd):
os.makedirs(self.cwd)
if not os.path.isdir(os.path.join(self.cwd, ".git")):
self.git.init()
self.git.config("user.email", "you@example.com")
self.git.config("user.name", "Your Name") | python | def ensure_repo_exists(self):
"""Create git repo if one does not exist yet"""
if not os.path.isdir(self.cwd):
os.makedirs(self.cwd)
if not os.path.isdir(os.path.join(self.cwd, ".git")):
self.git.init()
self.git.config("user.email", "you@example.com")
self.git.config("user.name", "Your Name") | [
"def",
"ensure_repo_exists",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"cwd",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"cwd",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
"... | Create git repo if one does not exist yet | [
"Create",
"git",
"repo",
"if",
"one",
"does",
"not",
"exist",
"yet"
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/storage.py#L78-L85 | train | 28,664 |
kibitzr/kibitzr | kibitzr/storage.py | ChangesReporter.word | def word(self):
"""Return last changes with word diff"""
try:
output = ensure_unicode(self.git.diff(
'--no-color',
'--word-diff=plain',
'HEAD~1:content',
'HEAD:content',
).stdout)
except sh.ErrorReturnCode_128:
result = ensure_unicode(self.git.show(
"HEAD:content"
).stdout)
else:
ago = ensure_unicode(self.git.log(
'-2',
'--pretty=format:last change was %cr',
'content'
).stdout).splitlines()
lines = output.splitlines()
result = u'\n'.join(
itertools.chain(
itertools.islice(
itertools.dropwhile(
lambda x: not x.startswith('@@'),
lines[1:],
),
1,
None,
),
itertools.islice(ago, 1, None),
)
)
return result | python | def word(self):
"""Return last changes with word diff"""
try:
output = ensure_unicode(self.git.diff(
'--no-color',
'--word-diff=plain',
'HEAD~1:content',
'HEAD:content',
).stdout)
except sh.ErrorReturnCode_128:
result = ensure_unicode(self.git.show(
"HEAD:content"
).stdout)
else:
ago = ensure_unicode(self.git.log(
'-2',
'--pretty=format:last change was %cr',
'content'
).stdout).splitlines()
lines = output.splitlines()
result = u'\n'.join(
itertools.chain(
itertools.islice(
itertools.dropwhile(
lambda x: not x.startswith('@@'),
lines[1:],
),
1,
None,
),
itertools.islice(ago, 1, None),
)
)
return result | [
"def",
"word",
"(",
"self",
")",
":",
"try",
":",
"output",
"=",
"ensure_unicode",
"(",
"self",
".",
"git",
".",
"diff",
"(",
"'--no-color'",
",",
"'--word-diff=plain'",
",",
"'HEAD~1:content'",
",",
"'HEAD:content'",
",",
")",
".",
"stdout",
")",
"except"... | Return last changes with word diff | [
"Return",
"last",
"changes",
"with",
"word",
"diff"
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/storage.py#L109-L142 | train | 28,665 |
kibitzr/kibitzr | kibitzr/storage.py | ChangesReporter.default | def default(self):
"""Return last changes in truncated unified diff format"""
output = ensure_unicode(self.git.log(
'-1',
'-p',
'--no-color',
'--format=%s',
).stdout)
lines = output.splitlines()
return u'\n'.join(
itertools.chain(
lines[:1],
itertools.islice(
itertools.dropwhile(
lambda x: not x.startswith('+++'),
lines[1:],
),
1,
None,
),
)
) | python | def default(self):
"""Return last changes in truncated unified diff format"""
output = ensure_unicode(self.git.log(
'-1',
'-p',
'--no-color',
'--format=%s',
).stdout)
lines = output.splitlines()
return u'\n'.join(
itertools.chain(
lines[:1],
itertools.islice(
itertools.dropwhile(
lambda x: not x.startswith('+++'),
lines[1:],
),
1,
None,
),
)
) | [
"def",
"default",
"(",
"self",
")",
":",
"output",
"=",
"ensure_unicode",
"(",
"self",
".",
"git",
".",
"log",
"(",
"'-1'",
",",
"'-p'",
",",
"'--no-color'",
",",
"'--format=%s'",
",",
")",
".",
"stdout",
")",
"lines",
"=",
"output",
".",
"splitlines",... | Return last changes in truncated unified diff format | [
"Return",
"last",
"changes",
"in",
"truncated",
"unified",
"diff",
"format"
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/storage.py#L144-L165 | train | 28,666 |
kibitzr/kibitzr | kibitzr/bash.py | BashExecutor.temp_file | def temp_file(self):
"""
Create temporary file with code and yield its path.
Works both on Windows and Linux
"""
with tempfile.NamedTemporaryFile(suffix='.bat', delete=False) as fp:
try:
logger.debug("Saving code to %r", fp.name)
fp.write(self.code.encode('utf-8'))
fp.close()
yield fp.name
finally:
os.remove(fp.name) | python | def temp_file(self):
"""
Create temporary file with code and yield its path.
Works both on Windows and Linux
"""
with tempfile.NamedTemporaryFile(suffix='.bat', delete=False) as fp:
try:
logger.debug("Saving code to %r", fp.name)
fp.write(self.code.encode('utf-8'))
fp.close()
yield fp.name
finally:
os.remove(fp.name) | [
"def",
"temp_file",
"(",
"self",
")",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"'.bat'",
",",
"delete",
"=",
"False",
")",
"as",
"fp",
":",
"try",
":",
"logger",
".",
"debug",
"(",
"\"Saving code to %r\"",
",",
"fp",
".",
... | Create temporary file with code and yield its path.
Works both on Windows and Linux | [
"Create",
"temporary",
"file",
"with",
"code",
"and",
"yield",
"its",
"path",
".",
"Works",
"both",
"on",
"Windows",
"and",
"Linux"
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/bash.py#L165-L177 | train | 28,667 |
kibitzr/kibitzr | kibitzr/cli.py | once | def once(ctx, name):
"""Run kibitzr checks once and exit"""
from kibitzr.app import Application
app = Application()
sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name)) | python | def once(ctx, name):
"""Run kibitzr checks once and exit"""
from kibitzr.app import Application
app = Application()
sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name)) | [
"def",
"once",
"(",
"ctx",
",",
"name",
")",
":",
"from",
"kibitzr",
".",
"app",
"import",
"Application",
"app",
"=",
"Application",
"(",
")",
"sys",
".",
"exit",
"(",
"app",
".",
"run",
"(",
"once",
"=",
"True",
",",
"log_level",
"=",
"ctx",
".",
... | Run kibitzr checks once and exit | [
"Run",
"kibitzr",
"checks",
"once",
"and",
"exit"
] | 749da312488f1dda1ed1093cf4c95aaac0a604f7 | https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/cli.py#L61-L65 | train | 28,668 |
konstantint/matplotlib-venn | matplotlib_venn/_region.py | VennCircleRegion.subtract_and_intersect_circle | def subtract_and_intersect_circle(self, center, radius):
'''Will throw a VennRegionException if the circle to be subtracted is completely inside and not touching the given region.'''
# Check whether the target circle intersects us
center = np.asarray(center, float)
d = np.linalg.norm(center - self.center)
if d > (radius + self.radius - tol):
return [self, VennEmptyRegion()] # The circle does not intersect us
elif d < tol:
if radius > self.radius - tol:
# We are completely covered by that circle or we are the same circle
return [VennEmptyRegion(), self]
else:
# That other circle is inside us and smaller than us - we can't deal with it
raise VennRegionException("Invalid configuration of circular regions (holes are not supported).")
else:
# We *must* intersect the other circle. If it is not the case, then it is inside us completely,
# and we'll complain.
intersections = circle_circle_intersection(self.center, self.radius, center, radius)
if intersections is None:
raise VennRegionException("Invalid configuration of circular regions (holes are not supported).")
elif np.all(abs(intersections[0] - intersections[1]) < tol) and self.radius < radius:
# There is a single intersection point (i.e. we are touching the circle),
# the circle to be subtracted is not outside of us (this was checked before), and is larger than us.
# This is a particular corner case that is not dealt with correctly by the general-purpose code below and must
# be handled separately
return [VennEmptyRegion(), self]
else:
# Otherwise the subtracted region is a 2-arc-gon
# Before we need to convert the intersection points as angles wrt each circle.
a_1 = vector_angle_in_degrees(intersections[0] - self.center)
a_2 = vector_angle_in_degrees(intersections[1] - self.center)
b_1 = vector_angle_in_degrees(intersections[0] - center)
b_2 = vector_angle_in_degrees(intersections[1] - center)
# We must take care of the situation where the intersection points happen to be the same
if (abs(b_1 - b_2) < tol):
b_1 = b_2 - tol/2
if (abs(a_1 - a_2) < tol):
a_2 = a_1 + tol/2
# The subtraction is a 2-arc-gon [(AB, B-), (BA, A+)]
s_arc1 = Arc(center, radius, b_1, b_2, False)
s_arc2 = Arc(self.center, self.radius, a_2, a_1, True)
subtraction = VennArcgonRegion([s_arc1, s_arc2])
# .. and the intersection is a 2-arc-gon [(AB, A+), (BA, B+)]
i_arc1 = Arc(self.center, self.radius, a_1, a_2, True)
i_arc2 = Arc(center, radius, b_2, b_1, True)
intersection = VennArcgonRegion([i_arc1, i_arc2])
return [subtraction, intersection] | python | def subtract_and_intersect_circle(self, center, radius):
'''Will throw a VennRegionException if the circle to be subtracted is completely inside and not touching the given region.'''
# Check whether the target circle intersects us
center = np.asarray(center, float)
d = np.linalg.norm(center - self.center)
if d > (radius + self.radius - tol):
return [self, VennEmptyRegion()] # The circle does not intersect us
elif d < tol:
if radius > self.radius - tol:
# We are completely covered by that circle or we are the same circle
return [VennEmptyRegion(), self]
else:
# That other circle is inside us and smaller than us - we can't deal with it
raise VennRegionException("Invalid configuration of circular regions (holes are not supported).")
else:
# We *must* intersect the other circle. If it is not the case, then it is inside us completely,
# and we'll complain.
intersections = circle_circle_intersection(self.center, self.radius, center, radius)
if intersections is None:
raise VennRegionException("Invalid configuration of circular regions (holes are not supported).")
elif np.all(abs(intersections[0] - intersections[1]) < tol) and self.radius < radius:
# There is a single intersection point (i.e. we are touching the circle),
# the circle to be subtracted is not outside of us (this was checked before), and is larger than us.
# This is a particular corner case that is not dealt with correctly by the general-purpose code below and must
# be handled separately
return [VennEmptyRegion(), self]
else:
# Otherwise the subtracted region is a 2-arc-gon
# Before we need to convert the intersection points as angles wrt each circle.
a_1 = vector_angle_in_degrees(intersections[0] - self.center)
a_2 = vector_angle_in_degrees(intersections[1] - self.center)
b_1 = vector_angle_in_degrees(intersections[0] - center)
b_2 = vector_angle_in_degrees(intersections[1] - center)
# We must take care of the situation where the intersection points happen to be the same
if (abs(b_1 - b_2) < tol):
b_1 = b_2 - tol/2
if (abs(a_1 - a_2) < tol):
a_2 = a_1 + tol/2
# The subtraction is a 2-arc-gon [(AB, B-), (BA, A+)]
s_arc1 = Arc(center, radius, b_1, b_2, False)
s_arc2 = Arc(self.center, self.radius, a_2, a_1, True)
subtraction = VennArcgonRegion([s_arc1, s_arc2])
# .. and the intersection is a 2-arc-gon [(AB, A+), (BA, B+)]
i_arc1 = Arc(self.center, self.radius, a_1, a_2, True)
i_arc2 = Arc(center, radius, b_2, b_1, True)
intersection = VennArcgonRegion([i_arc1, i_arc2])
return [subtraction, intersection] | [
"def",
"subtract_and_intersect_circle",
"(",
"self",
",",
"center",
",",
"radius",
")",
":",
"# Check whether the target circle intersects us",
"center",
"=",
"np",
".",
"asarray",
"(",
"center",
",",
"float",
")",
"d",
"=",
"np",
".",
"linalg",
".",
"norm",
"... | Will throw a VennRegionException if the circle to be subtracted is completely inside and not touching the given region. | [
"Will",
"throw",
"a",
"VennRegionException",
"if",
"the",
"circle",
"to",
"be",
"subtracted",
"is",
"completely",
"inside",
"and",
"not",
"touching",
"the",
"given",
"region",
"."
] | c26796c9925bdac512edf48387452fbd1848c791 | https://github.com/konstantint/matplotlib-venn/blob/c26796c9925bdac512edf48387452fbd1848c791/matplotlib_venn/_region.py#L132-L183 | train | 28,669 |
konstantint/matplotlib-venn | matplotlib_venn/_region.py | VennArcgonRegion.size | def size(self):
'''Return the area of the patch.
The area can be computed using the standard polygon area formula + signed segment areas of each arc.
'''
polygon_area = 0
for a in self.arcs:
polygon_area += box_product(a.start_point(), a.end_point())
polygon_area /= 2.0
return polygon_area + sum([a.sign * a.segment_area() for a in self.arcs]) | python | def size(self):
'''Return the area of the patch.
The area can be computed using the standard polygon area formula + signed segment areas of each arc.
'''
polygon_area = 0
for a in self.arcs:
polygon_area += box_product(a.start_point(), a.end_point())
polygon_area /= 2.0
return polygon_area + sum([a.sign * a.segment_area() for a in self.arcs]) | [
"def",
"size",
"(",
"self",
")",
":",
"polygon_area",
"=",
"0",
"for",
"a",
"in",
"self",
".",
"arcs",
":",
"polygon_area",
"+=",
"box_product",
"(",
"a",
".",
"start_point",
"(",
")",
",",
"a",
".",
"end_point",
"(",
")",
")",
"polygon_area",
"/=",
... | Return the area of the patch.
The area can be computed using the standard polygon area formula + signed segment areas of each arc. | [
"Return",
"the",
"area",
"of",
"the",
"patch",
".",
"The",
"area",
"can",
"be",
"computed",
"using",
"the",
"standard",
"polygon",
"area",
"formula",
"+",
"signed",
"segment",
"areas",
"of",
"each",
"arc",
"."
] | c26796c9925bdac512edf48387452fbd1848c791 | https://github.com/konstantint/matplotlib-venn/blob/c26796c9925bdac512edf48387452fbd1848c791/matplotlib_venn/_region.py#L471-L480 | train | 28,670 |
konstantint/matplotlib-venn | matplotlib_venn/_region.py | VennArcgonRegion.make_patch | def make_patch(self):
'''
Retuns a matplotlib PathPatch representing the current region.
'''
path = [self.arcs[0].start_point()]
for a in self.arcs:
if a.direction:
vertices = Path.arc(a.from_angle, a.to_angle).vertices
else:
vertices = Path.arc(a.to_angle, a.from_angle).vertices
vertices = vertices[np.arange(len(vertices) - 1, -1, -1)]
vertices = vertices * a.radius + a.center
path = path + list(vertices[1:])
codes = [1] + [4] * (len(path) - 1) # NB: We could also add a CLOSEPOLY code (and a random vertex) to the end
return PathPatch(Path(path, codes)) | python | def make_patch(self):
'''
Retuns a matplotlib PathPatch representing the current region.
'''
path = [self.arcs[0].start_point()]
for a in self.arcs:
if a.direction:
vertices = Path.arc(a.from_angle, a.to_angle).vertices
else:
vertices = Path.arc(a.to_angle, a.from_angle).vertices
vertices = vertices[np.arange(len(vertices) - 1, -1, -1)]
vertices = vertices * a.radius + a.center
path = path + list(vertices[1:])
codes = [1] + [4] * (len(path) - 1) # NB: We could also add a CLOSEPOLY code (and a random vertex) to the end
return PathPatch(Path(path, codes)) | [
"def",
"make_patch",
"(",
"self",
")",
":",
"path",
"=",
"[",
"self",
".",
"arcs",
"[",
"0",
"]",
".",
"start_point",
"(",
")",
"]",
"for",
"a",
"in",
"self",
".",
"arcs",
":",
"if",
"a",
".",
"direction",
":",
"vertices",
"=",
"Path",
".",
"ar... | Retuns a matplotlib PathPatch representing the current region. | [
"Retuns",
"a",
"matplotlib",
"PathPatch",
"representing",
"the",
"current",
"region",
"."
] | c26796c9925bdac512edf48387452fbd1848c791 | https://github.com/konstantint/matplotlib-venn/blob/c26796c9925bdac512edf48387452fbd1848c791/matplotlib_venn/_region.py#L482-L496 | train | 28,671 |
konstantint/matplotlib-venn | matplotlib_venn/_region.py | VennMultipieceRegion.label_position | def label_position(self):
'''
Find the largest region and position the label in that.
'''
reg_sizes = [(r.size(), r) for r in self.pieces]
reg_sizes.sort()
return reg_sizes[-1][1].label_position() | python | def label_position(self):
'''
Find the largest region and position the label in that.
'''
reg_sizes = [(r.size(), r) for r in self.pieces]
reg_sizes.sort()
return reg_sizes[-1][1].label_position() | [
"def",
"label_position",
"(",
"self",
")",
":",
"reg_sizes",
"=",
"[",
"(",
"r",
".",
"size",
"(",
")",
",",
"r",
")",
"for",
"r",
"in",
"self",
".",
"pieces",
"]",
"reg_sizes",
".",
"sort",
"(",
")",
"return",
"reg_sizes",
"[",
"-",
"1",
"]",
... | Find the largest region and position the label in that. | [
"Find",
"the",
"largest",
"region",
"and",
"position",
"the",
"label",
"in",
"that",
"."
] | c26796c9925bdac512edf48387452fbd1848c791 | https://github.com/konstantint/matplotlib-venn/blob/c26796c9925bdac512edf48387452fbd1848c791/matplotlib_venn/_region.py#L516-L522 | train | 28,672 |
konstantint/matplotlib-venn | matplotlib_venn/_region.py | VennMultipieceRegion.make_patch | def make_patch(self):
'''Currently only works if all the pieces are Arcgons.
In this case returns a multiple-piece path. Otherwise throws an exception.'''
paths = [p.make_patch().get_path() for p in self.pieces]
vertices = np.concatenate([p.vertices for p in paths])
codes = np.concatenate([p.codes for p in paths])
return PathPatch(Path(vertices, codes)) | python | def make_patch(self):
'''Currently only works if all the pieces are Arcgons.
In this case returns a multiple-piece path. Otherwise throws an exception.'''
paths = [p.make_patch().get_path() for p in self.pieces]
vertices = np.concatenate([p.vertices for p in paths])
codes = np.concatenate([p.codes for p in paths])
return PathPatch(Path(vertices, codes)) | [
"def",
"make_patch",
"(",
"self",
")",
":",
"paths",
"=",
"[",
"p",
".",
"make_patch",
"(",
")",
".",
"get_path",
"(",
")",
"for",
"p",
"in",
"self",
".",
"pieces",
"]",
"vertices",
"=",
"np",
".",
"concatenate",
"(",
"[",
"p",
".",
"vertices",
"... | Currently only works if all the pieces are Arcgons.
In this case returns a multiple-piece path. Otherwise throws an exception. | [
"Currently",
"only",
"works",
"if",
"all",
"the",
"pieces",
"are",
"Arcgons",
".",
"In",
"this",
"case",
"returns",
"a",
"multiple",
"-",
"piece",
"path",
".",
"Otherwise",
"throws",
"an",
"exception",
"."
] | c26796c9925bdac512edf48387452fbd1848c791 | https://github.com/konstantint/matplotlib-venn/blob/c26796c9925bdac512edf48387452fbd1848c791/matplotlib_venn/_region.py#L527-L533 | train | 28,673 |
konstantint/matplotlib-venn | matplotlib_venn/_arc.py | Arc.mid_point | def mid_point(self):
'''
Returns the midpoint of the arc as a 1x2 numpy array.
'''
midpoint_angle = self.from_angle + self.sign*self.length_degrees() / 2
return self.angle_as_point(midpoint_angle) | python | def mid_point(self):
'''
Returns the midpoint of the arc as a 1x2 numpy array.
'''
midpoint_angle = self.from_angle + self.sign*self.length_degrees() / 2
return self.angle_as_point(midpoint_angle) | [
"def",
"mid_point",
"(",
"self",
")",
":",
"midpoint_angle",
"=",
"self",
".",
"from_angle",
"+",
"self",
".",
"sign",
"*",
"self",
".",
"length_degrees",
"(",
")",
"/",
"2",
"return",
"self",
".",
"angle_as_point",
"(",
"midpoint_angle",
")"
] | Returns the midpoint of the arc as a 1x2 numpy array. | [
"Returns",
"the",
"midpoint",
"of",
"the",
"arc",
"as",
"a",
"1x2",
"numpy",
"array",
"."
] | c26796c9925bdac512edf48387452fbd1848c791 | https://github.com/konstantint/matplotlib-venn/blob/c26796c9925bdac512edf48387452fbd1848c791/matplotlib_venn/_arc.py#L188-L193 | train | 28,674 |
konstantint/matplotlib-venn | matplotlib_venn/_common.py | VennDiagram.hide_zeroes | def hide_zeroes(self):
'''
Sometimes it makes sense to hide the labels for subsets whose size is zero.
This utility method does this.
'''
for v in self.subset_labels:
if v is not None and v.get_text() == '0':
v.set_visible(False) | python | def hide_zeroes(self):
'''
Sometimes it makes sense to hide the labels for subsets whose size is zero.
This utility method does this.
'''
for v in self.subset_labels:
if v is not None and v.get_text() == '0':
v.set_visible(False) | [
"def",
"hide_zeroes",
"(",
"self",
")",
":",
"for",
"v",
"in",
"self",
".",
"subset_labels",
":",
"if",
"v",
"is",
"not",
"None",
"and",
"v",
".",
"get_text",
"(",
")",
"==",
"'0'",
":",
"v",
".",
"set_visible",
"(",
"False",
")"
] | Sometimes it makes sense to hide the labels for subsets whose size is zero.
This utility method does this. | [
"Sometimes",
"it",
"makes",
"sense",
"to",
"hide",
"the",
"labels",
"for",
"subsets",
"whose",
"size",
"is",
"zero",
".",
"This",
"utility",
"method",
"does",
"this",
"."
] | c26796c9925bdac512edf48387452fbd1848c791 | https://github.com/konstantint/matplotlib-venn/blob/c26796c9925bdac512edf48387452fbd1848c791/matplotlib_venn/_common.py#L60-L67 | train | 28,675 |
maas/python-libmaas | maas/client/utils/diff.py | calculate_dict_diff | def calculate_dict_diff(old_params: dict, new_params: dict):
"""Return the parameters based on the difference.
If a parameter exists in `old_params` but not in `new_params` then
parameter will be set to an empty string.
"""
# Ignore all None values as those cannot be saved.
old_params = remove_None(old_params)
new_params = remove_None(new_params)
params_diff = {}
for key, value in old_params.items():
if key in new_params:
if value != new_params[key]:
params_diff[key] = new_params[key]
else:
params_diff[key] = ''
for key, value in new_params.items():
if key not in old_params:
params_diff[key] = value
return params_diff | python | def calculate_dict_diff(old_params: dict, new_params: dict):
"""Return the parameters based on the difference.
If a parameter exists in `old_params` but not in `new_params` then
parameter will be set to an empty string.
"""
# Ignore all None values as those cannot be saved.
old_params = remove_None(old_params)
new_params = remove_None(new_params)
params_diff = {}
for key, value in old_params.items():
if key in new_params:
if value != new_params[key]:
params_diff[key] = new_params[key]
else:
params_diff[key] = ''
for key, value in new_params.items():
if key not in old_params:
params_diff[key] = value
return params_diff | [
"def",
"calculate_dict_diff",
"(",
"old_params",
":",
"dict",
",",
"new_params",
":",
"dict",
")",
":",
"# Ignore all None values as those cannot be saved.",
"old_params",
"=",
"remove_None",
"(",
"old_params",
")",
"new_params",
"=",
"remove_None",
"(",
"new_params",
... | Return the parameters based on the difference.
If a parameter exists in `old_params` but not in `new_params` then
parameter will be set to an empty string. | [
"Return",
"the",
"parameters",
"based",
"on",
"the",
"difference",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/diff.py#L25-L44 | train | 28,676 |
maas/python-libmaas | maas/client/flesh/machines.py | validate_file | def validate_file(parser, arg):
"""Validates that `arg` is a valid file."""
if not os.path.isfile(arg):
parser.error("%s is not a file." % arg)
return arg | python | def validate_file(parser, arg):
"""Validates that `arg` is a valid file."""
if not os.path.isfile(arg):
parser.error("%s is not a file." % arg)
return arg | [
"def",
"validate_file",
"(",
"parser",
",",
"arg",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"arg",
")",
":",
"parser",
".",
"error",
"(",
"\"%s is not a file.\"",
"%",
"arg",
")",
"return",
"arg"
] | Validates that `arg` is a valid file. | [
"Validates",
"that",
"arg",
"is",
"a",
"valid",
"file",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/machines.py#L29-L33 | train | 28,677 |
maas/python-libmaas | maas/client/flesh/machines.py | register | def register(parser):
"""Register commands with the given parser."""
cmd_machines.register(parser)
cmd_machine.register(parser)
cmd_allocate.register(parser)
cmd_deploy.register(parser)
cmd_commission.register(parser)
cmd_release.register(parser)
cmd_abort.register(parser)
cmd_mark_fixed.register(parser)
cmd_mark_broken.register(parser)
cmd_power_off.register(parser)
cmd_power_on.register(parser)
cmd_ssh.register(parser) | python | def register(parser):
"""Register commands with the given parser."""
cmd_machines.register(parser)
cmd_machine.register(parser)
cmd_allocate.register(parser)
cmd_deploy.register(parser)
cmd_commission.register(parser)
cmd_release.register(parser)
cmd_abort.register(parser)
cmd_mark_fixed.register(parser)
cmd_mark_broken.register(parser)
cmd_power_off.register(parser)
cmd_power_on.register(parser)
cmd_ssh.register(parser) | [
"def",
"register",
"(",
"parser",
")",
":",
"cmd_machines",
".",
"register",
"(",
"parser",
")",
"cmd_machine",
".",
"register",
"(",
"parser",
")",
"cmd_allocate",
".",
"register",
"(",
"parser",
")",
"cmd_deploy",
".",
"register",
"(",
"parser",
")",
"cm... | Register commands with the given parser. | [
"Register",
"commands",
"with",
"the",
"given",
"parser",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/machines.py#L960-L973 | train | 28,678 |
maas/python-libmaas | maas/client/flesh/machines.py | MachineWorkMixin.perform_action | def perform_action(
self, action, machines, params, progress_title, success_title):
"""Perform the action on the set of machines."""
if len(machines) == 0:
return 0
with utils.Spinner() as context:
return self._async_perform_action(
context, action, list(machines), params,
progress_title, success_title) | python | def perform_action(
self, action, machines, params, progress_title, success_title):
"""Perform the action on the set of machines."""
if len(machines) == 0:
return 0
with utils.Spinner() as context:
return self._async_perform_action(
context, action, list(machines), params,
progress_title, success_title) | [
"def",
"perform_action",
"(",
"self",
",",
"action",
",",
"machines",
",",
"params",
",",
"progress_title",
",",
"success_title",
")",
":",
"if",
"len",
"(",
"machines",
")",
"==",
"0",
":",
"return",
"0",
"with",
"utils",
".",
"Spinner",
"(",
")",
"as... | Perform the action on the set of machines. | [
"Perform",
"the",
"action",
"on",
"the",
"set",
"of",
"machines",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/machines.py#L343-L351 | train | 28,679 |
maas/python-libmaas | maas/client/flesh/machines.py | MachineWorkMixin.get_machines | def get_machines(self, origin, hostnames):
"""Return a set of machines based on `hostnames`.
Any hostname that is not found will result in an error.
"""
hostnames = {
hostname: True
for hostname in hostnames
}
machines = origin.Machines.read(hostnames=hostnames)
machines = [
machine
for machine in machines
if hostnames.pop(machine.hostname, False)
]
if len(hostnames) > 0:
raise CommandError(
"Unable to find %s %s." % (
"machines" if len(hostnames) > 1 else "machine",
','.join(hostnames)))
return machines | python | def get_machines(self, origin, hostnames):
"""Return a set of machines based on `hostnames`.
Any hostname that is not found will result in an error.
"""
hostnames = {
hostname: True
for hostname in hostnames
}
machines = origin.Machines.read(hostnames=hostnames)
machines = [
machine
for machine in machines
if hostnames.pop(machine.hostname, False)
]
if len(hostnames) > 0:
raise CommandError(
"Unable to find %s %s." % (
"machines" if len(hostnames) > 1 else "machine",
','.join(hostnames)))
return machines | [
"def",
"get_machines",
"(",
"self",
",",
"origin",
",",
"hostnames",
")",
":",
"hostnames",
"=",
"{",
"hostname",
":",
"True",
"for",
"hostname",
"in",
"hostnames",
"}",
"machines",
"=",
"origin",
".",
"Machines",
".",
"read",
"(",
"hostnames",
"=",
"hos... | Return a set of machines based on `hostnames`.
Any hostname that is not found will result in an error. | [
"Return",
"a",
"set",
"of",
"machines",
"based",
"on",
"hostnames",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/machines.py#L353-L373 | train | 28,680 |
maas/python-libmaas | maas/client/flesh/machines.py | MachineSSHMixin.add_ssh_options | def add_ssh_options(self, parser):
"""Add the SSH arguments to the `parser`."""
parser.add_argument(
"--username", metavar='USER', help=(
"Username for the SSH connection."))
parser.add_argument(
"--boot-only", action="store_true", help=(
"Only use the IP addresses on the machine's boot interface.")) | python | def add_ssh_options(self, parser):
"""Add the SSH arguments to the `parser`."""
parser.add_argument(
"--username", metavar='USER', help=(
"Username for the SSH connection."))
parser.add_argument(
"--boot-only", action="store_true", help=(
"Only use the IP addresses on the machine's boot interface.")) | [
"def",
"add_ssh_options",
"(",
"self",
",",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"\"--username\"",
",",
"metavar",
"=",
"'USER'",
",",
"help",
"=",
"(",
"\"Username for the SSH connection.\"",
")",
")",
"parser",
".",
"add_argument",
"(",
"\... | Add the SSH arguments to the `parser`. | [
"Add",
"the",
"SSH",
"arguments",
"to",
"the",
"parser",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/machines.py#L379-L386 | train | 28,681 |
maas/python-libmaas | maas/client/flesh/machines.py | MachineSSHMixin.get_ip_addresses | def get_ip_addresses(self, machine, *, boot_only=False, discovered=False):
"""Return all IP address for `machine`.
IP address from `boot_interface` come first.
"""
boot_ips = [
link.ip_address
for link in machine.boot_interface.links
if link.ip_address
]
if boot_only:
if boot_ips:
return boot_ips
elif discovered:
return [
link.ip_address
for link in machine.boot_interface.discovered
if link.ip_address
]
else:
return []
else:
other_ips = [
link.ip_address
for interface in machine.interfaces
for link in interface.links
if (interface.id != machine.boot_interface.id and
link.ip_address)
]
ips = boot_ips + other_ips
if ips:
return ips
elif discovered:
return [
link.ip_address
for link in machine.boot_interface.discovered
if link.ip_address
] + [
link.ip_address
for interface in machine.interfaces
for link in interface.discovered
if (interface.id != machine.boot_interface.id and
link.ip_address)
]
else:
return [] | python | def get_ip_addresses(self, machine, *, boot_only=False, discovered=False):
"""Return all IP address for `machine`.
IP address from `boot_interface` come first.
"""
boot_ips = [
link.ip_address
for link in machine.boot_interface.links
if link.ip_address
]
if boot_only:
if boot_ips:
return boot_ips
elif discovered:
return [
link.ip_address
for link in machine.boot_interface.discovered
if link.ip_address
]
else:
return []
else:
other_ips = [
link.ip_address
for interface in machine.interfaces
for link in interface.links
if (interface.id != machine.boot_interface.id and
link.ip_address)
]
ips = boot_ips + other_ips
if ips:
return ips
elif discovered:
return [
link.ip_address
for link in machine.boot_interface.discovered
if link.ip_address
] + [
link.ip_address
for interface in machine.interfaces
for link in interface.discovered
if (interface.id != machine.boot_interface.id and
link.ip_address)
]
else:
return [] | [
"def",
"get_ip_addresses",
"(",
"self",
",",
"machine",
",",
"*",
",",
"boot_only",
"=",
"False",
",",
"discovered",
"=",
"False",
")",
":",
"boot_ips",
"=",
"[",
"link",
".",
"ip_address",
"for",
"link",
"in",
"machine",
".",
"boot_interface",
".",
"lin... | Return all IP address for `machine`.
IP address from `boot_interface` come first. | [
"Return",
"all",
"IP",
"address",
"for",
"machine",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/machines.py#L388-L433 | train | 28,682 |
maas/python-libmaas | maas/client/flesh/machines.py | MachineSSHMixin._async_get_sshable_ips | async def _async_get_sshable_ips(self, ip_addresses):
"""Return list of all IP address that could be pinged."""
async def _async_ping(ip_address):
try:
reader, writer = await asyncio.wait_for(
asyncio.open_connection(ip_address, 22), timeout=5)
except (OSError, TimeoutError):
return None
try:
line = await reader.readline()
finally:
writer.close()
if line.startswith(b'SSH-'):
return ip_address
ssh_ips = await asyncio.gather(*[
_async_ping(ip_address)
for ip_address in ip_addresses
])
return [
ip_address
for ip_address in ssh_ips
if ip_address is not None
] | python | async def _async_get_sshable_ips(self, ip_addresses):
"""Return list of all IP address that could be pinged."""
async def _async_ping(ip_address):
try:
reader, writer = await asyncio.wait_for(
asyncio.open_connection(ip_address, 22), timeout=5)
except (OSError, TimeoutError):
return None
try:
line = await reader.readline()
finally:
writer.close()
if line.startswith(b'SSH-'):
return ip_address
ssh_ips = await asyncio.gather(*[
_async_ping(ip_address)
for ip_address in ip_addresses
])
return [
ip_address
for ip_address in ssh_ips
if ip_address is not None
] | [
"async",
"def",
"_async_get_sshable_ips",
"(",
"self",
",",
"ip_addresses",
")",
":",
"async",
"def",
"_async_ping",
"(",
"ip_address",
")",
":",
"try",
":",
"reader",
",",
"writer",
"=",
"await",
"asyncio",
".",
"wait_for",
"(",
"asyncio",
".",
"open_connec... | Return list of all IP address that could be pinged. | [
"Return",
"list",
"of",
"all",
"IP",
"address",
"that",
"could",
"be",
"pinged",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/machines.py#L436-L460 | train | 28,683 |
maas/python-libmaas | maas/client/flesh/machines.py | MachineSSHMixin._check_ssh | def _check_ssh(self, *args):
"""Check if SSH connection can be made to IP with username."""
ssh = subprocess.Popen(
args,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
ssh.wait()
return ssh.returncode == 0 | python | def _check_ssh(self, *args):
"""Check if SSH connection can be made to IP with username."""
ssh = subprocess.Popen(
args,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
ssh.wait()
return ssh.returncode == 0 | [
"def",
"_check_ssh",
"(",
"self",
",",
"*",
"args",
")",
":",
"ssh",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"stdin",
"=",
"subprocess",
".",
"DEVNULL",
",",
"stdout",
"=",
"subprocess",
".",
"DEVNULL",
",",
"stderr",
"=",
"subprocess",
".",... | Check if SSH connection can be made to IP with username. | [
"Check",
"if",
"SSH",
"connection",
"can",
"be",
"made",
"to",
"IP",
"with",
"username",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/machines.py#L462-L470 | train | 28,684 |
maas/python-libmaas | maas/client/flesh/machines.py | MachineSSHMixin._determine_username | def _determine_username(self, ip):
"""SSH in as root and determine the username."""
ssh = subprocess.Popen([
"ssh",
"-o", "UserKnownHostsFile=/dev/null",
"-o", "StrictHostKeyChecking=no",
"root@%s" % ip],
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
first_line = ssh.stdout.readline()
ssh.kill()
ssh.wait()
if first_line:
match = re.search(
r"Please login as the user \"(\w+)\" rather than "
r"the user \"root\".", first_line.decode('utf-8'))
if match:
return match.groups()[0]
else:
return None | python | def _determine_username(self, ip):
"""SSH in as root and determine the username."""
ssh = subprocess.Popen([
"ssh",
"-o", "UserKnownHostsFile=/dev/null",
"-o", "StrictHostKeyChecking=no",
"root@%s" % ip],
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
first_line = ssh.stdout.readline()
ssh.kill()
ssh.wait()
if first_line:
match = re.search(
r"Please login as the user \"(\w+)\" rather than "
r"the user \"root\".", first_line.decode('utf-8'))
if match:
return match.groups()[0]
else:
return None | [
"def",
"_determine_username",
"(",
"self",
",",
"ip",
")",
":",
"ssh",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"\"ssh\"",
",",
"\"-o\"",
",",
"\"UserKnownHostsFile=/dev/null\"",
",",
"\"-o\"",
",",
"\"StrictHostKeyChecking=no\"",
",",
"\"root@%s\"",
"%",
"ip"... | SSH in as root and determine the username. | [
"SSH",
"in",
"as",
"root",
"and",
"determine",
"the",
"username",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/machines.py#L472-L492 | train | 28,685 |
maas/python-libmaas | maas/client/flesh/machines.py | MachineSSHMixin.ssh | def ssh(
self, machine, *,
username=None, command=None, boot_only=False, discovered=False,
wait=300):
"""SSH into `machine`."""
start_time = time.monotonic()
with utils.Spinner() as context:
context.msg = colorized(
"{autoblue}Determining{/autoblue} best IP for %s" % (
machine.hostname))
ip_addresses = self.get_ip_addresses(
machine, boot_only=boot_only, discovered=discovered)
if len(ip_addresses) > 0:
pingable_ips = self._async_get_sshable_ips(ip_addresses)
while (len(pingable_ips) == 0 and
(time.monotonic() - start_time) < wait):
time.sleep(5)
pingable_ips = self._async_get_sshable_ips(ip_addresses)
if len(pingable_ips) == 0:
raise CommandError(
"No IP addresses on %s can be reached." % (
machine.hostname))
else:
ip = pingable_ips[0]
else:
raise CommandError(
"%s has no IP addresses." % machine.hostname)
if username is None:
context.msg = colorized(
"{autoblue}Determining{/autoblue} SSH username on %s" % (
machine.hostname))
username = self._determine_username(ip)
while (username is None and
(time.monotonic() - start_time) < wait):
username = self._determine_username(ip)
if username is None:
raise CommandError(
"Failed to determine the username for SSH.")
conn_str = "%s@%s" % (username, ip)
args = [
"ssh",
"-o", "UserKnownHostsFile=/dev/null",
"-o", "StrictHostKeyChecking=no",
conn_str
]
context.msg = colorized(
"{automagenta}Waiting{/automagenta} for SSH on %s" % (
machine.hostname))
check_args = args + ["echo"]
connectable = self._check_ssh(*check_args)
while not connectable and (time.monotonic() - start_time) < wait:
time.sleep(5)
connectable = self._check_ssh(*check_args)
if not connectable:
raise CommandError(
"SSH never started on %s using IP %s." % (
machine.hostname, ip))
if command is not None:
args.append(command)
ssh = subprocess.Popen(
args, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
ssh.wait()
return ssh.returncode | python | def ssh(
self, machine, *,
username=None, command=None, boot_only=False, discovered=False,
wait=300):
"""SSH into `machine`."""
start_time = time.monotonic()
with utils.Spinner() as context:
context.msg = colorized(
"{autoblue}Determining{/autoblue} best IP for %s" % (
machine.hostname))
ip_addresses = self.get_ip_addresses(
machine, boot_only=boot_only, discovered=discovered)
if len(ip_addresses) > 0:
pingable_ips = self._async_get_sshable_ips(ip_addresses)
while (len(pingable_ips) == 0 and
(time.monotonic() - start_time) < wait):
time.sleep(5)
pingable_ips = self._async_get_sshable_ips(ip_addresses)
if len(pingable_ips) == 0:
raise CommandError(
"No IP addresses on %s can be reached." % (
machine.hostname))
else:
ip = pingable_ips[0]
else:
raise CommandError(
"%s has no IP addresses." % machine.hostname)
if username is None:
context.msg = colorized(
"{autoblue}Determining{/autoblue} SSH username on %s" % (
machine.hostname))
username = self._determine_username(ip)
while (username is None and
(time.monotonic() - start_time) < wait):
username = self._determine_username(ip)
if username is None:
raise CommandError(
"Failed to determine the username for SSH.")
conn_str = "%s@%s" % (username, ip)
args = [
"ssh",
"-o", "UserKnownHostsFile=/dev/null",
"-o", "StrictHostKeyChecking=no",
conn_str
]
context.msg = colorized(
"{automagenta}Waiting{/automagenta} for SSH on %s" % (
machine.hostname))
check_args = args + ["echo"]
connectable = self._check_ssh(*check_args)
while not connectable and (time.monotonic() - start_time) < wait:
time.sleep(5)
connectable = self._check_ssh(*check_args)
if not connectable:
raise CommandError(
"SSH never started on %s using IP %s." % (
machine.hostname, ip))
if command is not None:
args.append(command)
ssh = subprocess.Popen(
args, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
ssh.wait()
return ssh.returncode | [
"def",
"ssh",
"(",
"self",
",",
"machine",
",",
"*",
",",
"username",
"=",
"None",
",",
"command",
"=",
"None",
",",
"boot_only",
"=",
"False",
",",
"discovered",
"=",
"False",
",",
"wait",
"=",
"300",
")",
":",
"start_time",
"=",
"time",
".",
"mon... | SSH into `machine`. | [
"SSH",
"into",
"machine",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/machines.py#L494-L560 | train | 28,686 |
maas/python-libmaas | maas/client/flesh/machines.py | cmd_deploy._get_deploy_options | def _get_deploy_options(self, options):
"""Return the deployment options based on command line."""
user_data = None
if options.user_data and options.b64_user_data:
raise CommandError(
"Cannot provide both --user-data and --b64-user-data.")
if options.b64_user_data:
user_data = options.b64_user_data
if options.user_data:
user_data = base64_file(options.user_data).decode("ascii")
return utils.remove_None({
'distro_series': options.image,
'hwe_kernel': options.hwe_kernel,
'user_data': user_data,
'comment': options.comment,
'wait': False,
}) | python | def _get_deploy_options(self, options):
"""Return the deployment options based on command line."""
user_data = None
if options.user_data and options.b64_user_data:
raise CommandError(
"Cannot provide both --user-data and --b64-user-data.")
if options.b64_user_data:
user_data = options.b64_user_data
if options.user_data:
user_data = base64_file(options.user_data).decode("ascii")
return utils.remove_None({
'distro_series': options.image,
'hwe_kernel': options.hwe_kernel,
'user_data': user_data,
'comment': options.comment,
'wait': False,
}) | [
"def",
"_get_deploy_options",
"(",
"self",
",",
"options",
")",
":",
"user_data",
"=",
"None",
"if",
"options",
".",
"user_data",
"and",
"options",
".",
"b64_user_data",
":",
"raise",
"CommandError",
"(",
"\"Cannot provide both --user-data and --b64-user-data.\"",
")"... | Return the deployment options based on command line. | [
"Return",
"the",
"deployment",
"options",
"based",
"on",
"command",
"line",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/machines.py#L633-L649 | train | 28,687 |
maas/python-libmaas | maas/client/flesh/machines.py | cmd_deploy._handle_abort | def _handle_abort(self, machine, allocated):
"""Handle the user aborting mid deployment."""
abort = yes_or_no("Abort deployment?")
if abort:
with utils.Spinner() as context:
if allocated:
context.msg = colorized(
"{autoblue}Releasing{/autoblue} %s") % (
machine.hostname)
machine.release()
context.print(colorized(
"{autoblue}Released{/autoblue} %s") % (
machine.hostname))
else:
context.msg = colorized(
"{autoblue}Aborting{/autoblue} %s") % (
machine.hostname)
machine.abort()
context.print(colorized(
"{autoblue}Aborted{/autoblue} %s") % (
machine.hostname)) | python | def _handle_abort(self, machine, allocated):
"""Handle the user aborting mid deployment."""
abort = yes_or_no("Abort deployment?")
if abort:
with utils.Spinner() as context:
if allocated:
context.msg = colorized(
"{autoblue}Releasing{/autoblue} %s") % (
machine.hostname)
machine.release()
context.print(colorized(
"{autoblue}Released{/autoblue} %s") % (
machine.hostname))
else:
context.msg = colorized(
"{autoblue}Aborting{/autoblue} %s") % (
machine.hostname)
machine.abort()
context.print(colorized(
"{autoblue}Aborted{/autoblue} %s") % (
machine.hostname)) | [
"def",
"_handle_abort",
"(",
"self",
",",
"machine",
",",
"allocated",
")",
":",
"abort",
"=",
"yes_or_no",
"(",
"\"Abort deployment?\"",
")",
"if",
"abort",
":",
"with",
"utils",
".",
"Spinner",
"(",
")",
"as",
"context",
":",
"if",
"allocated",
":",
"c... | Handle the user aborting mid deployment. | [
"Handle",
"the",
"user",
"aborting",
"mid",
"deployment",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/machines.py#L651-L671 | train | 28,688 |
maas/python-libmaas | maas/client/flesh/profiles.py | register | def register(parser):
"""Register profile commands with the given parser."""
cmd_login.register(parser)
cmd_logout.register(parser)
cmd_switch.register(parser)
cmd_profiles.register(parser) | python | def register(parser):
"""Register profile commands with the given parser."""
cmd_login.register(parser)
cmd_logout.register(parser)
cmd_switch.register(parser)
cmd_profiles.register(parser) | [
"def",
"register",
"(",
"parser",
")",
":",
"cmd_login",
".",
"register",
"(",
"parser",
")",
"cmd_logout",
".",
"register",
"(",
"parser",
")",
"cmd_switch",
".",
"register",
"(",
"parser",
")",
"cmd_profiles",
".",
"register",
"(",
"parser",
")"
] | Register profile commands with the given parser. | [
"Register",
"profile",
"commands",
"with",
"the",
"given",
"parser",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/profiles.py#L226-L231 | train | 28,689 |
maas/python-libmaas | maas/client/flesh/profiles.py | cmd_login.print_whats_next | def print_whats_next(profile):
"""Explain what to do next."""
what_next = [
"{{autogreen}}Congratulations!{{/autogreen}} You are logged in "
"to the MAAS server at {{autoblue}}{profile.url}{{/autoblue}} "
"with the profile name {{autoblue}}{profile.name}{{/autoblue}}.",
"For help with the available commands, try:",
" maas help",
]
for message in what_next:
message = message.format(profile=profile)
print(colorized(message))
print() | python | def print_whats_next(profile):
"""Explain what to do next."""
what_next = [
"{{autogreen}}Congratulations!{{/autogreen}} You are logged in "
"to the MAAS server at {{autoblue}}{profile.url}{{/autoblue}} "
"with the profile name {{autoblue}}{profile.name}{{/autoblue}}.",
"For help with the available commands, try:",
" maas help",
]
for message in what_next:
message = message.format(profile=profile)
print(colorized(message))
print() | [
"def",
"print_whats_next",
"(",
"profile",
")",
":",
"what_next",
"=",
"[",
"\"{{autogreen}}Congratulations!{{/autogreen}} You are logged in \"",
"\"to the MAAS server at {{autoblue}}{profile.url}{{/autoblue}} \"",
"\"with the profile name {{autoblue}}{profile.name}{{/autoblue}}.\"",
",",
... | Explain what to do next. | [
"Explain",
"what",
"to",
"do",
"next",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/profiles.py#L131-L143 | train | 28,690 |
maas/python-libmaas | maas/client/utils/auth.py | obtain_credentials | def obtain_credentials(credentials):
"""Prompt for credentials if possible.
If the credentials are "-" then read from stdin without interactive
prompting.
"""
if credentials == "-":
credentials = sys.stdin.readline().strip()
elif credentials is None:
credentials = try_getpass(
"API key (leave empty for anonymous access): ")
# Ensure that the credentials have a valid form.
if credentials and not credentials.isspace():
return Credentials.parse(credentials)
else:
return None | python | def obtain_credentials(credentials):
"""Prompt for credentials if possible.
If the credentials are "-" then read from stdin without interactive
prompting.
"""
if credentials == "-":
credentials = sys.stdin.readline().strip()
elif credentials is None:
credentials = try_getpass(
"API key (leave empty for anonymous access): ")
# Ensure that the credentials have a valid form.
if credentials and not credentials.isspace():
return Credentials.parse(credentials)
else:
return None | [
"def",
"obtain_credentials",
"(",
"credentials",
")",
":",
"if",
"credentials",
"==",
"\"-\"",
":",
"credentials",
"=",
"sys",
".",
"stdin",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
"elif",
"credentials",
"is",
"None",
":",
"credentials",
"=",
... | Prompt for credentials if possible.
If the credentials are "-" then read from stdin without interactive
prompting. | [
"Prompt",
"for",
"credentials",
"if",
"possible",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/auth.py#L36-L51 | train | 28,691 |
maas/python-libmaas | maas/client/bones/__init__.py | SessionAPI.fromURL | async def fromURL(
cls, url, *, credentials=None, insecure=False):
"""Return a `SessionAPI` for a given MAAS instance."""
try:
description = await helpers.fetch_api_description(
url, insecure=insecure)
except helpers.RemoteError as error:
# For now just re-raise as SessionError.
raise SessionError(str(error))
else:
session = cls(description, credentials)
session.insecure = insecure
return session | python | async def fromURL(
cls, url, *, credentials=None, insecure=False):
"""Return a `SessionAPI` for a given MAAS instance."""
try:
description = await helpers.fetch_api_description(
url, insecure=insecure)
except helpers.RemoteError as error:
# For now just re-raise as SessionError.
raise SessionError(str(error))
else:
session = cls(description, credentials)
session.insecure = insecure
return session | [
"async",
"def",
"fromURL",
"(",
"cls",
",",
"url",
",",
"*",
",",
"credentials",
"=",
"None",
",",
"insecure",
"=",
"False",
")",
":",
"try",
":",
"description",
"=",
"await",
"helpers",
".",
"fetch_api_description",
"(",
"url",
",",
"insecure",
"=",
"... | Return a `SessionAPI` for a given MAAS instance. | [
"Return",
"a",
"SessionAPI",
"for",
"a",
"given",
"MAAS",
"instance",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/bones/__init__.py#L36-L48 | train | 28,692 |
maas/python-libmaas | maas/client/bones/__init__.py | SessionAPI.fromProfileName | def fromProfileName(cls, name):
"""Return a `SessionAPI` from a given configuration profile name.
:see: `ProfileStore`.
"""
with profiles.ProfileStore.open() as config:
return cls.fromProfile(config.load(name)) | python | def fromProfileName(cls, name):
"""Return a `SessionAPI` from a given configuration profile name.
:see: `ProfileStore`.
"""
with profiles.ProfileStore.open() as config:
return cls.fromProfile(config.load(name)) | [
"def",
"fromProfileName",
"(",
"cls",
",",
"name",
")",
":",
"with",
"profiles",
".",
"ProfileStore",
".",
"open",
"(",
")",
"as",
"config",
":",
"return",
"cls",
".",
"fromProfile",
"(",
"config",
".",
"load",
"(",
"name",
")",
")"
] | Return a `SessionAPI` from a given configuration profile name.
:see: `ProfileStore`. | [
"Return",
"a",
"SessionAPI",
"from",
"a",
"given",
"configuration",
"profile",
"name",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/bones/__init__.py#L59-L65 | train | 28,693 |
maas/python-libmaas | maas/client/bones/__init__.py | SessionAPI.login | async def login(
cls, url, *, username=None, password=None, insecure=False):
"""Make a `SessionAPI` by logging-in with a username and password.
:return: A tuple of ``profile`` and ``session``, where the former is
an unsaved `Profile` instance, and the latter is a `SessionAPI`
instance made using the profile.
"""
profile = await helpers.login(
url=url, username=username, password=password, insecure=insecure)
session = cls(profile.description, profile.credentials)
session.insecure = insecure
return profile, session | python | async def login(
cls, url, *, username=None, password=None, insecure=False):
"""Make a `SessionAPI` by logging-in with a username and password.
:return: A tuple of ``profile`` and ``session``, where the former is
an unsaved `Profile` instance, and the latter is a `SessionAPI`
instance made using the profile.
"""
profile = await helpers.login(
url=url, username=username, password=password, insecure=insecure)
session = cls(profile.description, profile.credentials)
session.insecure = insecure
return profile, session | [
"async",
"def",
"login",
"(",
"cls",
",",
"url",
",",
"*",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"insecure",
"=",
"False",
")",
":",
"profile",
"=",
"await",
"helpers",
".",
"login",
"(",
"url",
"=",
"url",
",",
"username... | Make a `SessionAPI` by logging-in with a username and password.
:return: A tuple of ``profile`` and ``session``, where the former is
an unsaved `Profile` instance, and the latter is a `SessionAPI`
instance made using the profile. | [
"Make",
"a",
"SessionAPI",
"by",
"logging",
"-",
"in",
"with",
"a",
"username",
"and",
"password",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/bones/__init__.py#L69-L81 | train | 28,694 |
maas/python-libmaas | maas/client/bones/__init__.py | SessionAPI.connect | async def connect(
cls, url, *, apikey=None, insecure=False):
"""Make a `SessionAPI` by connecting with an apikey.
:return: A tuple of ``profile`` and ``session``, where the former is
an unsaved `Profile` instance, and the latter is a `SessionAPI`
instance made using the profile.
"""
profile = await helpers.connect(
url=url, apikey=apikey, insecure=insecure)
session = cls(profile.description, profile.credentials)
session.insecure = insecure
return profile, session | python | async def connect(
cls, url, *, apikey=None, insecure=False):
"""Make a `SessionAPI` by connecting with an apikey.
:return: A tuple of ``profile`` and ``session``, where the former is
an unsaved `Profile` instance, and the latter is a `SessionAPI`
instance made using the profile.
"""
profile = await helpers.connect(
url=url, apikey=apikey, insecure=insecure)
session = cls(profile.description, profile.credentials)
session.insecure = insecure
return profile, session | [
"async",
"def",
"connect",
"(",
"cls",
",",
"url",
",",
"*",
",",
"apikey",
"=",
"None",
",",
"insecure",
"=",
"False",
")",
":",
"profile",
"=",
"await",
"helpers",
".",
"connect",
"(",
"url",
"=",
"url",
",",
"apikey",
"=",
"apikey",
",",
"insecu... | Make a `SessionAPI` by connecting with an apikey.
:return: A tuple of ``profile`` and ``session``, where the former is
an unsaved `Profile` instance, and the latter is a `SessionAPI`
instance made using the profile. | [
"Make",
"a",
"SessionAPI",
"by",
"connecting",
"with",
"an",
"apikey",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/bones/__init__.py#L85-L97 | train | 28,695 |
maas/python-libmaas | maas/client/bones/__init__.py | CallAPI.rebind | def rebind(self, **params):
"""Rebind the parameters into the URI.
:return: A new `CallAPI` instance with the new parameters.
"""
new_params = self.__params.copy()
new_params.update(params)
return self.__class__(new_params, self.__action) | python | def rebind(self, **params):
"""Rebind the parameters into the URI.
:return: A new `CallAPI` instance with the new parameters.
"""
new_params = self.__params.copy()
new_params.update(params)
return self.__class__(new_params, self.__action) | [
"def",
"rebind",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"new_params",
"=",
"self",
".",
"__params",
".",
"copy",
"(",
")",
"new_params",
".",
"update",
"(",
"params",
")",
"return",
"self",
".",
"__class__",
"(",
"new_params",
",",
"self",
"... | Rebind the parameters into the URI.
:return: A new `CallAPI` instance with the new parameters. | [
"Rebind",
"the",
"parameters",
"into",
"the",
"URI",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/bones/__init__.py#L382-L389 | train | 28,696 |
maas/python-libmaas | maas/client/bones/__init__.py | CallAPI.call | def call(self, **data):
"""Issue the call.
:param data: Data to pass in the *body* of the request.
"""
uri, body, headers = self.prepare(data)
return self.dispatch(uri, body, headers) | python | def call(self, **data):
"""Issue the call.
:param data: Data to pass in the *body* of the request.
"""
uri, body, headers = self.prepare(data)
return self.dispatch(uri, body, headers) | [
"def",
"call",
"(",
"self",
",",
"*",
"*",
"data",
")",
":",
"uri",
",",
"body",
",",
"headers",
"=",
"self",
".",
"prepare",
"(",
"data",
")",
"return",
"self",
".",
"dispatch",
"(",
"uri",
",",
"body",
",",
"headers",
")"
] | Issue the call.
:param data: Data to pass in the *body* of the request. | [
"Issue",
"the",
"call",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/bones/__init__.py#L391-L397 | train | 28,697 |
maas/python-libmaas | maas/client/bones/__init__.py | CallAPI.prepare | def prepare(self, data):
"""Prepare the call payload.
This is used by `call` and can be overridden to marshal the request in
a different way.
:param data: Data to pass in the *body* of the request.
:type data: dict
"""
def expand(data):
for name, value in data.items():
if isinstance(value, Iterable):
for value in value:
yield name, value
else:
yield name, value
# `data` must be an iterable yielding 2-tuples.
if self.action.method in ("GET", "DELETE"):
# MAAS does not expect an entity-body for GET or DELETE.
data = expand(data)
else:
# MAAS expects and entity-body for PUT and POST.
data = data.items()
# Bundle things up ready to throw over the wire.
uri, body, headers = utils.prepare_payload(
self.action.op, self.action.method, self.uri, data)
# Headers are returned as a list, but they must be a dict for
# the signing machinery.
headers = dict(headers)
# Sign request if credentials have been provided.
credentials = self.action.handler.session.credentials
if credentials is not None:
utils.sign(uri, headers, credentials)
return uri, body, headers | python | def prepare(self, data):
"""Prepare the call payload.
This is used by `call` and can be overridden to marshal the request in
a different way.
:param data: Data to pass in the *body* of the request.
:type data: dict
"""
def expand(data):
for name, value in data.items():
if isinstance(value, Iterable):
for value in value:
yield name, value
else:
yield name, value
# `data` must be an iterable yielding 2-tuples.
if self.action.method in ("GET", "DELETE"):
# MAAS does not expect an entity-body for GET or DELETE.
data = expand(data)
else:
# MAAS expects and entity-body for PUT and POST.
data = data.items()
# Bundle things up ready to throw over the wire.
uri, body, headers = utils.prepare_payload(
self.action.op, self.action.method, self.uri, data)
# Headers are returned as a list, but they must be a dict for
# the signing machinery.
headers = dict(headers)
# Sign request if credentials have been provided.
credentials = self.action.handler.session.credentials
if credentials is not None:
utils.sign(uri, headers, credentials)
return uri, body, headers | [
"def",
"prepare",
"(",
"self",
",",
"data",
")",
":",
"def",
"expand",
"(",
"data",
")",
":",
"for",
"name",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Iterable",
")",
":",
"for",
"value",
"in... | Prepare the call payload.
This is used by `call` and can be overridden to marshal the request in
a different way.
:param data: Data to pass in the *body* of the request.
:type data: dict | [
"Prepare",
"the",
"call",
"payload",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/bones/__init__.py#L399-L437 | train | 28,698 |
maas/python-libmaas | maas/client/bones/__init__.py | CallAPI.dispatch | async def dispatch(self, uri, body, headers):
"""Dispatch the call via HTTP.
This is used by `call` and can be overridden to use a different HTTP
library.
"""
insecure = self.action.handler.session.insecure
connector = aiohttp.TCPConnector(verify_ssl=(not insecure))
session = aiohttp.ClientSession(connector=connector)
async with session:
response = await session.request(
self.action.method, uri, data=body,
headers=_prefer_json(headers))
async with response:
# Fetch the raw body content.
content = await response.read()
# Debug output.
if self.action.handler.session.debug:
print(response)
# 2xx status codes are all okay.
if response.status // 100 != 2:
request = {
"body": body,
"headers": headers,
"method": self.action.method,
"uri": uri,
}
raise CallError(request, response, content, self)
# Decode from JSON if that's what it's declared as.
if response.content_type is None:
data = await response.read()
elif response.content_type.endswith('/json'):
data = await response.json()
else:
data = await response.read()
if response.content_type is None:
data = content
elif response.content_type.endswith('/json'):
# JSON should always be UTF-8.
data = json.loads(content.decode("utf-8"))
else:
data = content
return CallResult(response, content, data) | python | async def dispatch(self, uri, body, headers):
"""Dispatch the call via HTTP.
This is used by `call` and can be overridden to use a different HTTP
library.
"""
insecure = self.action.handler.session.insecure
connector = aiohttp.TCPConnector(verify_ssl=(not insecure))
session = aiohttp.ClientSession(connector=connector)
async with session:
response = await session.request(
self.action.method, uri, data=body,
headers=_prefer_json(headers))
async with response:
# Fetch the raw body content.
content = await response.read()
# Debug output.
if self.action.handler.session.debug:
print(response)
# 2xx status codes are all okay.
if response.status // 100 != 2:
request = {
"body": body,
"headers": headers,
"method": self.action.method,
"uri": uri,
}
raise CallError(request, response, content, self)
# Decode from JSON if that's what it's declared as.
if response.content_type is None:
data = await response.read()
elif response.content_type.endswith('/json'):
data = await response.json()
else:
data = await response.read()
if response.content_type is None:
data = content
elif response.content_type.endswith('/json'):
# JSON should always be UTF-8.
data = json.loads(content.decode("utf-8"))
else:
data = content
return CallResult(response, content, data) | [
"async",
"def",
"dispatch",
"(",
"self",
",",
"uri",
",",
"body",
",",
"headers",
")",
":",
"insecure",
"=",
"self",
".",
"action",
".",
"handler",
".",
"session",
".",
"insecure",
"connector",
"=",
"aiohttp",
".",
"TCPConnector",
"(",
"verify_ssl",
"=",... | Dispatch the call via HTTP.
This is used by `call` and can be overridden to use a different HTTP
library. | [
"Dispatch",
"the",
"call",
"via",
"HTTP",
"."
] | 4092c68ef7fb1753efc843569848e2bcc3415002 | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/bones/__init__.py#L440-L487 | train | 28,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.