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:... | 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:... | [
"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 `... | 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 `... | [
"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/"
cml... | 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/"
cml... | [
"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.w... | 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.w... | [
"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 resp... | 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 resp... | [
"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... | 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... | [
"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 ig... | 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 ig... | [
"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 = [
sel... | 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 = [
sel... | [
"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.ko... | 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.ko... | [
"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'... | 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'... | [
"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 = label... | 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 = label... | [
"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
... | 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
... | [
"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 t... | 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 t... | [
"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 (em... | [
"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 = (
... | 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 = (
... | [
"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'),
... | [
"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... | 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... | [
"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' % (c... | 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' % (c... | [
"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.
... | 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.
... | [
"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... | [
"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 == 'autho... | 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 == 'autho... | [
"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(expirat... | 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(expirat... | [
"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.
:para... | 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.
:para... | [
"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 ... | [
"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:
... | 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:
... | [
"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`.
... | 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`.
... | [
"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 \
... | 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 \
... | [
"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... | 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... | [
"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_datet... | 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_datet... | [
"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 ge... | 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 ge... | [
"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 = {'crea... | [
"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 hasht... | 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 hasht... | [
"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:
... | [
"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 ... | 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 ... | [
"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... | 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... | [
"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 return... | [
"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 se... | 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 se... | [
"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",
... "n... | [
"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
... | 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
... | [
"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 i... | [
"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 expect... | 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 expect... | [
"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:
Unexpected... | [
"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... | 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... | [
"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
... | 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
... | [
"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"... | [
"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:
l... | 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:
l... | [
"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 whe... | [
"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.get... | 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.get... | [
"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... | [
"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
mat... | 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
mat... | [
"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... | [
"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://... | 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://... | [
"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... | [
"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... | 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... | [
"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",
"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 _la... | 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 _la... | [
"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 (o... | 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 (o... | [
"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_qu... | [
"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 (o... | 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 (o... | [
"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_retwe... | [
"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_e... | 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_e... | [
"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)
... | [
"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
... | 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
... | [
"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, se... | 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, se... | [
"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.pa... | 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.pa... | [
"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(... | 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(... | [
"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('tem... | 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('tem... | [
"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)
... | 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)
... | [
"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_I... | 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_I... | [
"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 = Op... | 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 = Op... | [
"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, ... | 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, ... | [
"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.impli... | 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.impli... | [
"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()
... | 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()
... | [
"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 se... | 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 se... | [
"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)
... | 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)
... | [
"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")
... | 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")
... | [
"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_12... | 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_12... | [
"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(
iterto... | 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(
iterto... | [
"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.wri... | 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.wri... | [
"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... | 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... | [
"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())
... | 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())
... | [
"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:
... | 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:
... | [
"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... | 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... | [
"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_... | 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_... | [
"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_f... | 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_f... | [
"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, ac... | 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, ac... | [
"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(hostn... | 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(hostn... | [
"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=(
"... | 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=(
"... | [
"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_addres... | 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_addres... | [
"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)
... | 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)
... | [
"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,
s... | 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,
s... | [
"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}Deter... | 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}Deter... | [
"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_... | 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_... | [
"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}... | 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}... | [
"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}}.... | 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}}.... | [
"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(
... | 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(
... | [
"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... | 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... | [
"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`
... | 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`
... | [
"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... | 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... | [
"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, val... | 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, val... | [
"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))
... | 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))
... | [
"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.