repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
pymc-devs/pymc | pymc/StepMethods.py | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1204-L1214 | def check_type(self):
"""Make sure each stochastic has a correct type, and identify discrete stochastics."""
self.isdiscrete = {}
for stochastic in self.stochastics:
if stochastic.dtype in integer_dtypes:
self.isdiscrete[stochastic] = True
elif stochastic.dtype in bool_dtypes:
raise ValueError(
'Binary stochastics not supported by AdaptativeMetropolis.')
else:
self.isdiscrete[stochastic] = False | [
"def",
"check_type",
"(",
"self",
")",
":",
"self",
".",
"isdiscrete",
"=",
"{",
"}",
"for",
"stochastic",
"in",
"self",
".",
"stochastics",
":",
"if",
"stochastic",
".",
"dtype",
"in",
"integer_dtypes",
":",
"self",
".",
"isdiscrete",
"[",
"stochastic",
... | Make sure each stochastic has a correct type, and identify discrete stochastics. | [
"Make",
"sure",
"each",
"stochastic",
"has",
"a",
"correct",
"type",
"and",
"identify",
"discrete",
"stochastics",
"."
] | python | train |
GoogleCloudPlatform/appengine-pipelines | python/src/pipeline/models.py | https://github.com/GoogleCloudPlatform/appengine-pipelines/blob/277394648dac3e8214677af898935d07399ac8e1/python/src/pipeline/models.py#L251-L271 | def to_barrier_key(cls, barrier_index_key):
"""Converts a _BarrierIndex key to a _BarrierRecord key.
Args:
barrier_index_key: db.Key for a _BarrierIndex entity.
Returns:
db.Key for the corresponding _BarrierRecord entity.
"""
barrier_index_path = barrier_index_key.to_path()
# Pick out the items from the _BarrierIndex key path that we need to
# construct the _BarrierRecord key path.
(pipeline_kind, dependent_pipeline_id,
unused_kind, purpose) = barrier_index_path[-4:]
barrier_record_path = (
pipeline_kind, dependent_pipeline_id,
_BarrierRecord.kind(), purpose)
return db.Key.from_path(*barrier_record_path) | [
"def",
"to_barrier_key",
"(",
"cls",
",",
"barrier_index_key",
")",
":",
"barrier_index_path",
"=",
"barrier_index_key",
".",
"to_path",
"(",
")",
"# Pick out the items from the _BarrierIndex key path that we need to",
"# construct the _BarrierRecord key path.",
"(",
"pipeline_ki... | Converts a _BarrierIndex key to a _BarrierRecord key.
Args:
barrier_index_key: db.Key for a _BarrierIndex entity.
Returns:
db.Key for the corresponding _BarrierRecord entity. | [
"Converts",
"a",
"_BarrierIndex",
"key",
"to",
"a",
"_BarrierRecord",
"key",
"."
] | python | train |
mila-iqia/fuel | fuel/server.py | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/server.py#L48-L81 | def recv_arrays(socket):
"""Receive a list of NumPy arrays.
Parameters
----------
socket : :class:`zmq.Socket`
The socket to receive the arrays on.
Returns
-------
list
A list of :class:`numpy.ndarray` objects.
Raises
------
StopIteration
If the first JSON object received contains the key `stop`,
signifying that the server has finished a single epoch.
"""
headers = socket.recv_json()
if 'stop' in headers:
raise StopIteration
arrays = []
for header in headers:
data = socket.recv(copy=False)
buf = buffer_(data)
array = numpy.frombuffer(buf, dtype=numpy.dtype(header['descr']))
array.shape = header['shape']
if header['fortran_order']:
array.shape = header['shape'][::-1]
array = array.transpose()
arrays.append(array)
return arrays | [
"def",
"recv_arrays",
"(",
"socket",
")",
":",
"headers",
"=",
"socket",
".",
"recv_json",
"(",
")",
"if",
"'stop'",
"in",
"headers",
":",
"raise",
"StopIteration",
"arrays",
"=",
"[",
"]",
"for",
"header",
"in",
"headers",
":",
"data",
"=",
"socket",
... | Receive a list of NumPy arrays.
Parameters
----------
socket : :class:`zmq.Socket`
The socket to receive the arrays on.
Returns
-------
list
A list of :class:`numpy.ndarray` objects.
Raises
------
StopIteration
If the first JSON object received contains the key `stop`,
signifying that the server has finished a single epoch. | [
"Receive",
"a",
"list",
"of",
"NumPy",
"arrays",
"."
] | python | train |
welbornprod/colr | colr/colr.py | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/colr.py#L904-L920 | def _ext_attr_to_partial(self, name, kwarg_key):
""" Convert a string like '233' or 'aliceblue' into partial for
self.chained.
"""
try:
intval = int(name)
except ValueError:
# Try as an extended name_data name.
info = name_data.get(name, None)
if info is None:
# Not an int value or name_data name.
return None
kws = {kwarg_key: info['code']}
return partial(self.chained, **kws)
# Integer str passed, use the int value.
kws = {kwarg_key: intval}
return partial(self.chained, **kws) | [
"def",
"_ext_attr_to_partial",
"(",
"self",
",",
"name",
",",
"kwarg_key",
")",
":",
"try",
":",
"intval",
"=",
"int",
"(",
"name",
")",
"except",
"ValueError",
":",
"# Try as an extended name_data name.",
"info",
"=",
"name_data",
".",
"get",
"(",
"name",
"... | Convert a string like '233' or 'aliceblue' into partial for
self.chained. | [
"Convert",
"a",
"string",
"like",
"233",
"or",
"aliceblue",
"into",
"partial",
"for",
"self",
".",
"chained",
"."
] | python | train |
ampl/amplpy | amplpy/ampl.py | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L1084-L1090 | def _startRecording(self, filename):
"""
Start recording the session to a file for debug purposes.
"""
self.setOption('_log_file_name', filename)
self.setOption('_log_input_only', True)
self.setOption('_log', True) | [
"def",
"_startRecording",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"setOption",
"(",
"'_log_file_name'",
",",
"filename",
")",
"self",
".",
"setOption",
"(",
"'_log_input_only'",
",",
"True",
")",
"self",
".",
"setOption",
"(",
"'_log'",
",",
"... | Start recording the session to a file for debug purposes. | [
"Start",
"recording",
"the",
"session",
"to",
"a",
"file",
"for",
"debug",
"purposes",
"."
] | python | train |
gabstopper/smc-python | smc/core/collection.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/collection.py#L903-L919 | def add_tunnel_interface(self, interface_id, address, network_value,
zone_ref=None, comment=None):
"""
Creates a tunnel interface for a virtual engine.
:param str,int interface_id: the tunnel id for the interface, used as nicid also
:param str address: ip address of interface
:param str network_value: network cidr for interface; format: 1.1.1.0/24
:param str zone_ref: zone reference for interface can be name, href or Zone
:raises EngineCommandFailed: failure during creation
:return: None
"""
interfaces = [{'nodes': [{'address': address, 'network_value': network_value}]}]
interface = {'interface_id': interface_id, 'interfaces': interfaces,
'zone_ref': zone_ref, 'comment': comment}
tunnel_interface = TunnelInterface(**interface)
self._engine.add_interface(tunnel_interface) | [
"def",
"add_tunnel_interface",
"(",
"self",
",",
"interface_id",
",",
"address",
",",
"network_value",
",",
"zone_ref",
"=",
"None",
",",
"comment",
"=",
"None",
")",
":",
"interfaces",
"=",
"[",
"{",
"'nodes'",
":",
"[",
"{",
"'address'",
":",
"address",
... | Creates a tunnel interface for a virtual engine.
:param str,int interface_id: the tunnel id for the interface, used as nicid also
:param str address: ip address of interface
:param str network_value: network cidr for interface; format: 1.1.1.0/24
:param str zone_ref: zone reference for interface can be name, href or Zone
:raises EngineCommandFailed: failure during creation
:return: None | [
"Creates",
"a",
"tunnel",
"interface",
"for",
"a",
"virtual",
"engine",
"."
] | python | train |
juanifioren/django-oidc-provider | oidc_provider/lib/utils/common.py | https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/utils/common.py#L145-L151 | def get_browser_state_or_default(request):
"""
Determine value to use as session state.
"""
key = (request.session.session_key or
settings.get('OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY'))
return sha224(key.encode('utf-8')).hexdigest() | [
"def",
"get_browser_state_or_default",
"(",
"request",
")",
":",
"key",
"=",
"(",
"request",
".",
"session",
".",
"session_key",
"or",
"settings",
".",
"get",
"(",
"'OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY'",
")",
")",
"return",
"sha224",
"(",
"key",
".",
"e... | Determine value to use as session state. | [
"Determine",
"value",
"to",
"use",
"as",
"session",
"state",
"."
] | python | train |
sorgerlab/indra | indra/tools/machine/cli.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/machine/cli.py#L30-L42 | def make(directory):
"""Makes a RAS Machine directory"""
if os.path.exists(directory):
if os.path.isdir(directory):
click.echo('Directory already exists')
else:
click.echo('Path exists and is not a directory')
sys.exit()
os.makedirs(directory)
os.mkdir(os.path.join(directory, 'jsons'))
copy_default_config(os.path.join(directory, 'config.yaml')) | [
"def",
"make",
"(",
"directory",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"click",
".",
"echo",
"(",
"'Directory already exists'",
")",
"else",
":... | Makes a RAS Machine directory | [
"Makes",
"a",
"RAS",
"Machine",
"directory"
] | python | train |
fermiPy/fermipy | fermipy/jobs/scatter_gather.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/scatter_gather.py#L459-L509 | def resubmit(self, stream=sys.stdout, fail_running=False, resubmit_failed=False):
"""Function to resubmit failed jobs and collect results
Parameters
-----------
stream : `file`
Stream that this function will print to,
Must have 'write' function.
fail_running : `bool`
If True, consider running jobs as failed
resubmit_failed : bool
Resubmit failed jobs.
Returns
-------
status_vect : `JobStatusVector`
Vector that summarize the number of jobs in various states.
"""
self._build_job_dict()
status_vect = self.check_status(stream, check_once=True, fail_pending=True,
fail_running=fail_running)
status = status_vect.get_status()
if status == JobStatus.done:
return status
failed_jobs = self._scatter_link.get_failed_jobs(True, True)
if failed_jobs:
scatter_status = self._interface.submit_jobs(self._scatter_link, failed_jobs,
job_archive=self._job_archive,
stream=stream)
if scatter_status == JobStatus.failed:
return JobStatus.failed
status_vect = self.check_status(stream, write_status=True)
status = status_vect.get_status()
if status == JobStatus.partial_failed:
if resubmit_failed:
sys.stdout.write("Resubmitting partially failed link %s\n" %
self.full_linkname)
status_vect = self.resubmit(stream=stream, fail_running=False, resubmit_failed=False)
else:
sys.stdout.write("NOT resubmitting partially failed link %s\n" %
self.full_linkname)
if self.args['dry_run']:
return JobStatus.unknown
return status_vect | [
"def",
"resubmit",
"(",
"self",
",",
"stream",
"=",
"sys",
".",
"stdout",
",",
"fail_running",
"=",
"False",
",",
"resubmit_failed",
"=",
"False",
")",
":",
"self",
".",
"_build_job_dict",
"(",
")",
"status_vect",
"=",
"self",
".",
"check_status",
"(",
"... | Function to resubmit failed jobs and collect results
Parameters
-----------
stream : `file`
Stream that this function will print to,
Must have 'write' function.
fail_running : `bool`
If True, consider running jobs as failed
resubmit_failed : bool
Resubmit failed jobs.
Returns
-------
status_vect : `JobStatusVector`
Vector that summarize the number of jobs in various states. | [
"Function",
"to",
"resubmit",
"failed",
"jobs",
"and",
"collect",
"results"
] | python | train |
allenai/allennlp | scripts/reformat_text2sql_data.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/reformat_text2sql_data.py#L38-L91 | def main(output_directory: int, data: str) -> None:
"""
Processes the text2sql data into the following directory structure:
``dataset/{query_split, question_split}/{train,dev,test}.json``
for datasets which have train, dev and test splits, or:
``dataset/{query_split, question_split}/{split_{split_id}}.json``
for datasets which use cross validation.
The JSON format is identical to the original datasets, apart from they
are split into separate files with respect to the split_type. This means that
for the question split, all of the sql data is duplicated for each sentence
which is bucketed together as having the same semantics.
As an example, the following blob would be put "as-is" into the query split
dataset, and split into two datasets with identical blobs for the question split,
differing only in the "sentence" key, where blob1 would end up in the train split
and blob2 would be in the dev split, with the rest of the json duplicated in each.
{
"comments": [],
"old-name": "",
"query-split": "train",
"sentences": [{blob1, "question-split": "train"}, {blob2, "question-split": "dev"}],
"sql": [],
"variables": []
},
Parameters
----------
output_directory : str, required.
The output directory.
data: str, default = None
The path to the data director of https://github.com/jkkummerfeld/text2sql-data.
"""
json_files = glob.glob(os.path.join(data, "*.json"))
for dataset in json_files:
dataset_name = os.path.basename(dataset)[:-5]
print(f"Processing dataset: {dataset} into query and question "
f"splits at output path: {output_directory + '/' + dataset_name}")
full_dataset = json.load(open(dataset))
if not isinstance(full_dataset, list):
full_dataset = [full_dataset]
for split_type in ["query_split", "question_split"]:
dataset_out = os.path.join(output_directory, dataset_name, split_type)
for split, split_dataset in process_dataset(full_dataset, split_type):
dataset_out = os.path.join(output_directory, dataset_name, split_type)
os.makedirs(dataset_out, exist_ok=True)
json.dump(split_dataset, open(os.path.join(dataset_out, split), "w"), indent=4) | [
"def",
"main",
"(",
"output_directory",
":",
"int",
",",
"data",
":",
"str",
")",
"->",
"None",
":",
"json_files",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"data",
",",
"\"*.json\"",
")",
")",
"for",
"dataset",
"in",
"jso... | Processes the text2sql data into the following directory structure:
``dataset/{query_split, question_split}/{train,dev,test}.json``
for datasets which have train, dev and test splits, or:
``dataset/{query_split, question_split}/{split_{split_id}}.json``
for datasets which use cross validation.
The JSON format is identical to the original datasets, apart from they
are split into separate files with respect to the split_type. This means that
for the question split, all of the sql data is duplicated for each sentence
which is bucketed together as having the same semantics.
As an example, the following blob would be put "as-is" into the query split
dataset, and split into two datasets with identical blobs for the question split,
differing only in the "sentence" key, where blob1 would end up in the train split
and blob2 would be in the dev split, with the rest of the json duplicated in each.
{
"comments": [],
"old-name": "",
"query-split": "train",
"sentences": [{blob1, "question-split": "train"}, {blob2, "question-split": "dev"}],
"sql": [],
"variables": []
},
Parameters
----------
output_directory : str, required.
The output directory.
data: str, default = None
The path to the data director of https://github.com/jkkummerfeld/text2sql-data. | [
"Processes",
"the",
"text2sql",
"data",
"into",
"the",
"following",
"directory",
"structure",
":"
] | python | train |
uw-it-aca/uw-restclients-canvas | uw_canvas/admins.py | https://github.com/uw-it-aca/uw-restclients-canvas/blob/9845faf33d49a8f06908efc22640c001116d6ea2/uw_canvas/admins.py#L9-L20 | def get_admins(self, account_id, params={}):
"""
Return a list of the admins in the account.
https://canvas.instructure.com/doc/api/admins.html#method.admins.index
"""
url = ADMINS_API.format(account_id)
admins = []
for data in self._get_paged_resource(url, params=params):
admins.append(CanvasAdmin(data=data))
return admins | [
"def",
"get_admins",
"(",
"self",
",",
"account_id",
",",
"params",
"=",
"{",
"}",
")",
":",
"url",
"=",
"ADMINS_API",
".",
"format",
"(",
"account_id",
")",
"admins",
"=",
"[",
"]",
"for",
"data",
"in",
"self",
".",
"_get_paged_resource",
"(",
"url",
... | Return a list of the admins in the account.
https://canvas.instructure.com/doc/api/admins.html#method.admins.index | [
"Return",
"a",
"list",
"of",
"the",
"admins",
"in",
"the",
"account",
"."
] | python | test |
manahl/arctic | arctic/_compression.py | https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/_compression.py#L126-L140 | def decompress_array(str_list):
"""
Decompress a list of strings
"""
global _compress_thread_pool
if not str_list:
return str_list
if not ENABLE_PARALLEL or len(str_list) <= LZ4_N_PARALLEL:
return [lz4_decompress(chunk) for chunk in str_list]
if _compress_thread_pool is None:
_compress_thread_pool = ThreadPool(LZ4_WORKERS)
return _compress_thread_pool.map(lz4_decompress, str_list) | [
"def",
"decompress_array",
"(",
"str_list",
")",
":",
"global",
"_compress_thread_pool",
"if",
"not",
"str_list",
":",
"return",
"str_list",
"if",
"not",
"ENABLE_PARALLEL",
"or",
"len",
"(",
"str_list",
")",
"<=",
"LZ4_N_PARALLEL",
":",
"return",
"[",
"lz4_decom... | Decompress a list of strings | [
"Decompress",
"a",
"list",
"of",
"strings"
] | python | train |
wavycloud/pyboto3 | pyboto3/elasticbeanstalk.py | https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/elasticbeanstalk.py#L1672-L1753 | def describe_events(ApplicationName=None, VersionLabel=None, TemplateName=None, EnvironmentId=None, EnvironmentName=None, PlatformArn=None, RequestId=None, Severity=None, StartTime=None, EndTime=None, MaxRecords=None, NextToken=None):
"""
Returns list of event descriptions matching criteria up to the last 6 weeks.
See also: AWS API Documentation
Examples
The following operation retrieves events for an environment named my-env:
Expected Output:
:example: response = client.describe_events(
ApplicationName='string',
VersionLabel='string',
TemplateName='string',
EnvironmentId='string',
EnvironmentName='string',
PlatformArn='string',
RequestId='string',
Severity='TRACE'|'DEBUG'|'INFO'|'WARN'|'ERROR'|'FATAL',
StartTime=datetime(2015, 1, 1),
EndTime=datetime(2015, 1, 1),
MaxRecords=123,
NextToken='string'
)
:type ApplicationName: string
:param ApplicationName: If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only those associated with this application.
:type VersionLabel: string
:param VersionLabel: If specified, AWS Elastic Beanstalk restricts the returned descriptions to those associated with this application version.
:type TemplateName: string
:param TemplateName: If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that are associated with this environment configuration.
:type EnvironmentId: string
:param EnvironmentId: If specified, AWS Elastic Beanstalk restricts the returned descriptions to those associated with this environment.
:type EnvironmentName: string
:param EnvironmentName: If specified, AWS Elastic Beanstalk restricts the returned descriptions to those associated with this environment.
:type PlatformArn: string
:param PlatformArn: The ARN of the version of the custom platform.
:type RequestId: string
:param RequestId: If specified, AWS Elastic Beanstalk restricts the described events to include only those associated with this request ID.
:type Severity: string
:param Severity: If specified, limits the events returned from this call to include only those with the specified severity or higher.
:type StartTime: datetime
:param StartTime: If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that occur on or after this time.
:type EndTime: datetime
:param EndTime: If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that occur up to, but not including, the EndTime .
:type MaxRecords: integer
:param MaxRecords: Specifies the maximum number of events that can be returned, beginning with the most recent event.
:type NextToken: string
:param NextToken: Pagination token. If specified, the events return the next batch of results.
:rtype: dict
:return: {
'Events': [
{
'EventDate': datetime(2015, 1, 1),
'Message': 'string',
'ApplicationName': 'string',
'VersionLabel': 'string',
'TemplateName': 'string',
'EnvironmentName': 'string',
'PlatformArn': 'string',
'RequestId': 'string',
'Severity': 'TRACE'|'DEBUG'|'INFO'|'WARN'|'ERROR'|'FATAL'
},
],
'NextToken': 'string'
}
"""
pass | [
"def",
"describe_events",
"(",
"ApplicationName",
"=",
"None",
",",
"VersionLabel",
"=",
"None",
",",
"TemplateName",
"=",
"None",
",",
"EnvironmentId",
"=",
"None",
",",
"EnvironmentName",
"=",
"None",
",",
"PlatformArn",
"=",
"None",
",",
"RequestId",
"=",
... | Returns list of event descriptions matching criteria up to the last 6 weeks.
See also: AWS API Documentation
Examples
The following operation retrieves events for an environment named my-env:
Expected Output:
:example: response = client.describe_events(
ApplicationName='string',
VersionLabel='string',
TemplateName='string',
EnvironmentId='string',
EnvironmentName='string',
PlatformArn='string',
RequestId='string',
Severity='TRACE'|'DEBUG'|'INFO'|'WARN'|'ERROR'|'FATAL',
StartTime=datetime(2015, 1, 1),
EndTime=datetime(2015, 1, 1),
MaxRecords=123,
NextToken='string'
)
:type ApplicationName: string
:param ApplicationName: If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only those associated with this application.
:type VersionLabel: string
:param VersionLabel: If specified, AWS Elastic Beanstalk restricts the returned descriptions to those associated with this application version.
:type TemplateName: string
:param TemplateName: If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that are associated with this environment configuration.
:type EnvironmentId: string
:param EnvironmentId: If specified, AWS Elastic Beanstalk restricts the returned descriptions to those associated with this environment.
:type EnvironmentName: string
:param EnvironmentName: If specified, AWS Elastic Beanstalk restricts the returned descriptions to those associated with this environment.
:type PlatformArn: string
:param PlatformArn: The ARN of the version of the custom platform.
:type RequestId: string
:param RequestId: If specified, AWS Elastic Beanstalk restricts the described events to include only those associated with this request ID.
:type Severity: string
:param Severity: If specified, limits the events returned from this call to include only those with the specified severity or higher.
:type StartTime: datetime
:param StartTime: If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that occur on or after this time.
:type EndTime: datetime
:param EndTime: If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that occur up to, but not including, the EndTime .
:type MaxRecords: integer
:param MaxRecords: Specifies the maximum number of events that can be returned, beginning with the most recent event.
:type NextToken: string
:param NextToken: Pagination token. If specified, the events return the next batch of results.
:rtype: dict
:return: {
'Events': [
{
'EventDate': datetime(2015, 1, 1),
'Message': 'string',
'ApplicationName': 'string',
'VersionLabel': 'string',
'TemplateName': 'string',
'EnvironmentName': 'string',
'PlatformArn': 'string',
'RequestId': 'string',
'Severity': 'TRACE'|'DEBUG'|'INFO'|'WARN'|'ERROR'|'FATAL'
},
],
'NextToken': 'string'
} | [
"Returns",
"list",
"of",
"event",
"descriptions",
"matching",
"criteria",
"up",
"to",
"the",
"last",
"6",
"weeks",
".",
"See",
"also",
":",
"AWS",
"API",
"Documentation",
"Examples",
"The",
"following",
"operation",
"retrieves",
"events",
"for",
"an",
"environ... | python | train |
cvxopt/chompack | src/python/misc.py | https://github.com/cvxopt/chompack/blob/e07106b58b8055c34f6201e8c954482f86987833/src/python/misc.py#L42-L53 | def perm(A, p):
"""
Symmetric permutation of a symmetric sparse matrix.
:param A: :py:class:`spmatrix`
:param p: :py:class:`matrix` or :class:`list` of length `A.size[0]`
"""
assert isinstance(A,spmatrix), "argument must be a sparse matrix"
assert A.size[0] == A.size[1], "A must be a square matrix"
assert A.size[0] == len(p), "length of p must be equal to the order of A"
return A[p,p] | [
"def",
"perm",
"(",
"A",
",",
"p",
")",
":",
"assert",
"isinstance",
"(",
"A",
",",
"spmatrix",
")",
",",
"\"argument must be a sparse matrix\"",
"assert",
"A",
".",
"size",
"[",
"0",
"]",
"==",
"A",
".",
"size",
"[",
"1",
"]",
",",
"\"A must be a squa... | Symmetric permutation of a symmetric sparse matrix.
:param A: :py:class:`spmatrix`
:param p: :py:class:`matrix` or :class:`list` of length `A.size[0]` | [
"Symmetric",
"permutation",
"of",
"a",
"symmetric",
"sparse",
"matrix",
"."
] | python | train |
django-parler/django-parler-rest | parler_rest/serializers.py | https://github.com/django-parler/django-parler-rest/blob/9f9d469ece38aaf4e0e3d2152bb9e7824bb3d9f5/parler_rest/serializers.py#L41-L54 | def save_translations(self, instance, translated_data):
"""
Save translation data into translation objects.
"""
for meta in self.Meta.model._parler_meta:
translations = translated_data.get(meta.rel_name, {})
for lang_code, model_fields in translations.items():
translation = instance._get_translated_model(lang_code, auto_create=True, meta=meta)
for field, value in model_fields.items():
setattr(translation, field, value)
# Go through the same hooks as the regular model,
# instead of calling translation.save() directly.
instance.save_translations() | [
"def",
"save_translations",
"(",
"self",
",",
"instance",
",",
"translated_data",
")",
":",
"for",
"meta",
"in",
"self",
".",
"Meta",
".",
"model",
".",
"_parler_meta",
":",
"translations",
"=",
"translated_data",
".",
"get",
"(",
"meta",
".",
"rel_name",
... | Save translation data into translation objects. | [
"Save",
"translation",
"data",
"into",
"translation",
"objects",
"."
] | python | train |
tornadoweb/tornado | tornado/process.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/process.py#L319-L340 | def initialize(cls) -> None:
"""Initializes the ``SIGCHLD`` handler.
The signal handler is run on an `.IOLoop` to avoid locking issues.
Note that the `.IOLoop` used for signal handling need not be the
same one used by individual Subprocess objects (as long as the
``IOLoops`` are each running in separate threads).
.. versionchanged:: 5.0
The ``io_loop`` argument (deprecated since version 4.1) has been
removed.
Availability: Unix
"""
if cls._initialized:
return
io_loop = ioloop.IOLoop.current()
cls._old_sigchld = signal.signal(
signal.SIGCHLD,
lambda sig, frame: io_loop.add_callback_from_signal(cls._cleanup),
)
cls._initialized = True | [
"def",
"initialize",
"(",
"cls",
")",
"->",
"None",
":",
"if",
"cls",
".",
"_initialized",
":",
"return",
"io_loop",
"=",
"ioloop",
".",
"IOLoop",
".",
"current",
"(",
")",
"cls",
".",
"_old_sigchld",
"=",
"signal",
".",
"signal",
"(",
"signal",
".",
... | Initializes the ``SIGCHLD`` handler.
The signal handler is run on an `.IOLoop` to avoid locking issues.
Note that the `.IOLoop` used for signal handling need not be the
same one used by individual Subprocess objects (as long as the
``IOLoops`` are each running in separate threads).
.. versionchanged:: 5.0
The ``io_loop`` argument (deprecated since version 4.1) has been
removed.
Availability: Unix | [
"Initializes",
"the",
"SIGCHLD",
"handler",
"."
] | python | train |
inasafe/inasafe | safe/gis/raster/contour.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/raster/contour.py#L117-L228 | def convolve(input, weights, mask=None, slow=False):
"""2 dimensional convolution.
This is a Python implementation of what will be written in Fortran.
Borders are handled with reflection.
Masking is supported in the following way:
* Masked points are skipped.
* Parts of the input which are masked have weight 0 in the kernel.
* Since the kernel as a whole needs to have value 1, the weights of the
masked parts of the kernel are evenly distributed over the non-masked
parts.
Adapted from https://github.com/nicjhan/gaussian-filter
"""
assert (len(input.shape) == 2)
assert (len(weights.shape) == 2)
# Only one reflection is done on each side so the weights array cannot be
# bigger than width/height of input +1.
assert (weights.shape[0] < input.shape[0] + 1)
assert (weights.shape[1] < input.shape[1] + 1)
if mask is not None:
# The slow convolve does not support masking.
assert (not slow)
assert (input.shape == mask.shape)
tiled_mask = tile_and_reflect(mask)
output = np.copy(input)
tiled_input = tile_and_reflect(input)
rows = input.shape[0]
cols = input.shape[1]
# Stands for half weights row.
hw_row = np.int(weights.shape[0] / 2)
hw_col = np.int(weights.shape[1] / 2)
# Stands for full weights row.
fw_row = weights.shape[0]
fw_col = weights.shape[0]
# Now do convolution on central array.
# Iterate over tiled_input.
for i, io in zip(list(range(rows, rows * 2)), list(range(rows))):
for j, jo in zip(list(range(cols, cols * 2)), list(range(cols))):
# The current central pixel is at (i, j)
# Skip masked points.
if mask is not None and tiled_mask[i, j]:
continue
average = 0.0
if slow:
# Iterate over weights/kernel.
for k in range(weights.shape[0]):
for l in range(weights.shape[1]):
# Get coordinates of tiled_input array that match given
# weights
m = i + k - hw_row
n = j + l - hw_col
average += tiled_input[m, n] * weights[k, l]
else:
# Find the part of the tiled_input array that overlaps with the
# weights array.
overlapping = tiled_input[
i - hw_row:i - hw_row + fw_row,
j - hw_col:j - hw_col + fw_col]
assert (overlapping.shape == weights.shape)
# If any of 'overlapping' is masked then set the corresponding
# points in the weights matrix to 0 and redistribute these to
# non-masked points.
if mask is not None:
overlapping_mask = tiled_mask[
i - hw_row:i - hw_row + fw_row,
j - hw_col:j - hw_col + fw_row]
assert (overlapping_mask.shape == weights.shape)
# Total value and number of weights clobbered by the mask.
clobber_total = np.sum(weights[overlapping_mask])
remaining_num = np.sum(np.logical_not(overlapping_mask))
# This is impossible since at least i, j is not masked.
assert (remaining_num > 0)
correction = clobber_total / remaining_num
# It is OK if nothing is masked - the weights will not be
# changed.
if correction == 0:
assert (not overlapping_mask.any())
# Redistribute to non-masked points.
tmp_weights = np.copy(weights)
tmp_weights[overlapping_mask] = 0.0
tmp_weights[np.where(tmp_weights != 0)] += correction
# Should be very close to 1. May not be exact due to
# rounding.
assert (abs(np.sum(tmp_weights) - 1) < 1e-15)
else:
tmp_weights = weights
merged = tmp_weights[:] * overlapping
average = np.sum(merged)
# Set new output value.
output[io, jo] = average
return output | [
"def",
"convolve",
"(",
"input",
",",
"weights",
",",
"mask",
"=",
"None",
",",
"slow",
"=",
"False",
")",
":",
"assert",
"(",
"len",
"(",
"input",
".",
"shape",
")",
"==",
"2",
")",
"assert",
"(",
"len",
"(",
"weights",
".",
"shape",
")",
"==",
... | 2 dimensional convolution.
This is a Python implementation of what will be written in Fortran.
Borders are handled with reflection.
Masking is supported in the following way:
* Masked points are skipped.
* Parts of the input which are masked have weight 0 in the kernel.
* Since the kernel as a whole needs to have value 1, the weights of the
masked parts of the kernel are evenly distributed over the non-masked
parts.
Adapted from https://github.com/nicjhan/gaussian-filter | [
"2",
"dimensional",
"convolution",
"."
] | python | train |
rigetti/grove | grove/pyqaoa/qaoa.py | https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/pyqaoa/qaoa.py#L132-L178 | def get_parameterized_program(self):
"""
Return a function that accepts parameters and returns a new Quil program.
:returns: a function
"""
cost_para_programs = []
driver_para_programs = []
for idx in range(self.steps):
cost_list = []
driver_list = []
for cost_pauli_sum in self.cost_ham:
for term in cost_pauli_sum.terms:
cost_list.append(exponential_map(term))
for driver_pauli_sum in self.ref_ham:
for term in driver_pauli_sum.terms:
driver_list.append(exponential_map(term))
cost_para_programs.append(cost_list)
driver_para_programs.append(driver_list)
def psi_ref(params):
"""
Construct a Quil program for the vector (beta, gamma).
:param params: array of 2 . p angles, betas first, then gammas
:return: a pyquil program object
"""
if len(params) != 2*self.steps:
raise ValueError("params doesn't match the number of parameters set by `steps`")
betas = params[:self.steps]
gammas = params[self.steps:]
prog = Program()
prog += self.ref_state_prep
for idx in range(self.steps):
for fprog in cost_para_programs[idx]:
prog += fprog(gammas[idx])
for fprog in driver_para_programs[idx]:
prog += fprog(betas[idx])
return prog
return psi_ref | [
"def",
"get_parameterized_program",
"(",
"self",
")",
":",
"cost_para_programs",
"=",
"[",
"]",
"driver_para_programs",
"=",
"[",
"]",
"for",
"idx",
"in",
"range",
"(",
"self",
".",
"steps",
")",
":",
"cost_list",
"=",
"[",
"]",
"driver_list",
"=",
"[",
... | Return a function that accepts parameters and returns a new Quil program.
:returns: a function | [
"Return",
"a",
"function",
"that",
"accepts",
"parameters",
"and",
"returns",
"a",
"new",
"Quil",
"program",
"."
] | python | train |
SAP/PyHDB | pyhdb/protocol/parts.py | https://github.com/SAP/PyHDB/blob/826539d06b8bcef74fe755e7489b8a8255628f12/pyhdb/protocol/parts.py#L428-L435 | def unpack_data(cls, argument_count, payload):
"""Unpack payload by splitting up the raw payload into list of locator_ids
:param argument_count: number of locator_ids in payload is equal to argument_count
:param payload: BytesIO instance with list of concatenated locator_ids, where each locator_id is 8 bytes long
"""
pl = payload.read()
locator_ids = [pl[start:start+8] for start in range(0, len(pl), 8)]
return locator_ids, | [
"def",
"unpack_data",
"(",
"cls",
",",
"argument_count",
",",
"payload",
")",
":",
"pl",
"=",
"payload",
".",
"read",
"(",
")",
"locator_ids",
"=",
"[",
"pl",
"[",
"start",
":",
"start",
"+",
"8",
"]",
"for",
"start",
"in",
"range",
"(",
"0",
",",
... | Unpack payload by splitting up the raw payload into list of locator_ids
:param argument_count: number of locator_ids in payload is equal to argument_count
:param payload: BytesIO instance with list of concatenated locator_ids, where each locator_id is 8 bytes long | [
"Unpack",
"payload",
"by",
"splitting",
"up",
"the",
"raw",
"payload",
"into",
"list",
"of",
"locator_ids",
":",
"param",
"argument_count",
":",
"number",
"of",
"locator_ids",
"in",
"payload",
"is",
"equal",
"to",
"argument_count",
":",
"param",
"payload",
":"... | python | train |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/base_boxes.py | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/base_boxes.py#L49-L122 | def buttonbox(msg="", title=" ", choices=("Button[1]", "Button[2]", "Button[3]"), image=None, root=None, default_choice=None, cancel_choice=None):
"""
Display a msg, a title, an image, and a set of buttons.
The buttons are defined by the members of the choices list.
:param str msg: the msg to be displayed
:param str title: the window title
:param list choices: a list or tuple of the choices to be displayed
:param str image: Filename of image to display
:param str default_choice: The choice you want highlighted when the gui appears
:param str cancel_choice: If the user presses the 'X' close, which button should be pressed
:return: the text of the button that the user selected
"""
global boxRoot, __replyButtonText, buttonsFrame
# If default is not specified, select the first button. This matches old
# behavior.
if default_choice is None:
default_choice = choices[0]
# Initialize __replyButtonText to the first choice.
# This is what will be used if the window is closed by the close button.
__replyButtonText = choices[0]
if root:
root.withdraw()
boxRoot = Toplevel(master=root)
boxRoot.withdraw()
else:
boxRoot = Tk()
boxRoot.withdraw()
boxRoot.title(title)
boxRoot.iconname('Dialog')
boxRoot.geometry(st.rootWindowPosition)
boxRoot.minsize(400, 100)
# ------------- define the messageFrame ---------------------------------
messageFrame = Frame(master=boxRoot)
messageFrame.pack(side=TOP, fill=BOTH)
# ------------- define the imageFrame ---------------------------------
if image:
tk_Image = None
try:
tk_Image = ut.load_tk_image(image)
except Exception as inst:
print(inst)
if tk_Image:
imageFrame = Frame(master=boxRoot)
imageFrame.pack(side=TOP, fill=BOTH)
label = Label(imageFrame, image=tk_Image)
label.image = tk_Image # keep a reference!
label.pack(side=TOP, expand=YES, fill=X, padx='1m', pady='1m')
# ------------- define the buttonsFrame ---------------------------------
buttonsFrame = Frame(master=boxRoot)
buttonsFrame.pack(side=TOP, fill=BOTH)
# -------------------- place the widgets in the frames -------------------
messageWidget = Message(messageFrame, text=msg, width=400)
messageWidget.configure(
font=(st.PROPORTIONAL_FONT_FAMILY, st.PROPORTIONAL_FONT_SIZE))
messageWidget.pack(side=TOP, expand=YES, fill=X, padx='3m', pady='3m')
__put_buttons_in_buttonframe(choices, default_choice, cancel_choice)
# -------------- the action begins -----------
boxRoot.deiconify()
boxRoot.mainloop()
boxRoot.destroy()
if root:
root.deiconify()
return __replyButtonText | [
"def",
"buttonbox",
"(",
"msg",
"=",
"\"\"",
",",
"title",
"=",
"\" \"",
",",
"choices",
"=",
"(",
"\"Button[1]\"",
",",
"\"Button[2]\"",
",",
"\"Button[3]\"",
")",
",",
"image",
"=",
"None",
",",
"root",
"=",
"None",
",",
"default_choice",
"=",
"None",
... | Display a msg, a title, an image, and a set of buttons.
The buttons are defined by the members of the choices list.
:param str msg: the msg to be displayed
:param str title: the window title
:param list choices: a list or tuple of the choices to be displayed
:param str image: Filename of image to display
:param str default_choice: The choice you want highlighted when the gui appears
:param str cancel_choice: If the user presses the 'X' close, which button should be pressed
:return: the text of the button that the user selected | [
"Display",
"a",
"msg",
"a",
"title",
"an",
"image",
"and",
"a",
"set",
"of",
"buttons",
".",
"The",
"buttons",
"are",
"defined",
"by",
"the",
"members",
"of",
"the",
"choices",
"list",
"."
] | python | train |
jsommers/switchyard | switchyard/lib/socket/socketemu.py | https://github.com/jsommers/switchyard/blob/fdcb3869c937dcedbd6ea7a7822ebd412bf1e2b0/switchyard/lib/socket/socketemu.py#L141-L175 | def send_to_app(proto, local_addr, remote_addr, data):
'''
Called by a network stack implementer to push application-layer
data "up" from the stack.
Arguments are protocol number, local_addr (a 2-tuple of IP address
and port), remote_addr (a 2-tuple of IP address and port), and the
message.
Returns True if a socket was found to which to deliver the message,
and False otherwise. When False is returned, a log warning is also
emitted.
'''
proto = IPProtocol(proto)
local_addr = _normalize_addrs(local_addr)
remote_addr = _normalize_addrs(remote_addr)
xtup = (proto, local_addr[0], local_addr[1])
with _lock:
sockqueue = ApplicationLayer._to_app.get(xtup, None)
if sockqueue is not None:
sockqueue.put((local_addr,remote_addr,data))
return True
# no dice, try local IP addr of 0.0.0.0
local2 = _normalize_addrs(("0.0.0.0", local_addr[1]))
xtup = (proto, local2[0], local2[1])
with _lock:
sockqueue = ApplicationLayer._to_app.get(xtup, None)
if sockqueue is not None:
sockqueue.put((local_addr,remote_addr,data))
return True
log_warn("No socket queue found for local proto/address: {}".format(xtup))
return False | [
"def",
"send_to_app",
"(",
"proto",
",",
"local_addr",
",",
"remote_addr",
",",
"data",
")",
":",
"proto",
"=",
"IPProtocol",
"(",
"proto",
")",
"local_addr",
"=",
"_normalize_addrs",
"(",
"local_addr",
")",
"remote_addr",
"=",
"_normalize_addrs",
"(",
"remote... | Called by a network stack implementer to push application-layer
data "up" from the stack.
Arguments are protocol number, local_addr (a 2-tuple of IP address
and port), remote_addr (a 2-tuple of IP address and port), and the
message.
Returns True if a socket was found to which to deliver the message,
and False otherwise. When False is returned, a log warning is also
emitted. | [
"Called",
"by",
"a",
"network",
"stack",
"implementer",
"to",
"push",
"application",
"-",
"layer",
"data",
"up",
"from",
"the",
"stack",
"."
] | python | train |
nerdvegas/rez | src/rez/suite.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L515-L523 | def load_visible_suites(cls, paths=None):
"""Get a list of suites whos bin paths are visible on $PATH.
Returns:
List of `Suite` objects.
"""
suite_paths = cls.visible_suite_paths(paths)
suites = [cls.load(x) for x in suite_paths]
return suites | [
"def",
"load_visible_suites",
"(",
"cls",
",",
"paths",
"=",
"None",
")",
":",
"suite_paths",
"=",
"cls",
".",
"visible_suite_paths",
"(",
"paths",
")",
"suites",
"=",
"[",
"cls",
".",
"load",
"(",
"x",
")",
"for",
"x",
"in",
"suite_paths",
"]",
"retur... | Get a list of suites whos bin paths are visible on $PATH.
Returns:
List of `Suite` objects. | [
"Get",
"a",
"list",
"of",
"suites",
"whos",
"bin",
"paths",
"are",
"visible",
"on",
"$PATH",
"."
] | python | train |
joeyespo/grip | grip/api.py | https://github.com/joeyespo/grip/blob/ce933ccc4ca8e0d3718f271c59bd530a4518bf63/grip/api.py#L13-L46 | def create_app(path=None, user_content=False, context=None, username=None,
password=None, render_offline=False, render_wide=False,
render_inline=False, api_url=None, title=None, text=None,
autorefresh=None, quiet=None, grip_class=None):
"""
Creates a Grip application with the specified overrides.
"""
# Customize the app
if grip_class is None:
grip_class = Grip
# Customize the reader
if text is not None:
display_filename = DirectoryReader(path, True).filename_for(None)
source = TextReader(text, display_filename)
elif path == '-':
source = StdinReader()
else:
source = DirectoryReader(path)
# Customize the renderer
if render_offline:
renderer = OfflineRenderer(user_content, context)
elif user_content or context or api_url:
renderer = GitHubRenderer(user_content, context, api_url)
else:
renderer = None
# Optional basic auth
auth = (username, password) if username or password else None
# Create the customized app with default asset manager
return grip_class(source, auth, renderer, None, render_wide,
render_inline, title, autorefresh, quiet) | [
"def",
"create_app",
"(",
"path",
"=",
"None",
",",
"user_content",
"=",
"False",
",",
"context",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"render_offline",
"=",
"False",
",",
"render_wide",
"=",
"False",
",",
"render... | Creates a Grip application with the specified overrides. | [
"Creates",
"a",
"Grip",
"application",
"with",
"the",
"specified",
"overrides",
"."
] | python | train |
UDST/urbansim | urbansim/utils/misc.py | https://github.com/UDST/urbansim/blob/79f815a6503e109f50be270cee92d0f4a34f49ef/urbansim/utils/misc.py#L300-L317 | def numpymat2df(mat):
"""
Sometimes (though not very often) it is useful to convert a numpy matrix
which has no column names to a Pandas dataframe for use of the Pandas
functions. This method converts a 2D numpy matrix to Pandas dataframe
with default column headers.
Parameters
----------
mat : The numpy matrix
Returns
-------
A pandas dataframe with the same data as the input matrix but with columns
named x0, x1, ... x[n-1] for the number of columns.
"""
return pd.DataFrame(
dict(('x%d' % i, mat[:, i]) for i in range(mat.shape[1]))) | [
"def",
"numpymat2df",
"(",
"mat",
")",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"dict",
"(",
"(",
"'x%d'",
"%",
"i",
",",
"mat",
"[",
":",
",",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"mat",
".",
"shape",
"[",
"1",
"]",
")",
")",
... | Sometimes (though not very often) it is useful to convert a numpy matrix
which has no column names to a Pandas dataframe for use of the Pandas
functions. This method converts a 2D numpy matrix to Pandas dataframe
with default column headers.
Parameters
----------
mat : The numpy matrix
Returns
-------
A pandas dataframe with the same data as the input matrix but with columns
named x0, x1, ... x[n-1] for the number of columns. | [
"Sometimes",
"(",
"though",
"not",
"very",
"often",
")",
"it",
"is",
"useful",
"to",
"convert",
"a",
"numpy",
"matrix",
"which",
"has",
"no",
"column",
"names",
"to",
"a",
"Pandas",
"dataframe",
"for",
"use",
"of",
"the",
"Pandas",
"functions",
".",
"Thi... | python | train |
pyamg/pyamg | pyamg/graph.py | https://github.com/pyamg/pyamg/blob/89dc54aa27e278f65d2f54bdaf16ab97d7768fa6/pyamg/graph.py#L32-L78 | def maximal_independent_set(G, algo='serial', k=None):
"""Compute a maximal independent vertex set for a graph.
Parameters
----------
G : sparse matrix
Symmetric matrix, preferably in sparse CSR or CSC format
The nonzeros of G represent the edges of an undirected graph.
algo : {'serial', 'parallel'}
Algorithm used to compute the MIS
* serial : greedy serial algorithm
* parallel : variant of Luby's parallel MIS algorithm
Returns
-------
S : array
S[i] = 1 if vertex i is in the MIS
S[i] = 0 otherwise
Notes
-----
Diagonal entries in the G (self loops) will be ignored.
Luby's algorithm is significantly more expensive than the
greedy serial algorithm.
"""
G = asgraph(G)
N = G.shape[0]
mis = np.empty(N, dtype='intc')
mis[:] = -1
if k is None:
if algo == 'serial':
fn = amg_core.maximal_independent_set_serial
fn(N, G.indptr, G.indices, -1, 1, 0, mis)
elif algo == 'parallel':
fn = amg_core.maximal_independent_set_parallel
fn(N, G.indptr, G.indices, -1, 1, 0, mis, sp.rand(N), -1)
else:
raise ValueError('unknown algorithm (%s)' % algo)
else:
fn = amg_core.maximal_independent_set_k_parallel
fn(N, G.indptr, G.indices, k, mis, sp.rand(N), -1)
return mis | [
"def",
"maximal_independent_set",
"(",
"G",
",",
"algo",
"=",
"'serial'",
",",
"k",
"=",
"None",
")",
":",
"G",
"=",
"asgraph",
"(",
"G",
")",
"N",
"=",
"G",
".",
"shape",
"[",
"0",
"]",
"mis",
"=",
"np",
".",
"empty",
"(",
"N",
",",
"dtype",
... | Compute a maximal independent vertex set for a graph.
Parameters
----------
G : sparse matrix
Symmetric matrix, preferably in sparse CSR or CSC format
The nonzeros of G represent the edges of an undirected graph.
algo : {'serial', 'parallel'}
Algorithm used to compute the MIS
* serial : greedy serial algorithm
* parallel : variant of Luby's parallel MIS algorithm
Returns
-------
S : array
S[i] = 1 if vertex i is in the MIS
S[i] = 0 otherwise
Notes
-----
Diagonal entries in the G (self loops) will be ignored.
Luby's algorithm is significantly more expensive than the
greedy serial algorithm. | [
"Compute",
"a",
"maximal",
"independent",
"vertex",
"set",
"for",
"a",
"graph",
"."
] | python | train |
mrstephenneal/pdfconduit | pdf/modify/draw/pdf.py | https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/modify/draw/pdf.py#L15-L17 | def text_width(string, font_name, font_size):
"""Determine with width in pixels of string."""
return stringWidth(string, fontName=font_name, fontSize=font_size) | [
"def",
"text_width",
"(",
"string",
",",
"font_name",
",",
"font_size",
")",
":",
"return",
"stringWidth",
"(",
"string",
",",
"fontName",
"=",
"font_name",
",",
"fontSize",
"=",
"font_size",
")"
] | Determine with width in pixels of string. | [
"Determine",
"with",
"width",
"in",
"pixels",
"of",
"string",
"."
] | python | train |
shoeffner/pandoc-source-exec | pandoc_source_exec.py | https://github.com/shoeffner/pandoc-source-exec/blob/9a13b9054d629a60b63196a906fafe2673722d13/pandoc_source_exec.py#L189-L209 | def remove_import_statements(code):
"""Removes lines with import statements from the code.
Args:
code: The code to be stripped.
Returns:
The code without import statements.
"""
new_code = []
for line in code.splitlines():
if not line.lstrip().startswith('import ') and \
not line.lstrip().startswith('from '):
new_code.append(line)
while new_code and new_code[0] == '':
new_code.pop(0)
while new_code and new_code[-1] == '':
new_code.pop()
return '\n'.join(new_code) | [
"def",
"remove_import_statements",
"(",
"code",
")",
":",
"new_code",
"=",
"[",
"]",
"for",
"line",
"in",
"code",
".",
"splitlines",
"(",
")",
":",
"if",
"not",
"line",
".",
"lstrip",
"(",
")",
".",
"startswith",
"(",
"'import '",
")",
"and",
"not",
... | Removes lines with import statements from the code.
Args:
code: The code to be stripped.
Returns:
The code without import statements. | [
"Removes",
"lines",
"with",
"import",
"statements",
"from",
"the",
"code",
"."
] | python | train |
jjkester/moneybird-python | moneybird/api.py | https://github.com/jjkester/moneybird-python/blob/da5f4c8c7ae6c8ed717dc273514a464bc9c284ed/moneybird/api.py#L138-L190 | def _process_response(response: requests.Response, expected: list = []) -> dict:
"""
Processes an API response. Raises an exception when appropriate.
The exception that will be raised is MoneyBird.APIError. This exception is subclassed so implementing programs
can easily react appropriately to different exceptions.
The following subclasses of MoneyBird.APIError are likely to be raised:
- MoneyBird.Unauthorized: No access to the resource or invalid authentication
- MoneyBird.Throttled: Access (temporarily) denied, please try again
- MoneyBird.NotFound: Resource not found, check resource path
- MoneyBird.InvalidData: Validation errors occured while processing your input
- MoneyBird.ServerError: Error on the server
:param response: The response to process.
:param expected: A list of expected status codes which won't raise an exception.
:return: The useful data in the response (may be None).
"""
responses = {
200: None,
201: None,
204: None,
400: MoneyBird.Unauthorized,
401: MoneyBird.Unauthorized,
403: MoneyBird.Throttled,
404: MoneyBird.NotFound,
406: MoneyBird.NotFound,
422: MoneyBird.InvalidData,
429: MoneyBird.Throttled,
500: MoneyBird.ServerError,
}
logger.debug("API request: %s %s\n" % (response.request.method, response.request.url) +
"Response: %s %s" % (response.status_code, response.text))
if response.status_code not in expected:
if response.status_code not in responses:
logger.error("API response contained unknown status code")
raise MoneyBird.APIError(response, "API response contained unknown status code")
elif responses[response.status_code] is not None:
try:
description = response.json()['error']
except (AttributeError, TypeError, KeyError, ValueError):
description = None
raise responses[response.status_code](response, description)
try:
data = response.json()
except ValueError:
logger.error("API response is not JSON decodable")
data = None
return data | [
"def",
"_process_response",
"(",
"response",
":",
"requests",
".",
"Response",
",",
"expected",
":",
"list",
"=",
"[",
"]",
")",
"->",
"dict",
":",
"responses",
"=",
"{",
"200",
":",
"None",
",",
"201",
":",
"None",
",",
"204",
":",
"None",
",",
"4... | Processes an API response. Raises an exception when appropriate.
The exception that will be raised is MoneyBird.APIError. This exception is subclassed so implementing programs
can easily react appropriately to different exceptions.
The following subclasses of MoneyBird.APIError are likely to be raised:
- MoneyBird.Unauthorized: No access to the resource or invalid authentication
- MoneyBird.Throttled: Access (temporarily) denied, please try again
- MoneyBird.NotFound: Resource not found, check resource path
- MoneyBird.InvalidData: Validation errors occured while processing your input
- MoneyBird.ServerError: Error on the server
:param response: The response to process.
:param expected: A list of expected status codes which won't raise an exception.
:return: The useful data in the response (may be None). | [
"Processes",
"an",
"API",
"response",
".",
"Raises",
"an",
"exception",
"when",
"appropriate",
"."
] | python | train |
mikemaccana/python-docx | docx.py | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L644-L661 | def clean(document):
""" Perform misc cleaning operations on documents.
Returns cleaned document.
"""
newdocument = document
# Clean empty text and r tags
for t in ('t', 'r'):
rmlist = []
for element in newdocument.iter():
if element.tag == '{%s}%s' % (nsprefixes['w'], t):
if not element.text and not len(element):
rmlist.append(element)
for element in rmlist:
element.getparent().remove(element)
return newdocument | [
"def",
"clean",
"(",
"document",
")",
":",
"newdocument",
"=",
"document",
"# Clean empty text and r tags",
"for",
"t",
"in",
"(",
"'t'",
",",
"'r'",
")",
":",
"rmlist",
"=",
"[",
"]",
"for",
"element",
"in",
"newdocument",
".",
"iter",
"(",
")",
":",
... | Perform misc cleaning operations on documents.
Returns cleaned document. | [
"Perform",
"misc",
"cleaning",
"operations",
"on",
"documents",
".",
"Returns",
"cleaned",
"document",
"."
] | python | train |
ldomic/lintools | lintools/lintools.py | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/lintools.py#L87-L97 | def analysis_of_prot_lig_interactions(self):
"""
The classes and function that deal with protein-ligand interaction analysis.
"""
self.hbonds = HBonds(self.topol_data,self.trajectory,self.start,self.end,self.skip,self.analysis_cutoff,distance=3)
self.pistacking = PiStacking(self.topol_data,self.trajectory,self.start,self.end,self.skip, self.analysis_cutoff)
self.sasa = SASA(self.topol_data,self.trajectory)
self.lig_descr = LigDescr(self.topol_data)
if self.trajectory!=[]:
self.rmsf = RMSF_measurements(self.topol_data,self.topology,self.trajectory,self.ligand,self.start,self.end,self.skip)
self.salt_bridges = SaltBridges(self.topol_data,self.trajectory,self.lig_descr,self.start,self.end,self.skip,self.analysis_cutoff) | [
"def",
"analysis_of_prot_lig_interactions",
"(",
"self",
")",
":",
"self",
".",
"hbonds",
"=",
"HBonds",
"(",
"self",
".",
"topol_data",
",",
"self",
".",
"trajectory",
",",
"self",
".",
"start",
",",
"self",
".",
"end",
",",
"self",
".",
"skip",
",",
... | The classes and function that deal with protein-ligand interaction analysis. | [
"The",
"classes",
"and",
"function",
"that",
"deal",
"with",
"protein",
"-",
"ligand",
"interaction",
"analysis",
"."
] | python | train |
mogproject/mog-commons-python | src/mog_commons/terminal.py | https://github.com/mogproject/mog-commons-python/blob/951cf0fa9a56248b4d45be720be25f1d4b7e1bff/src/mog_commons/terminal.py#L108-L122 | def _get_restore_function(self):
"""
Return the binary function for restoring terminal attributes.
:return: function (signal, frame) => None:
"""
if os.name == 'nt' or not self.getch_enabled:
return lambda signal, frame: None
try:
fd = self.stdin.fileno()
initial = termios.tcgetattr(fd)
except termios.error:
return lambda signal, frame: None
return lambda signal, frame: termios.tcsetattr(fd, termios.TCSADRAIN, initial) | [
"def",
"_get_restore_function",
"(",
"self",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
"or",
"not",
"self",
".",
"getch_enabled",
":",
"return",
"lambda",
"signal",
",",
"frame",
":",
"None",
"try",
":",
"fd",
"=",
"self",
".",
"stdin",
".",
"... | Return the binary function for restoring terminal attributes.
:return: function (signal, frame) => None: | [
"Return",
"the",
"binary",
"function",
"for",
"restoring",
"terminal",
"attributes",
".",
":",
"return",
":",
"function",
"(",
"signal",
"frame",
")",
"=",
">",
"None",
":"
] | python | train |
iotile/coretools | transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L290-L298 | def _disable_rpcs(self, conn, services, timeout=1.0):
"""Prevent this device from receiving more RPCs
"""
success, result = self._set_notification(conn, services[TileBusService]['characteristics'][TileBusReceiveHeaderCharacteristic], False, timeout)
if not success:
return success, result
return self._set_notification(conn, services[TileBusService]['characteristics'][TileBusReceivePayloadCharacteristic], False, timeout) | [
"def",
"_disable_rpcs",
"(",
"self",
",",
"conn",
",",
"services",
",",
"timeout",
"=",
"1.0",
")",
":",
"success",
",",
"result",
"=",
"self",
".",
"_set_notification",
"(",
"conn",
",",
"services",
"[",
"TileBusService",
"]",
"[",
"'characteristics'",
"]... | Prevent this device from receiving more RPCs | [
"Prevent",
"this",
"device",
"from",
"receiving",
"more",
"RPCs"
] | python | train |
KelSolaar/Umbra | umbra/components/factory/script_editor/models.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/factory/script_editor/models.py#L723-L737 | def delete_authoring_nodes(self, editor):
"""
Deletes the Model authoring Nodes associated with given editor.
:param editor: Editor.
:type editor: Editor
:return: Method success.
:rtype: bool
"""
editor_node = foundations.common.get_first_item(self.get_editor_nodes(editor))
file_node = editor_node.parent
self.unregister_editor(editor_node)
self.unregister_file(file_node, raise_exception=False)
return True | [
"def",
"delete_authoring_nodes",
"(",
"self",
",",
"editor",
")",
":",
"editor_node",
"=",
"foundations",
".",
"common",
".",
"get_first_item",
"(",
"self",
".",
"get_editor_nodes",
"(",
"editor",
")",
")",
"file_node",
"=",
"editor_node",
".",
"parent",
"self... | Deletes the Model authoring Nodes associated with given editor.
:param editor: Editor.
:type editor: Editor
:return: Method success.
:rtype: bool | [
"Deletes",
"the",
"Model",
"authoring",
"Nodes",
"associated",
"with",
"given",
"editor",
"."
] | python | train |
hawkular/hawkular-client-python | hawkular/alerts/common.py | https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/common.py#L81-L90 | def status(self):
"""
Get the status of Alerting Service
:return: Status object
"""
orig_dict = self._get(self._service_url('status'))
orig_dict['implementation_version'] = orig_dict.pop('Implementation-Version')
orig_dict['built_from_git_sha1'] = orig_dict.pop('Built-From-Git-SHA1')
return Status(orig_dict) | [
"def",
"status",
"(",
"self",
")",
":",
"orig_dict",
"=",
"self",
".",
"_get",
"(",
"self",
".",
"_service_url",
"(",
"'status'",
")",
")",
"orig_dict",
"[",
"'implementation_version'",
"]",
"=",
"orig_dict",
".",
"pop",
"(",
"'Implementation-Version'",
")",... | Get the status of Alerting Service
:return: Status object | [
"Get",
"the",
"status",
"of",
"Alerting",
"Service"
] | python | train |
rbuffat/pyepw | pyepw/epw.py | https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L1034-L1061 | def coldestmonth(self, value=None):
"""Corresponds to IDD Field `coldestmonth`
Args:
value (int): value for IDD Field `coldestmonth`
value >= 1
value <= 12
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid value
"""
if value is not None:
try:
value = int(value)
except ValueError:
raise ValueError('value {} need to be of type int '
'for field `coldestmonth`'.format(value))
if value < 1:
raise ValueError('value need to be greater or equal 1 '
'for field `coldestmonth`')
if value > 12:
raise ValueError('value need to be smaller 12 '
'for field `coldestmonth`')
self._coldestmonth = value | [
"def",
"coldestmonth",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"int",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type int... | Corresponds to IDD Field `coldestmonth`
Args:
value (int): value for IDD Field `coldestmonth`
value >= 1
value <= 12
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid value | [
"Corresponds",
"to",
"IDD",
"Field",
"coldestmonth"
] | python | train |
saltstack/salt | salt/modules/ps.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L119-L178 | def top(num_processes=5, interval=3):
'''
Return a list of top CPU consuming processes during the interval.
num_processes = return the top N CPU consuming processes
interval = the number of seconds to sample CPU usage over
CLI Examples:
.. code-block:: bash
salt '*' ps.top
salt '*' ps.top 5 10
'''
result = []
start_usage = {}
for pid in psutil.pids():
try:
process = psutil.Process(pid)
user, system = process.cpu_times()
except ValueError:
user, system, _, _ = process.cpu_times()
except psutil.NoSuchProcess:
continue
start_usage[process] = user + system
time.sleep(interval)
usage = set()
for process, start in six.iteritems(start_usage):
try:
user, system = process.cpu_times()
except ValueError:
user, system, _, _ = process.cpu_times()
except psutil.NoSuchProcess:
continue
now = user + system
diff = now - start
usage.add((diff, process))
for idx, (diff, process) in enumerate(reversed(sorted(usage))):
if num_processes and idx >= num_processes:
break
if not _get_proc_cmdline(process):
cmdline = _get_proc_name(process)
else:
cmdline = _get_proc_cmdline(process)
info = {'cmd': cmdline,
'user': _get_proc_username(process),
'status': _get_proc_status(process),
'pid': _get_proc_pid(process),
'create_time': _get_proc_create_time(process),
'cpu': {},
'mem': {},
}
for key, value in six.iteritems(process.cpu_times()._asdict()):
info['cpu'][key] = value
for key, value in six.iteritems(process.memory_info()._asdict()):
info['mem'][key] = value
result.append(info)
return result | [
"def",
"top",
"(",
"num_processes",
"=",
"5",
",",
"interval",
"=",
"3",
")",
":",
"result",
"=",
"[",
"]",
"start_usage",
"=",
"{",
"}",
"for",
"pid",
"in",
"psutil",
".",
"pids",
"(",
")",
":",
"try",
":",
"process",
"=",
"psutil",
".",
"Proces... | Return a list of top CPU consuming processes during the interval.
num_processes = return the top N CPU consuming processes
interval = the number of seconds to sample CPU usage over
CLI Examples:
.. code-block:: bash
salt '*' ps.top
salt '*' ps.top 5 10 | [
"Return",
"a",
"list",
"of",
"top",
"CPU",
"consuming",
"processes",
"during",
"the",
"interval",
".",
"num_processes",
"=",
"return",
"the",
"top",
"N",
"CPU",
"consuming",
"processes",
"interval",
"=",
"the",
"number",
"of",
"seconds",
"to",
"sample",
"CPU... | python | train |
GetmeUK/MongoFrames | snippets/comparable.py | https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/comparable.py#L151-L214 | def diff_to_html(cls, details):
"""Return an entry's details in HTML format"""
changes = []
# Check that there are details to convert to HMTL
if not details:
return ''
def _frame(value):
"""
Handle converted `Frame` references where the human identifier is
stored against the `_str` key.
"""
if isinstance(value, dict) and '_str' in value:
return value['_str']
elif isinstance(value, list):
return ', '.join([_frame(v) for v in value])
return str(value)
# Additions
fields = sorted(details.get('additions', {}))
for field in fields:
new_value = _frame(details['additions'][field])
if isinstance(new_value, list):
new_value = ', '.join([_frame(v) for v in new_value])
change = cls._templates['add'].format(
field=field,
new_value=new_value
)
changes.append(change)
# Updates
fields = sorted(details.get('updates', {}))
for field in fields:
original_value = _frame(details['updates'][field][0])
if isinstance(original_value, list):
original_value = ', '.join([_frame(v) for v in original_value])
new_value = _frame(details['updates'][field][1])
if isinstance(new_value, list):
new_value = ', '.join([_frame(v) for v in new_value])
change = cls._templates['update'].format(
field=field,
original_value=original_value,
new_value=new_value
)
changes.append(change)
# Deletions
fields = sorted(details.get('deletions', {}))
for field in fields:
original_value = _frame(details['deletions'][field])
if isinstance(original_value, list):
original_value = ', '.join([_frame(v) for v in original_value])
change = cls._templates['delete'].format(
field=field,
original_value=original_value
)
changes.append(change)
return '\n'.join(changes) | [
"def",
"diff_to_html",
"(",
"cls",
",",
"details",
")",
":",
"changes",
"=",
"[",
"]",
"# Check that there are details to convert to HMTL",
"if",
"not",
"details",
":",
"return",
"''",
"def",
"_frame",
"(",
"value",
")",
":",
"\"\"\"\n Handle converted `F... | Return an entry's details in HTML format | [
"Return",
"an",
"entry",
"s",
"details",
"in",
"HTML",
"format"
] | python | train |
jdoda/sdl2hl | sdl2hl/rect.py | https://github.com/jdoda/sdl2hl/blob/3b477e1e01cea5d8e15e9e5ef3a302ea460f5946/sdl2hl/rect.py#L117-L126 | def has_intersection(self, other):
"""Return whether this rectangle intersects with another rectangle.
Args:
other (Rect): The rectangle to test intersection with.
Returns:
bool: True if there is an intersection, False otherwise.
"""
return bool(lib.SDL_HasIntersection(self._ptr, other._ptr)) | [
"def",
"has_intersection",
"(",
"self",
",",
"other",
")",
":",
"return",
"bool",
"(",
"lib",
".",
"SDL_HasIntersection",
"(",
"self",
".",
"_ptr",
",",
"other",
".",
"_ptr",
")",
")"
] | Return whether this rectangle intersects with another rectangle.
Args:
other (Rect): The rectangle to test intersection with.
Returns:
bool: True if there is an intersection, False otherwise. | [
"Return",
"whether",
"this",
"rectangle",
"intersects",
"with",
"another",
"rectangle",
"."
] | python | train |
prajwalkr/track-it | trackit/trackers.py | https://github.com/prajwalkr/track-it/blob/01a91dba8e7bc169976e0b13faacf7dd7330237b/trackit/trackers.py#L421-L463 | def Extract_Checkpoints(self):
'''
Extract the checkpoints and store in self.tracking_data
'''
# Make sure page is available
if self.page is None:
raise Exception("The HTML data was not fetched due to some reasons")
soup = BeautifulSoup(self.page,'html.parser')
if 'Delivery information not found' in self.page:
raise ValueError('The Tracking number is invalid/Tracking number is over 45 days old.')
# Assign the current status of the shipment
if 'Delivered on' in self.page:
self.status = 'C'
else: # The shipment is in Transit
self.status = 'T'
# Checkpoints extraction begins here
table = soup.findAll('table',{'cellpadding':'1','cellspacing':'1','border':'1','align':'center','style':"width:800px;border-color:#034291;"})[1]
rows = table.findAll('tr')[1:]
for row in rows:
'''
Each row will have 3 columns: Date--Location--Status
'''
row_cells = row.findAll('td')
date = row_cells[0].string.strip()
date = datetime.strptime(date,"%A, %B %d, %Y")
location = row_cells[1].find('a').string.strip()
if location is '': # ignore the days which are holidays
continue
status = row_cells[2].text.strip()
self.tracking_data.append({'status':status,'date':date,'location':location})
# Sort the checkpoints based on Date and Time --- this is important
self.tracking_data = sorted(self.tracking_data, key=lambda k: k['date']) | [
"def",
"Extract_Checkpoints",
"(",
"self",
")",
":",
"# Make sure page is available",
"if",
"self",
".",
"page",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"The HTML data was not fetched due to some reasons\"",
")",
"soup",
"=",
"BeautifulSoup",
"(",
"self",
".",... | Extract the checkpoints and store in self.tracking_data | [
"Extract",
"the",
"checkpoints",
"and",
"store",
"in",
"self",
".",
"tracking_data"
] | python | train |
docker/docker-py | docker/models/plugins.py | https://github.com/docker/docker-py/blob/613d6aad83acc9931ff2ecfd6a6c7bd8061dc125/docker/models/plugins.py#L100-L122 | def upgrade(self, remote=None):
"""
Upgrade the plugin.
Args:
remote (string): Remote reference to upgrade to. The
``:latest`` tag is optional and is the default if omitted.
Default: this plugin's name.
Returns:
A generator streaming the decoded API logs
"""
if self.enabled:
raise errors.DockerError(
'Plugin must be disabled before upgrading.'
)
if remote is None:
remote = self.name
privileges = self.client.api.plugin_privileges(remote)
for d in self.client.api.upgrade_plugin(self.name, remote, privileges):
yield d
self._reload() | [
"def",
"upgrade",
"(",
"self",
",",
"remote",
"=",
"None",
")",
":",
"if",
"self",
".",
"enabled",
":",
"raise",
"errors",
".",
"DockerError",
"(",
"'Plugin must be disabled before upgrading.'",
")",
"if",
"remote",
"is",
"None",
":",
"remote",
"=",
"self",
... | Upgrade the plugin.
Args:
remote (string): Remote reference to upgrade to. The
``:latest`` tag is optional and is the default if omitted.
Default: this plugin's name.
Returns:
A generator streaming the decoded API logs | [
"Upgrade",
"the",
"plugin",
"."
] | python | train |
Captricity/captools | captools/api/client.py | https://github.com/Captricity/captools/blob/e7dc069ff5ede95d4956c7a0a4614d0e53e5a955/captools/api/client.py#L207-L227 | def _put_or_post_json(self, method, url, data):
"""
urlencodes the data and PUTs it to the url
the response is parsed as JSON and the resulting data type is returned
"""
if self.parsed_endpoint.scheme == 'https':
conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc)
else:
conn = httplib.HTTPConnection(self.parsed_endpoint.netloc)
head = {
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": USER_AGENT,
API_TOKEN_HEADER_NAME: self.api_token,
}
if self.api_version in ['0.1', '0.01a']:
head[API_VERSION_HEADER_NAME] = self.api_version
conn.request(method, url, json.dumps(data), head)
resp = conn.getresponse()
self._handle_response_errors(method, url, resp)
return json.loads(resp.read()) | [
"def",
"_put_or_post_json",
"(",
"self",
",",
"method",
",",
"url",
",",
"data",
")",
":",
"if",
"self",
".",
"parsed_endpoint",
".",
"scheme",
"==",
"'https'",
":",
"conn",
"=",
"httplib",
".",
"HTTPSConnection",
"(",
"self",
".",
"parsed_endpoint",
".",
... | urlencodes the data and PUTs it to the url
the response is parsed as JSON and the resulting data type is returned | [
"urlencodes",
"the",
"data",
"and",
"PUTs",
"it",
"to",
"the",
"url",
"the",
"response",
"is",
"parsed",
"as",
"JSON",
"and",
"the",
"resulting",
"data",
"type",
"is",
"returned"
] | python | train |
Jajcus/pyxmpp2 | pyxmpp2/roster.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L307-L321 | def verify_roster_push(self, fix = False):
"""Check if `self` is valid roster push item.
Valid item must have proper `subscription` value other and valid value
for 'ask'.
:Parameters:
- `fix`: if `True` than replace invalid 'subscription' and 'ask'
values with the defaults
:Types:
- `fix`: `bool`
:Raise: `ValueError` if the item is invalid.
"""
self._verify((None, u"from", u"to", u"both", u"remove"), fix) | [
"def",
"verify_roster_push",
"(",
"self",
",",
"fix",
"=",
"False",
")",
":",
"self",
".",
"_verify",
"(",
"(",
"None",
",",
"u\"from\"",
",",
"u\"to\"",
",",
"u\"both\"",
",",
"u\"remove\"",
")",
",",
"fix",
")"
] | Check if `self` is valid roster push item.
Valid item must have proper `subscription` value other and valid value
for 'ask'.
:Parameters:
- `fix`: if `True` than replace invalid 'subscription' and 'ask'
values with the defaults
:Types:
- `fix`: `bool`
:Raise: `ValueError` if the item is invalid. | [
"Check",
"if",
"self",
"is",
"valid",
"roster",
"push",
"item",
"."
] | python | valid |
Kortemme-Lab/klab | klab/bio/basics.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/basics.py#L283-L290 | def pdb_atom_name_to_element(s):
'''s should be a string taken from columns 12-15 (zero-indexed) inclusive of a PDB coordinate line.'''
assert(len(s) == 4)
if len(s.strip()) == 4:
assert(s[0] == 'H' or s[0] == 'C' or s[0] == 'O') # "If the name of a hydrogen has four characters, it is left-justified starting in column 13; if it has fewer than four characters, it is left-justified starting in column 14. If the name of a hydrogen has four characters, it is left-justified starting in column 13; if it has fewer than four characters, it is left-justified starting in column 14."
return s[0] # I think this works for hydrogen - I do not know if it is generally correct for carbon and oxygen but something like this is necessary - see CE11 in 1DAN. The correct approach is described somewhere in the IUPAC recommendations (Pure Appl Chem 70:117 (1998), http://www.iupac.org/publications/pac/1998/pdf/7001x0117.pdf.
else:
return s[:2].strip() | [
"def",
"pdb_atom_name_to_element",
"(",
"s",
")",
":",
"assert",
"(",
"len",
"(",
"s",
")",
"==",
"4",
")",
"if",
"len",
"(",
"s",
".",
"strip",
"(",
")",
")",
"==",
"4",
":",
"assert",
"(",
"s",
"[",
"0",
"]",
"==",
"'H'",
"or",
"s",
"[",
... | s should be a string taken from columns 12-15 (zero-indexed) inclusive of a PDB coordinate line. | [
"s",
"should",
"be",
"a",
"string",
"taken",
"from",
"columns",
"12",
"-",
"15",
"(",
"zero",
"-",
"indexed",
")",
"inclusive",
"of",
"a",
"PDB",
"coordinate",
"line",
"."
] | python | train |
AtteqCom/zsl | src/zsl/resource/resource_helper.py | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/resource_helper.py#L173-L184 | def flat_model(tree):
"""Flatten the tree into a list of properties adding parents as prefixes."""
names = []
for columns in viewvalues(tree):
for col in columns:
if isinstance(col, dict):
col_name = list(col)[0]
names += [col_name + '__' + c for c in flat_model(col)]
else:
names.append(col)
return names | [
"def",
"flat_model",
"(",
"tree",
")",
":",
"names",
"=",
"[",
"]",
"for",
"columns",
"in",
"viewvalues",
"(",
"tree",
")",
":",
"for",
"col",
"in",
"columns",
":",
"if",
"isinstance",
"(",
"col",
",",
"dict",
")",
":",
"col_name",
"=",
"list",
"("... | Flatten the tree into a list of properties adding parents as prefixes. | [
"Flatten",
"the",
"tree",
"into",
"a",
"list",
"of",
"properties",
"adding",
"parents",
"as",
"prefixes",
"."
] | python | train |
Tanganelli/CoAPthon3 | coapthon/layers/requestlayer.py | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/requestlayer.py#L99-L115 | def _handle_post(self, transaction):
"""
Handle POST requests
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the edited transaction with the response to the request
"""
path = str("/" + transaction.request.uri_path)
transaction.response = Response()
transaction.response.destination = transaction.request.source
transaction.response.token = transaction.request.token
# Create request
transaction = self._server.resourceLayer.create_resource(path, transaction)
return transaction | [
"def",
"_handle_post",
"(",
"self",
",",
"transaction",
")",
":",
"path",
"=",
"str",
"(",
"\"/\"",
"+",
"transaction",
".",
"request",
".",
"uri_path",
")",
"transaction",
".",
"response",
"=",
"Response",
"(",
")",
"transaction",
".",
"response",
".",
... | Handle POST requests
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the edited transaction with the response to the request | [
"Handle",
"POST",
"requests"
] | python | train |
gbowerman/azurerm | azurerm/amsrp.py | https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/azurerm/amsrp.py#L862-L876 | def helper_list(access_token, oid, path):
'''Helper Function to list a URL path.
Args:
access_token (str): A valid Azure authentication token.
oid (str): An OID.
path (str): A URL Path.
Returns:
HTTP response. JSON body.
'''
if oid != "":
path = ''.join([path, "('", oid, "')"])
endpoint = ''.join([ams_rest_endpoint, path])
return do_ams_get(endpoint, path, access_token) | [
"def",
"helper_list",
"(",
"access_token",
",",
"oid",
",",
"path",
")",
":",
"if",
"oid",
"!=",
"\"\"",
":",
"path",
"=",
"''",
".",
"join",
"(",
"[",
"path",
",",
"\"('\"",
",",
"oid",
",",
"\"')\"",
"]",
")",
"endpoint",
"=",
"''",
".",
"join"... | Helper Function to list a URL path.
Args:
access_token (str): A valid Azure authentication token.
oid (str): An OID.
path (str): A URL Path.
Returns:
HTTP response. JSON body. | [
"Helper",
"Function",
"to",
"list",
"a",
"URL",
"path",
"."
] | python | train |
thomasdelaet/python-velbus | velbus/controller.py | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/controller.py#L96-L121 | def scan(self, callback=None):
"""
Scan the bus and call the callback when a new module is discovered
:return: None
"""
def scan_finished():
"""
Callback when scan is finished
"""
time.sleep(3)
logging.info('Scan finished')
self._nb_of_modules_loaded = 0
def module_loaded():
self._nb_of_modules_loaded += 1
if self._nb_of_modules_loaded >= len(self._modules):
callback()
for module in self._modules:
self._modules[module].load(module_loaded)
for address in range(0, 256):
message = velbus.ModuleTypeRequestMessage(address)
if address == 255:
self.send(message, scan_finished)
else:
self.send(message) | [
"def",
"scan",
"(",
"self",
",",
"callback",
"=",
"None",
")",
":",
"def",
"scan_finished",
"(",
")",
":",
"\"\"\"\n Callback when scan is finished\n \"\"\"",
"time",
".",
"sleep",
"(",
"3",
")",
"logging",
".",
"info",
"(",
"'Scan finished'"... | Scan the bus and call the callback when a new module is discovered
:return: None | [
"Scan",
"the",
"bus",
"and",
"call",
"the",
"callback",
"when",
"a",
"new",
"module",
"is",
"discovered"
] | python | train |
erikrose/more-itertools | more_itertools/more.py | https://github.com/erikrose/more-itertools/blob/6a91b4e25c8e12fcf9fc2b53cf8ee0fba293e6f9/more_itertools/more.py#L1401-L1451 | def always_iterable(obj, base_type=(str, bytes)):
"""If *obj* is iterable, return an iterator over its items::
>>> obj = (1, 2, 3)
>>> list(always_iterable(obj))
[1, 2, 3]
If *obj* is not iterable, return a one-item iterable containing *obj*::
>>> obj = 1
>>> list(always_iterable(obj))
[1]
If *obj* is ``None``, return an empty iterable:
>>> obj = None
>>> list(always_iterable(None))
[]
By default, binary and text strings are not considered iterable::
>>> obj = 'foo'
>>> list(always_iterable(obj))
['foo']
If *base_type* is set, objects for which ``isinstance(obj, base_type)``
returns ``True`` won't be considered iterable.
>>> obj = {'a': 1}
>>> list(always_iterable(obj)) # Iterate over the dict's keys
['a']
>>> list(always_iterable(obj, base_type=dict)) # Treat dicts as a unit
[{'a': 1}]
Set *base_type* to ``None`` to avoid any special handling and treat objects
Python considers iterable as iterable:
>>> obj = 'foo'
>>> list(always_iterable(obj, base_type=None))
['f', 'o', 'o']
"""
if obj is None:
return iter(())
if (base_type is not None) and isinstance(obj, base_type):
return iter((obj,))
try:
return iter(obj)
except TypeError:
return iter((obj,)) | [
"def",
"always_iterable",
"(",
"obj",
",",
"base_type",
"=",
"(",
"str",
",",
"bytes",
")",
")",
":",
"if",
"obj",
"is",
"None",
":",
"return",
"iter",
"(",
"(",
")",
")",
"if",
"(",
"base_type",
"is",
"not",
"None",
")",
"and",
"isinstance",
"(",
... | If *obj* is iterable, return an iterator over its items::
>>> obj = (1, 2, 3)
>>> list(always_iterable(obj))
[1, 2, 3]
If *obj* is not iterable, return a one-item iterable containing *obj*::
>>> obj = 1
>>> list(always_iterable(obj))
[1]
If *obj* is ``None``, return an empty iterable:
>>> obj = None
>>> list(always_iterable(None))
[]
By default, binary and text strings are not considered iterable::
>>> obj = 'foo'
>>> list(always_iterable(obj))
['foo']
If *base_type* is set, objects for which ``isinstance(obj, base_type)``
returns ``True`` won't be considered iterable.
>>> obj = {'a': 1}
>>> list(always_iterable(obj)) # Iterate over the dict's keys
['a']
>>> list(always_iterable(obj, base_type=dict)) # Treat dicts as a unit
[{'a': 1}]
Set *base_type* to ``None`` to avoid any special handling and treat objects
Python considers iterable as iterable:
>>> obj = 'foo'
>>> list(always_iterable(obj, base_type=None))
['f', 'o', 'o'] | [
"If",
"*",
"obj",
"*",
"is",
"iterable",
"return",
"an",
"iterator",
"over",
"its",
"items",
"::"
] | python | train |
has2k1/plotnine | plotnine/qplot.py | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/qplot.py#L21-L215 | def qplot(x=None, y=None, data=None, facets=None, margins=False,
geom='auto', xlim=None, ylim=None, log='', main=None,
xlab=None, ylab=None, asp=None, **kwargs):
"""
Quick plot
Parameters
----------
x : str | array_like
x aesthetic
y : str | array_like
y aesthetic
data : dataframe
Data frame to use (optional). If not specified,
will create one, extracting arrays from the
current environment.
geom : str | list
*geom(s)* to do the drawing. If ``auto``, defaults
to 'point' if ``x`` and ``y`` are specified or
'histogram' if only ``x`` is specified.
xlim : tuple
x-axis limits
ylim : tuple
y-axis limits
log : str in ``{'x', 'y', 'xy'}``
Which variables to log transform.
main : str
Plot title
xlab : str
x-axis label
ylab : str
y-axis label
asp : str | float
The y/x aspect ratio.
**kwargs : dict
Arguments passed on to the geom.
Returns
-------
p: ggplot
ggplot object
"""
# Extract all recognizable aesthetic mappings from the parameters
# String values e.g "I('red')", "I(4)" are not treated as mappings
environment = EvalEnvironment.capture(1)
aesthetics = {} if x is None else {'x': x}
if y is not None:
aesthetics['y'] = y
def is_mapping(value):
"""
Return True if value is not enclosed in I() function
"""
with suppress(AttributeError):
return not (value.startswith('I(') and value.endswith(')'))
return True
def I(value):
return value
I_env = EvalEnvironment([{'I': I}])
for ae in kwargs.keys() & all_aesthetics:
value = kwargs[ae]
if is_mapping(value):
aesthetics[ae] = value
else:
kwargs[ae] = I_env.eval(value)
# List of geoms
if is_string(geom):
geom = [geom]
elif isinstance(geom, tuple):
geom = list(geom)
if data is None:
data = pd.DataFrame()
# Work out plot data, and modify aesthetics, if necessary
def replace_auto(lst, str2):
"""
Replace all occurences of 'auto' in with str2
"""
for i, value in enumerate(lst):
if value == 'auto':
lst[i] = str2
return lst
if 'auto' in geom:
if 'sample' in aesthetics:
replace_auto(geom, 'qq')
elif y is None:
# If x is discrete we choose geom_bar &
# geom_histogram otherwise. But we need to
# evaluate the mapping to find out the dtype
env = environment.with_outer_namespace(
{'factor': pd.Categorical})
if isinstance(aesthetics['x'], str):
try:
x = env.eval(aesthetics['x'], inner_namespace=data)
except Exception:
msg = "Could not evaluate aesthetic 'x={}'"
raise PlotnineError(msg.format(aesthetics['x']))
elif not hasattr(aesthetics['x'], 'dtype'):
x = np.asarray(aesthetics['x'])
if array_kind.discrete(x):
replace_auto(geom, 'bar')
else:
replace_auto(geom, 'histogram')
else:
if x is None:
if pdtypes.is_list_like(aesthetics['y']):
aesthetics['x'] = range(len(aesthetics['y']))
xlab = 'range(len(y))'
ylab = 'y'
else:
# We could solve the issue in layer.compute_asthetics
# but it is not worth the extra complexity
raise PlotnineError(
"Cannot infer how long x should be.")
replace_auto(geom, 'point')
p = ggplot(aes(**aesthetics), data=data, environment=environment)
def get_facet_type(facets):
with suppress(PlotnineError):
parse_grid_facets(facets)
return 'grid'
with suppress(PlotnineError):
parse_wrap_facets(facets)
return 'wrap'
warn("Could not determine the type of faceting, "
"therefore no faceting.", PlotnineWarning)
return 'null'
if facets:
facet_type = get_facet_type(facets)
if facet_type == 'grid':
p += facet_grid(facets, margins=margins)
elif facet_type == 'wrap':
p += facet_wrap(facets)
else:
p += facet_null()
# Add geoms
for g in geom:
geom_name = 'geom_{}'.format(g)
geom_klass = Registry[geom_name]
stat_name = 'stat_{}'.format(geom_klass.DEFAULT_PARAMS['stat'])
stat_klass = Registry[stat_name]
# find params
recognized = (kwargs.keys() &
(geom_klass.DEFAULT_PARAMS.keys() |
geom_klass.aesthetics() |
stat_klass.DEFAULT_PARAMS.keys() |
stat_klass.aesthetics()))
recognized = recognized - aesthetics.keys()
params = {ae: kwargs[ae] for ae in recognized}
p += geom_klass(**params)
# pd.Series objects have name attributes. In a dataframe, the
# series have the name of the column.
labels = {}
for ae in scaled_aesthetics & kwargs.keys():
with suppress(AttributeError):
labels[ae] = kwargs[ae].name
with suppress(AttributeError):
labels['x'] = xlab if xlab is not None else x.name
with suppress(AttributeError):
labels['y'] = ylab if ylab is not None else y.name
if main is not None:
labels['title'] = main
if 'x' in log:
p += scale_x_log10()
if 'y' in log:
p += scale_y_log10()
if labels:
p += labs(**labels)
if asp:
p += theme(aspect_ratio=asp)
return p | [
"def",
"qplot",
"(",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"data",
"=",
"None",
",",
"facets",
"=",
"None",
",",
"margins",
"=",
"False",
",",
"geom",
"=",
"'auto'",
",",
"xlim",
"=",
"None",
",",
"ylim",
"=",
"None",
",",
"log",
"=",
... | Quick plot
Parameters
----------
x : str | array_like
x aesthetic
y : str | array_like
y aesthetic
data : dataframe
Data frame to use (optional). If not specified,
will create one, extracting arrays from the
current environment.
geom : str | list
*geom(s)* to do the drawing. If ``auto``, defaults
to 'point' if ``x`` and ``y`` are specified or
'histogram' if only ``x`` is specified.
xlim : tuple
x-axis limits
ylim : tuple
y-axis limits
log : str in ``{'x', 'y', 'xy'}``
Which variables to log transform.
main : str
Plot title
xlab : str
x-axis label
ylab : str
y-axis label
asp : str | float
The y/x aspect ratio.
**kwargs : dict
Arguments passed on to the geom.
Returns
-------
p: ggplot
ggplot object | [
"Quick",
"plot"
] | python | train |
slhck/ffmpeg-normalize | ffmpeg_normalize/_media_file.py | https://github.com/slhck/ffmpeg-normalize/blob/18477a7f2d092777ee238340be40c04ecb45c132/ffmpeg_normalize/_media_file.py#L51-L114 | def parse_streams(self):
"""
Try to parse all input streams from file
"""
logger.debug("Parsing streams of {}".format(self.input_file))
cmd = [
self.ffmpeg_normalize.ffmpeg_exe, '-i', self.input_file,
'-c', 'copy', '-t', '0', '-map', '0',
'-f', 'null', NUL
]
cmd_runner = CommandRunner(cmd)
cmd_runner.run_command()
output = cmd_runner.get_output()
logger.debug("Stream parsing command output:")
logger.debug(output)
output_lines = [line.strip() for line in output.split('\n')]
for line in output_lines:
if not line.startswith('Stream'):
continue
stream_id_match = re.search(r'#0:([\d]+)', line)
if stream_id_match:
stream_id = int(stream_id_match.group(1))
if stream_id in self._stream_ids():
continue
else:
continue
if 'Audio' in line:
logger.debug("Found audio stream at index {}".format(stream_id))
sample_rate_match = re.search(r'(\d+) Hz', line)
sample_rate = int(sample_rate_match.group(1)) if sample_rate_match else None
bit_depth_match = re.search(r's(\d+)p?,', line)
bit_depth = int(bit_depth_match.group(1)) if bit_depth_match else None
self.streams['audio'][stream_id] = AudioStream(self, stream_id, sample_rate, bit_depth)
elif 'Video' in line:
logger.debug("Found video stream at index {}".format(stream_id))
self.streams['video'][stream_id] = VideoStream(self, stream_id)
elif 'Subtitle' in line:
logger.debug("Found subtitle stream at index {}".format(stream_id))
self.streams['subtitle'][stream_id] = SubtitleStream(self, stream_id)
if not self.streams['audio']:
raise FFmpegNormalizeError(
"Input file {} does not contain any audio streams"
.format(self.input_file))
if os.path.splitext(self.output_file)[1].lower() in ['.wav', '.mp3', '.aac']:
logger.warning(
"Output file only supports one stream. "
"Keeping only first audio stream."
)
first_stream = list(self.streams['audio'].values())[0]
self.streams['audio'] = {first_stream.stream_id: first_stream}
self.streams['video'] = {}
self.streams['subtitle'] = {} | [
"def",
"parse_streams",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Parsing streams of {}\"",
".",
"format",
"(",
"self",
".",
"input_file",
")",
")",
"cmd",
"=",
"[",
"self",
".",
"ffmpeg_normalize",
".",
"ffmpeg_exe",
",",
"'-i'",
",",
"self",... | Try to parse all input streams from file | [
"Try",
"to",
"parse",
"all",
"input",
"streams",
"from",
"file"
] | python | train |
blockstack/blockstack-core | blockstack/lib/storage/crawl.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/storage/crawl.py#L208-L221 | def add_atlas_zonefile_data(zonefile_text, zonefile_dir, fsync=True):
"""
Add a zone file to the atlas zonefiles
Return True on success
Return False on error
"""
rc = store_atlas_zonefile_data(zonefile_text, zonefile_dir, fsync=fsync)
if not rc:
zonefile_hash = get_zonefile_data_hash( zonefile_text )
log.error("Failed to save zonefile {}".format(zonefile_hash))
rc = False
return rc | [
"def",
"add_atlas_zonefile_data",
"(",
"zonefile_text",
",",
"zonefile_dir",
",",
"fsync",
"=",
"True",
")",
":",
"rc",
"=",
"store_atlas_zonefile_data",
"(",
"zonefile_text",
",",
"zonefile_dir",
",",
"fsync",
"=",
"fsync",
")",
"if",
"not",
"rc",
":",
"zonef... | Add a zone file to the atlas zonefiles
Return True on success
Return False on error | [
"Add",
"a",
"zone",
"file",
"to",
"the",
"atlas",
"zonefiles",
"Return",
"True",
"on",
"success",
"Return",
"False",
"on",
"error"
] | python | train |
Kentzo/Power | power/darwin.py | https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L209-L215 | def stopPowerNotificationsThread(self):
"""Removes the only source from NSRunLoop and cancels thread."""
assert NSThread.currentThread() == self._thread
CFRunLoopSourceInvalidate(self._source)
self._source = None
NSThread.currentThread().cancel() | [
"def",
"stopPowerNotificationsThread",
"(",
"self",
")",
":",
"assert",
"NSThread",
".",
"currentThread",
"(",
")",
"==",
"self",
".",
"_thread",
"CFRunLoopSourceInvalidate",
"(",
"self",
".",
"_source",
")",
"self",
".",
"_source",
"=",
"None",
"NSThread",
".... | Removes the only source from NSRunLoop and cancels thread. | [
"Removes",
"the",
"only",
"source",
"from",
"NSRunLoop",
"and",
"cancels",
"thread",
"."
] | python | train |
jopohl/urh | src/urh/controller/CompareFrameController.py | https://github.com/jopohl/urh/blob/2eb33b125c8407964cd1092843cde5010eb88aae/src/urh/controller/CompareFrameController.py#L201-L207 | def protocols(self):
"""
:rtype: dict[int, list of ProtocolAnalyzer]
"""
if self.__protocols is None:
self.__protocols = self.proto_tree_model.protocols
return self.__protocols | [
"def",
"protocols",
"(",
"self",
")",
":",
"if",
"self",
".",
"__protocols",
"is",
"None",
":",
"self",
".",
"__protocols",
"=",
"self",
".",
"proto_tree_model",
".",
"protocols",
"return",
"self",
".",
"__protocols"
] | :rtype: dict[int, list of ProtocolAnalyzer] | [
":",
"rtype",
":",
"dict",
"[",
"int",
"list",
"of",
"ProtocolAnalyzer",
"]"
] | python | train |
guaix-ucm/numina | numina/logger.py | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/logger.py#L30-L54 | def log_to_history(logger, name):
"""Decorate function, adding a logger handler stored in FITS."""
def log_to_history_decorator(method):
def l2h_method(self, ri):
history_header = fits.Header()
fh = FITSHistoryHandler(history_header)
fh.setLevel(logging.INFO)
logger.addHandler(fh)
try:
result = method(self, ri)
field = getattr(result, name, None)
if field:
with field.open() as hdulist:
hdr = hdulist[0].header
hdr.extend(history_header.cards)
return result
finally:
logger.removeHandler(fh)
return l2h_method
return log_to_history_decorator | [
"def",
"log_to_history",
"(",
"logger",
",",
"name",
")",
":",
"def",
"log_to_history_decorator",
"(",
"method",
")",
":",
"def",
"l2h_method",
"(",
"self",
",",
"ri",
")",
":",
"history_header",
"=",
"fits",
".",
"Header",
"(",
")",
"fh",
"=",
"FITSHist... | Decorate function, adding a logger handler stored in FITS. | [
"Decorate",
"function",
"adding",
"a",
"logger",
"handler",
"stored",
"in",
"FITS",
"."
] | python | train |
androguard/androguard | androguard/core/bytecodes/axml/__init__.py | https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/axml/__init__.py#L2383-L2392 | def get_language_and_region(self):
"""
Returns the combined language+region string or \x00\x00 for the default locale
:return:
"""
if self.locale != 0:
_language = self._unpack_language_or_region([self.locale & 0xff, (self.locale & 0xff00) >> 8, ], ord('a'))
_region = self._unpack_language_or_region([(self.locale & 0xff0000) >> 16, (self.locale & 0xff000000) >> 24, ], ord('0'))
return (_language + "-r" + _region) if _region else _language
return "\x00\x00" | [
"def",
"get_language_and_region",
"(",
"self",
")",
":",
"if",
"self",
".",
"locale",
"!=",
"0",
":",
"_language",
"=",
"self",
".",
"_unpack_language_or_region",
"(",
"[",
"self",
".",
"locale",
"&",
"0xff",
",",
"(",
"self",
".",
"locale",
"&",
"0xff00... | Returns the combined language+region string or \x00\x00 for the default locale
:return: | [
"Returns",
"the",
"combined",
"language",
"+",
"region",
"string",
"or",
"\\",
"x00",
"\\",
"x00",
"for",
"the",
"default",
"locale",
":",
"return",
":"
] | python | train |
roboogle/gtkmvc3 | gtkmvco/examples/undo/undo_manager.py | https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/examples/undo/undo_manager.py#L78-L82 | def can_undo(self):
"""
Are there actions to undo?
"""
return bool(self._undo) or bool(self._open and self._open[0]) | [
"def",
"can_undo",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"_undo",
")",
"or",
"bool",
"(",
"self",
".",
"_open",
"and",
"self",
".",
"_open",
"[",
"0",
"]",
")"
] | Are there actions to undo? | [
"Are",
"there",
"actions",
"to",
"undo?"
] | python | train |
resync/resync | resync/list_base_with_index.py | https://github.com/resync/resync/blob/98292c17b2c00f2d6f5191c6ab51fef8c292a018/resync/list_base_with_index.py#L352-L356 | def index_as_xml(self):
"""XML serialization of this list taken to be sitemapindex entries."""
self.default_capability()
s = self.new_sitemap()
return s.resources_as_xml(self, sitemapindex=True) | [
"def",
"index_as_xml",
"(",
"self",
")",
":",
"self",
".",
"default_capability",
"(",
")",
"s",
"=",
"self",
".",
"new_sitemap",
"(",
")",
"return",
"s",
".",
"resources_as_xml",
"(",
"self",
",",
"sitemapindex",
"=",
"True",
")"
] | XML serialization of this list taken to be sitemapindex entries. | [
"XML",
"serialization",
"of",
"this",
"list",
"taken",
"to",
"be",
"sitemapindex",
"entries",
"."
] | python | train |
Tanganelli/CoAPthon3 | coapthon/client/coap.py | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/coap.py#L309-L321 | def _send_rst(self, transaction): # pragma: no cover
"""
Sends an RST message for the response.
:param transaction: transaction that holds the response
"""
rst = Message()
rst.type = defines.Types['RST']
if not transaction.response.acknowledged:
rst = self._messageLayer.send_empty(transaction, transaction.response, rst)
self.send_datagram(rst) | [
"def",
"_send_rst",
"(",
"self",
",",
"transaction",
")",
":",
"# pragma: no cover",
"rst",
"=",
"Message",
"(",
")",
"rst",
".",
"type",
"=",
"defines",
".",
"Types",
"[",
"'RST'",
"]",
"if",
"not",
"transaction",
".",
"response",
".",
"acknowledged",
"... | Sends an RST message for the response.
:param transaction: transaction that holds the response | [
"Sends",
"an",
"RST",
"message",
"for",
"the",
"response",
"."
] | python | train |
coins13/twins | twins/twins.py | https://github.com/coins13/twins/blob/d66cc850007a25f01812a9d8c7e3efe64a631ca2/twins/twins.py#L274-L306 | def get_registered_courses (self):
""" 履修登録済み授業を取得 """
kdb = twins.kdb.Kdb()
_reged = []
for x in ((1, "A"), (2, "A"), (3, "A"), (4, "B"), (5, "B"), (6, "B")):
self.req("RSW0001000-flow")
self.get({
"_eventId": "search",
"moduleCode": x[0],
"gakkiKbnCode": x[1]
})
self.post({"_eventId": "output"}, True)
r = self.post({
"_eventId": "output",
"outputType": "csv",
"fileEncoding": "UTF8",
"logicalDeleteFlg": 0
}, True)
_reged += list(csv.reader(r.text.strip().split("\n")))
if _reged == []:
return []
already_appeared = []
reged = []
for c in [kdb.get_course_info(c[0]) for c in _reged]:
# 重複を除去
if c is None or c["id"] in already_appeared:
continue
reged.append(c)
already_appeared.append(c["id"])
return reged | [
"def",
"get_registered_courses",
"(",
"self",
")",
":",
"kdb",
"=",
"twins",
".",
"kdb",
".",
"Kdb",
"(",
")",
"_reged",
"=",
"[",
"]",
"for",
"x",
"in",
"(",
"(",
"1",
",",
"\"A\"",
")",
",",
"(",
"2",
",",
"\"A\"",
")",
",",
"(",
"3",
",",
... | 履修登録済み授業を取得 | [
"履修登録済み授業を取得"
] | python | train |
vertexproject/synapse | synapse/lib/base.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/base.py#L161-L170 | def onfini(self, func):
'''
Add a function/coroutine/Base to be called on fini().
'''
if isinstance(func, Base):
self.tofini.add(func)
return
assert self.anitted
self._fini_funcs.append(func) | [
"def",
"onfini",
"(",
"self",
",",
"func",
")",
":",
"if",
"isinstance",
"(",
"func",
",",
"Base",
")",
":",
"self",
".",
"tofini",
".",
"add",
"(",
"func",
")",
"return",
"assert",
"self",
".",
"anitted",
"self",
".",
"_fini_funcs",
".",
"append",
... | Add a function/coroutine/Base to be called on fini(). | [
"Add",
"a",
"function",
"/",
"coroutine",
"/",
"Base",
"to",
"be",
"called",
"on",
"fini",
"()",
"."
] | python | train |
croscon/fleaker | fleaker/peewee/mixins/search.py | https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/search.py#L97-L180 | def search(cls, term, fields=()):
"""Generic SQL search function that uses SQL ``LIKE`` to search the
database for matching records. The records are sorted by their
relavancey to the search term.
The query searches and sorts on the folling criteria, in order, where
the target string is ``exactly``:
1. Straight equality (``x = 'exactly'``)
2. Right hand ``LIKE`` (``x LIKE 'exact%'``)
3. Substring ``LIKE`` (``x LIKE %act%``)
Args:
term (str): The search term to apply to the query.
Keyword Args:
fields (list|tuple|None): An optional list of fields to apply the
search to. If not provided, the class variable
``Meta.search_fields`` will be used by default.
Returns:
peewee.SelectQuery: An unexecuted query for the records.
Raises:
AttributeError: Raised if `search_fields` isn't defined in the
class and `fields` aren't provided for the function.
"""
if not any((cls._meta.search_fields, fields)):
raise AttributeError(
"A list of searchable fields must be provided in the class's "
"search_fields or provided to this function in the `fields` "
"kwarg."
)
# If fields are provided, override the ones in the class
if not fields:
fields = cls._meta.search_fields
query = cls.select()
# Cache the LIKE terms
like_term = ''.join((term, '%'))
full_like_term = ''.join(('%', term, '%'))
# Cache the order by terms
# @TODO Peewee's order_by supports an `extend` kwarg will will allow
# for updating of the order by part of the query, but it's only
# supported in Peewee 2.8.5 and newer. Determine if we can support this
# before switching.
# http://docs.peewee-orm.com/en/stable/peewee/api.html#SelectQuery.order_by
order_by = []
# Store the clauses seperately because it is needed to perform an OR on
# them and that's somehow impossible with their query builder in
# a loop.
clauses = []
for field_name in fields:
# Cache the field, raising an exception if the field doesn't
# exist.
field = getattr(cls, field_name)
# Apply the search term case insensitively
clauses.append(
(field == term) |
(field ** like_term) |
(field ** full_like_term)
)
order_by.append(case(None, (
# Straight matches should show up first
(field == term, 0),
# Similar terms should show up second
(field ** like_term, 1),
# Substring matches should show up third
(field ** full_like_term, 2),
), default=3).asc())
# Apply the clauses to the query
query = query.where(reduce(operator.or_, clauses))
# Apply the sort order so it's influenced by the search term relevance.
query = query.order_by(*order_by)
return query | [
"def",
"search",
"(",
"cls",
",",
"term",
",",
"fields",
"=",
"(",
")",
")",
":",
"if",
"not",
"any",
"(",
"(",
"cls",
".",
"_meta",
".",
"search_fields",
",",
"fields",
")",
")",
":",
"raise",
"AttributeError",
"(",
"\"A list of searchable fields must b... | Generic SQL search function that uses SQL ``LIKE`` to search the
database for matching records. The records are sorted by their
relavancey to the search term.
The query searches and sorts on the folling criteria, in order, where
the target string is ``exactly``:
1. Straight equality (``x = 'exactly'``)
2. Right hand ``LIKE`` (``x LIKE 'exact%'``)
3. Substring ``LIKE`` (``x LIKE %act%``)
Args:
term (str): The search term to apply to the query.
Keyword Args:
fields (list|tuple|None): An optional list of fields to apply the
search to. If not provided, the class variable
``Meta.search_fields`` will be used by default.
Returns:
peewee.SelectQuery: An unexecuted query for the records.
Raises:
AttributeError: Raised if `search_fields` isn't defined in the
class and `fields` aren't provided for the function. | [
"Generic",
"SQL",
"search",
"function",
"that",
"uses",
"SQL",
"LIKE",
"to",
"search",
"the",
"database",
"for",
"matching",
"records",
".",
"The",
"records",
"are",
"sorted",
"by",
"their",
"relavancey",
"to",
"the",
"search",
"term",
"."
] | python | train |
nickmckay/LiPD-utilities | Python/lipd/lpd_noaa.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/lpd_noaa.py#L806-L823 | def __get_filename(table):
"""
Get filename from a data table
:param dict table:
:return str:
"""
try:
filename = table['filename']
except KeyError as e:
filename = ""
logger_lpd_noaa.warning("get_filename: KeyError: Table missing filename, {}".format(e))
except TypeError:
try:
filename = table[0]["filename"]
except Exception as e:
filename = ""
logger_lpd_noaa.warning("get_filename: Generic: Unable to get filename from table, {}".format(e))
return filename | [
"def",
"__get_filename",
"(",
"table",
")",
":",
"try",
":",
"filename",
"=",
"table",
"[",
"'filename'",
"]",
"except",
"KeyError",
"as",
"e",
":",
"filename",
"=",
"\"\"",
"logger_lpd_noaa",
".",
"warning",
"(",
"\"get_filename: KeyError: Table missing filename,... | Get filename from a data table
:param dict table:
:return str: | [
"Get",
"filename",
"from",
"a",
"data",
"table",
":",
"param",
"dict",
"table",
":",
":",
"return",
"str",
":"
] | python | train |
netpieio/microgear-python | microgear/cache.py | https://github.com/netpieio/microgear-python/blob/ea9bb352c7dd84b92f3462177645eaa4d448d50b/microgear/cache.py#L9-L16 | def get_item(key):
"""Return content in cached file in JSON format"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
try:
return json.loads(open(CACHED_KEY_FILE, "rb").read().decode('UTF-8'))["_"]
except (IOError, ValueError):
return None | [
"def",
"get_item",
"(",
"key",
")",
":",
"CACHED_KEY_FILE",
"=",
"os",
".",
"path",
".",
"join",
"(",
"CURRENT_DIR",
",",
"key",
")",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"open",
"(",
"CACHED_KEY_FILE",
",",
"\"rb\"",
")",
".",
"read",
"(... | Return content in cached file in JSON format | [
"Return",
"content",
"in",
"cached",
"file",
"in",
"JSON",
"format"
] | python | train |
ladybug-tools/ladybug | ladybug/_datacollectionbase.py | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L607-L626 | def _percentile(self, values, percent, key=lambda x: x):
"""Find the percentile of a list of values.
Args:
values: A list of values for which percentiles are desired
percent: A float value from 0 to 100 representing the requested percentile.
key: optional key function to compute value from each element of N.
Return:
The percentile of the values
"""
vals = sorted(values)
k = (len(vals) - 1) * (percent / 100)
f = math.floor(k)
c = math.ceil(k)
if f == c:
return key(vals[int(k)])
d0 = key(vals[int(f)]) * (c - k)
d1 = key(vals[int(c)]) * (k - f)
return d0 + d1 | [
"def",
"_percentile",
"(",
"self",
",",
"values",
",",
"percent",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"vals",
"=",
"sorted",
"(",
"values",
")",
"k",
"=",
"(",
"len",
"(",
"vals",
")",
"-",
"1",
")",
"*",
"(",
"percent",
"/",
... | Find the percentile of a list of values.
Args:
values: A list of values for which percentiles are desired
percent: A float value from 0 to 100 representing the requested percentile.
key: optional key function to compute value from each element of N.
Return:
The percentile of the values | [
"Find",
"the",
"percentile",
"of",
"a",
"list",
"of",
"values",
"."
] | python | train |
kensho-technologies/graphql-compiler | setup.py | https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/setup.py#L33-L40 | def find_name():
"""Only define name in one place"""
name_file = read_file('__init__.py')
name_match = re.search(r'^__package_name__ = ["\']([^"\']*)["\']',
name_file, re.M)
if name_match:
return name_match.group(1)
raise RuntimeError('Unable to find name string.') | [
"def",
"find_name",
"(",
")",
":",
"name_file",
"=",
"read_file",
"(",
"'__init__.py'",
")",
"name_match",
"=",
"re",
".",
"search",
"(",
"r'^__package_name__ = [\"\\']([^\"\\']*)[\"\\']'",
",",
"name_file",
",",
"re",
".",
"M",
")",
"if",
"name_match",
":",
"... | Only define name in one place | [
"Only",
"define",
"name",
"in",
"one",
"place"
] | python | train |
minhhoit/yacms | yacms/generic/managers.py | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/managers.py#L46-L59 | def get_or_create_iexact(self, **kwargs):
"""
Case insensitive title version of ``get_or_create``. Also
allows for multiple existing results.
"""
lookup = dict(**kwargs)
try:
lookup["title__iexact"] = lookup.pop("title")
except KeyError:
pass
try:
return self.filter(**lookup)[0], False
except IndexError:
return self.create(**kwargs), True | [
"def",
"get_or_create_iexact",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"lookup",
"=",
"dict",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"lookup",
"[",
"\"title__iexact\"",
"]",
"=",
"lookup",
".",
"pop",
"(",
"\"title\"",
")",
"except",
"KeyErr... | Case insensitive title version of ``get_or_create``. Also
allows for multiple existing results. | [
"Case",
"insensitive",
"title",
"version",
"of",
"get_or_create",
".",
"Also",
"allows",
"for",
"multiple",
"existing",
"results",
"."
] | python | train |
allenai/allennlp | allennlp/modules/token_embedders/embedding.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/token_embedders/embedding.py#L374-L443 | def _read_embeddings_from_text_file(file_uri: str,
embedding_dim: int,
vocab: Vocabulary,
namespace: str = "tokens") -> torch.FloatTensor:
"""
Read pre-trained word vectors from an eventually compressed text file, possibly contained
inside an archive with multiple files. The text file is assumed to be utf-8 encoded with
space-separated fields: [word] [dim 1] [dim 2] ...
Lines that contain more numerical tokens than ``embedding_dim`` raise a warning and are skipped.
The remainder of the docstring is identical to ``_read_pretrained_embeddings_file``.
"""
tokens_to_keep = set(vocab.get_index_to_token_vocabulary(namespace).values())
vocab_size = vocab.get_vocab_size(namespace)
embeddings = {}
# First we read the embeddings from the file, only keeping vectors for the words we need.
logger.info("Reading pretrained embeddings from file")
with EmbeddingsTextFile(file_uri) as embeddings_file:
for line in Tqdm.tqdm(embeddings_file):
token = line.split(' ', 1)[0]
if token in tokens_to_keep:
fields = line.rstrip().split(' ')
if len(fields) - 1 != embedding_dim:
# Sometimes there are funny unicode parsing problems that lead to different
# fields lengths (e.g., a word with a unicode space character that splits
# into more than one column). We skip those lines. Note that if you have
# some kind of long header, this could result in all of your lines getting
# skipped. It's hard to check for that here; you just have to look in the
# embedding_misses_file and at the model summary to make sure things look
# like they are supposed to.
logger.warning("Found line with wrong number of dimensions (expected: %d; actual: %d): %s",
embedding_dim, len(fields) - 1, line)
continue
vector = numpy.asarray(fields[1:], dtype='float32')
embeddings[token] = vector
if not embeddings:
raise ConfigurationError("No embeddings of correct dimension found; you probably "
"misspecified your embedding_dim parameter, or didn't "
"pre-populate your Vocabulary")
all_embeddings = numpy.asarray(list(embeddings.values()))
embeddings_mean = float(numpy.mean(all_embeddings))
embeddings_std = float(numpy.std(all_embeddings))
# Now we initialize the weight matrix for an embedding layer, starting with random vectors,
# then filling in the word vectors we just read.
logger.info("Initializing pre-trained embedding layer")
embedding_matrix = torch.FloatTensor(vocab_size, embedding_dim).normal_(embeddings_mean,
embeddings_std)
num_tokens_found = 0
index_to_token = vocab.get_index_to_token_vocabulary(namespace)
for i in range(vocab_size):
token = index_to_token[i]
# If we don't have a pre-trained vector for this word, we'll just leave this row alone,
# so the word has a random initialization.
if token in embeddings:
embedding_matrix[i] = torch.FloatTensor(embeddings[token])
num_tokens_found += 1
else:
logger.debug("Token %s was not found in the embedding file. Initialising randomly.", token)
logger.info("Pretrained embeddings were found for %d out of %d tokens",
num_tokens_found, vocab_size)
return embedding_matrix | [
"def",
"_read_embeddings_from_text_file",
"(",
"file_uri",
":",
"str",
",",
"embedding_dim",
":",
"int",
",",
"vocab",
":",
"Vocabulary",
",",
"namespace",
":",
"str",
"=",
"\"tokens\"",
")",
"->",
"torch",
".",
"FloatTensor",
":",
"tokens_to_keep",
"=",
"set"... | Read pre-trained word vectors from an eventually compressed text file, possibly contained
inside an archive with multiple files. The text file is assumed to be utf-8 encoded with
space-separated fields: [word] [dim 1] [dim 2] ...
Lines that contain more numerical tokens than ``embedding_dim`` raise a warning and are skipped.
The remainder of the docstring is identical to ``_read_pretrained_embeddings_file``. | [
"Read",
"pre",
"-",
"trained",
"word",
"vectors",
"from",
"an",
"eventually",
"compressed",
"text",
"file",
"possibly",
"contained",
"inside",
"an",
"archive",
"with",
"multiple",
"files",
".",
"The",
"text",
"file",
"is",
"assumed",
"to",
"be",
"utf",
"-",
... | python | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/topiclists.py | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/topiclists.py#L74-L104 | def _build_toctree(self):
"""Create a hidden toctree node with the contents of a directory
prefixed by the directory name specified by the `toctree` directive
option.
"""
dirname = posixpath.dirname(self._env.docname)
tree_prefix = self.options['toctree'].strip()
root = posixpath.normpath(posixpath.join(dirname, tree_prefix))
docnames = [docname for docname in self._env.found_docs
if docname.startswith(root)]
# Sort docnames alphabetically based on **class** name.
# The standard we assume is that task doc pages are named after
# their Python namespace.
# NOTE: this ordering only applies to the toctree; the visual ordering
# is set by `process_task_topic_list`.
# NOTE: docnames are **always** POSIX-like paths
class_names = [docname.split('/')[-1].split('.')[-1]
for docname in docnames]
docnames = [docname for docname, _ in
sorted(zip(docnames, class_names),
key=lambda pair: pair[1])]
tocnode = sphinx.addnodes.toctree()
tocnode['includefiles'] = docnames
tocnode['entries'] = [(None, docname) for docname in docnames]
tocnode['maxdepth'] = -1
tocnode['glob'] = None
tocnode['hidden'] = True
return tocnode | [
"def",
"_build_toctree",
"(",
"self",
")",
":",
"dirname",
"=",
"posixpath",
".",
"dirname",
"(",
"self",
".",
"_env",
".",
"docname",
")",
"tree_prefix",
"=",
"self",
".",
"options",
"[",
"'toctree'",
"]",
".",
"strip",
"(",
")",
"root",
"=",
"posixpa... | Create a hidden toctree node with the contents of a directory
prefixed by the directory name specified by the `toctree` directive
option. | [
"Create",
"a",
"hidden",
"toctree",
"node",
"with",
"the",
"contents",
"of",
"a",
"directory",
"prefixed",
"by",
"the",
"directory",
"name",
"specified",
"by",
"the",
"toctree",
"directive",
"option",
"."
] | python | train |
mikkeljans/pyconomic | pyconomic/base.py | https://github.com/mikkeljans/pyconomic/blob/845b8148a364cf5be9065f8a70133d4f16ab645d/pyconomic/base.py#L76-L117 | def __find_handles(self, model, **spec):
""" find model instances based on given filter (spec)
The filter is based on available server-calls, so some values might not be available for filtering.
Multiple filter-values is going to do multiple server-calls.
For complex filters in small datasets, it might be faster to fetch all and do your own in-memory filter.
Empty filter will fetch all.
:param model: subclass of EConomicsModel
:param spec: mapping of values to filter by
:return: a list of EConomicsModel instances
"""
server_calls = []
filter_names = dict([(f['name'], f['method'],) for f in model.get_filters()])
if not spec:
server_calls.append({'method': "%s_GetAll" % model.__name__, 'args': []})
else:
for key, value in spec.items():
if not key in filter_names:
raise ValueError("no server-method exists for filtering by '%s'" % key)
args = []
if not hasattr(value, '__iter__'):
value = [value]
if key.endswith('_list'):
vtype = type(value[0]).__name__
# TODO: this surely does not cover all cases of data types
array = self.soap_factory.create('ArrayOf%s' % vtype.capitalize())
getattr(array, "%s" % vtype).extend(value)
args.append(array)
else:
args.extend(value)
method = "%s_%s" % (model.__name__, filter_names[key])
if filter_names[key].startswith('GetAll'):
args = []
server_calls.append({'method': method, 'args': args, 'expect': "%sHandle" % model.__name__})
handles = [
map(Handle, self.fetch_list(scall['method'], scall.get('expect'), *scall['args']))
for scall in server_calls
]
return [h.wsdl for h in reduce(set.intersection, map(set, handles))] | [
"def",
"__find_handles",
"(",
"self",
",",
"model",
",",
"*",
"*",
"spec",
")",
":",
"server_calls",
"=",
"[",
"]",
"filter_names",
"=",
"dict",
"(",
"[",
"(",
"f",
"[",
"'name'",
"]",
",",
"f",
"[",
"'method'",
"]",
",",
")",
"for",
"f",
"in",
... | find model instances based on given filter (spec)
The filter is based on available server-calls, so some values might not be available for filtering.
Multiple filter-values is going to do multiple server-calls.
For complex filters in small datasets, it might be faster to fetch all and do your own in-memory filter.
Empty filter will fetch all.
:param model: subclass of EConomicsModel
:param spec: mapping of values to filter by
:return: a list of EConomicsModel instances | [
"find",
"model",
"instances",
"based",
"on",
"given",
"filter",
"(",
"spec",
")",
"The",
"filter",
"is",
"based",
"on",
"available",
"server",
"-",
"calls",
"so",
"some",
"values",
"might",
"not",
"be",
"available",
"for",
"filtering",
".",
"Multiple",
"fi... | python | train |
trailofbits/manticore | manticore/core/manticore.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/manticore.py#L424-L439 | def run(self, procs=1, timeout=None, should_profile=False):
"""
Runs analysis.
:param int procs: Number of parallel worker processes
:param timeout: Analysis timeout, in seconds
"""
assert not self.running, "Manticore is already running."
self._start_run()
self._last_run_stats['time_started'] = time.time()
with self.shutdown_timeout(timeout):
self._start_workers(procs, profiling=should_profile)
self._join_workers()
self._finish_run(profiling=should_profile) | [
"def",
"run",
"(",
"self",
",",
"procs",
"=",
"1",
",",
"timeout",
"=",
"None",
",",
"should_profile",
"=",
"False",
")",
":",
"assert",
"not",
"self",
".",
"running",
",",
"\"Manticore is already running.\"",
"self",
".",
"_start_run",
"(",
")",
"self",
... | Runs analysis.
:param int procs: Number of parallel worker processes
:param timeout: Analysis timeout, in seconds | [
"Runs",
"analysis",
"."
] | python | valid |
TomasTomecek/sen | sen/tui/commands/base.py | https://github.com/TomasTomecek/sen/blob/239b4868125814e8bf5527708119fc08b35f6cc0/sen/tui/commands/base.py#L120-L159 | def process(self, argument_list):
"""
:param argument_list: list of str, input from user
:return: dict:
{"cleaned_arg_name": "value"}
"""
arg_index = 0
for a in argument_list:
opt_and_val = a.split("=", 1)
opt_name = opt_and_val[0]
try:
# option
argument = self.options[opt_name]
except KeyError:
# argument
try:
argument = self.arguments[arg_index]
except IndexError:
logger.error("option/argument %r not specified", a)
raise NoSuchOptionOrArgument("No such option or argument: %r" % opt_name)
logger.info("argument found: %s", argument)
safe_arg_name = normalize_arg_name(argument.name) # so we can access names-with-dashes
logger.info("argument is available under name %r", safe_arg_name)
if isinstance(argument, Argument):
arg_index += 1
value = (a, )
else:
try:
value = (opt_and_val[1], )
except IndexError:
value = tuple()
arg_val = argument.action(*value)
logger.info("argument %r has value %r", safe_arg_name, arg_val)
self.given_arguments[safe_arg_name] = arg_val
return self.given_arguments | [
"def",
"process",
"(",
"self",
",",
"argument_list",
")",
":",
"arg_index",
"=",
"0",
"for",
"a",
"in",
"argument_list",
":",
"opt_and_val",
"=",
"a",
".",
"split",
"(",
"\"=\"",
",",
"1",
")",
"opt_name",
"=",
"opt_and_val",
"[",
"0",
"]",
"try",
":... | :param argument_list: list of str, input from user
:return: dict:
{"cleaned_arg_name": "value"} | [
":",
"param",
"argument_list",
":",
"list",
"of",
"str",
"input",
"from",
"user",
":",
"return",
":",
"dict",
":",
"{",
"cleaned_arg_name",
":",
"value",
"}"
] | python | train |
spyder-ide/spyder | spyder/widgets/browser.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/browser.py#L301-L304 | def url_combo_activated(self, valid):
"""Load URL from combo box first item"""
text = to_text_string(self.url_combo.currentText())
self.go_to(self.text_to_url(text)) | [
"def",
"url_combo_activated",
"(",
"self",
",",
"valid",
")",
":",
"text",
"=",
"to_text_string",
"(",
"self",
".",
"url_combo",
".",
"currentText",
"(",
")",
")",
"self",
".",
"go_to",
"(",
"self",
".",
"text_to_url",
"(",
"text",
")",
")"
] | Load URL from combo box first item | [
"Load",
"URL",
"from",
"combo",
"box",
"first",
"item"
] | python | train |
owncloud/pyocclient | owncloud/owncloud.py | https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1722-L1749 | def _make_dav_request(self, method, path, **kwargs):
"""Makes a WebDAV request
:param method: HTTP method
:param path: remote path of the targetted file
:param \*\*kwargs: optional arguments that ``requests.Request.request`` accepts
:returns array of :class:`FileInfo` if the response
contains it, or True if the operation succeded, False
if it didn't
"""
if self._debug:
print('DAV request: %s %s' % (method, path))
if kwargs.get('headers'):
print('Headers: ', kwargs.get('headers'))
path = self._normalize_path(path)
res = self._session.request(
method,
self._webdav_url + parse.quote(self._encode_string(path)),
**kwargs
)
if self._debug:
print('DAV status: %i' % res.status_code)
if res.status_code in [200, 207]:
return self._parse_dav_response(res)
if res.status_code in [204, 201]:
return True
raise HTTPResponseError(res) | [
"def",
"_make_dav_request",
"(",
"self",
",",
"method",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_debug",
":",
"print",
"(",
"'DAV request: %s %s'",
"%",
"(",
"method",
",",
"path",
")",
")",
"if",
"kwargs",
".",
"get",
"("... | Makes a WebDAV request
:param method: HTTP method
:param path: remote path of the targetted file
:param \*\*kwargs: optional arguments that ``requests.Request.request`` accepts
:returns array of :class:`FileInfo` if the response
contains it, or True if the operation succeded, False
if it didn't | [
"Makes",
"a",
"WebDAV",
"request"
] | python | train |
mgoral/subconvert | src/subconvert/utils/SubtitleSearch.py | https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/utils/SubtitleSearch.py#L45-L52 | def last(self):
"""Returns the last element accessed via next() or prev().
Returns the first element of range() if neither of these was called."""
if len(self._range) == 0:
raise IndexError("range is empty")
if self._idx == -1:
return self._range[0]
return self._get(self._idx) | [
"def",
"last",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_range",
")",
"==",
"0",
":",
"raise",
"IndexError",
"(",
"\"range is empty\"",
")",
"if",
"self",
".",
"_idx",
"==",
"-",
"1",
":",
"return",
"self",
".",
"_range",
"[",
"0",
... | Returns the last element accessed via next() or prev().
Returns the first element of range() if neither of these was called. | [
"Returns",
"the",
"last",
"element",
"accessed",
"via",
"next",
"()",
"or",
"prev",
"()",
".",
"Returns",
"the",
"first",
"element",
"of",
"range",
"()",
"if",
"neither",
"of",
"these",
"was",
"called",
"."
] | python | train |
Unidata/MetPy | metpy/io/_nexrad_msgs/parse_spec.py | https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/io/_nexrad_msgs/parse_spec.py#L138-L146 | def fix_desc(desc, units=None):
"""Clean up description column."""
full_desc = desc.strip()
if units and units != 'N/A':
if full_desc:
full_desc += ' (' + units + ')'
else:
full_desc = units
return full_desc | [
"def",
"fix_desc",
"(",
"desc",
",",
"units",
"=",
"None",
")",
":",
"full_desc",
"=",
"desc",
".",
"strip",
"(",
")",
"if",
"units",
"and",
"units",
"!=",
"'N/A'",
":",
"if",
"full_desc",
":",
"full_desc",
"+=",
"' ('",
"+",
"units",
"+",
"')'",
"... | Clean up description column. | [
"Clean",
"up",
"description",
"column",
"."
] | python | train |
Apstra/aeon-venos | pylib/aeon/nxos/autoload/guestshell.py | https://github.com/Apstra/aeon-venos/blob/4d4f73d5904831ddc78c30922a8a226c90cf7d90/pylib/aeon/nxos/autoload/guestshell.py#L150-L177 | def sudoers(self, enable):
"""
This method is used to enable/disable bash sudo commands running
through the guestshell virtual service. By default sudo access
is prevented due to the setting in the 'sudoers' file. Therefore
the setting must be disabled in the file to enable sudo commands.
This method assumes that the "bash-shell" feature is enabled.
@@@ TO-DO: have a mech to check &| control bash-shell feature support
:param enable:
True - enables sudo commands
False - disables sudo commands
:return:
returns the response of the sed command needed to make the
file change
"""
f_sudoers = "/isan/vdc_1/virtual-instance/guestshell+/rootfs/etc/sudoers"
if enable is True:
sed_cmd = r" 's/\(^Defaults *requiretty\)/#\1/g' "
elif enable is False:
sed_cmd = r" 's/^#\(Defaults *requiretty\)/\1/g' "
else:
raise RuntimeError('enable must be True or False')
self.guestshell("run bash sudo sed -i" + sed_cmd + f_sudoers) | [
"def",
"sudoers",
"(",
"self",
",",
"enable",
")",
":",
"f_sudoers",
"=",
"\"/isan/vdc_1/virtual-instance/guestshell+/rootfs/etc/sudoers\"",
"if",
"enable",
"is",
"True",
":",
"sed_cmd",
"=",
"r\" 's/\\(^Defaults *requiretty\\)/#\\1/g' \"",
"elif",
"enable",
"is",
"False"... | This method is used to enable/disable bash sudo commands running
through the guestshell virtual service. By default sudo access
is prevented due to the setting in the 'sudoers' file. Therefore
the setting must be disabled in the file to enable sudo commands.
This method assumes that the "bash-shell" feature is enabled.
@@@ TO-DO: have a mech to check &| control bash-shell feature support
:param enable:
True - enables sudo commands
False - disables sudo commands
:return:
returns the response of the sed command needed to make the
file change | [
"This",
"method",
"is",
"used",
"to",
"enable",
"/",
"disable",
"bash",
"sudo",
"commands",
"running",
"through",
"the",
"guestshell",
"virtual",
"service",
".",
"By",
"default",
"sudo",
"access",
"is",
"prevented",
"due",
"to",
"the",
"setting",
"in",
"the"... | python | train |
ARMmbed/icetea | icetea_lib/Plugin/PluginManager.py | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L90-L106 | def register_run_plugins(self, plugin_name, plugin_class):
"""
Loads a plugin as a dictionary and attaches needed parts to correct Icetea run
global parts.
:param plugin_name: Name of the plugins
:param plugin_class: PluginBase
:return: Nothing
"""
if plugin_name in self.registered_plugins:
raise PluginException("Plugin {} already registered! "
"Duplicate plugins?".format(plugin_name))
self.logger.debug("Registering plugin %s", plugin_name)
if plugin_class.get_allocators():
register_func = self.plugin_types[PluginTypes.ALLOCATOR]
register_func(plugin_name, plugin_class)
self.registered_plugins.append(plugin_name) | [
"def",
"register_run_plugins",
"(",
"self",
",",
"plugin_name",
",",
"plugin_class",
")",
":",
"if",
"plugin_name",
"in",
"self",
".",
"registered_plugins",
":",
"raise",
"PluginException",
"(",
"\"Plugin {} already registered! \"",
"\"Duplicate plugins?\"",
".",
"forma... | Loads a plugin as a dictionary and attaches needed parts to correct Icetea run
global parts.
:param plugin_name: Name of the plugins
:param plugin_class: PluginBase
:return: Nothing | [
"Loads",
"a",
"plugin",
"as",
"a",
"dictionary",
"and",
"attaches",
"needed",
"parts",
"to",
"correct",
"Icetea",
"run",
"global",
"parts",
"."
] | python | train |
saltstack/salt | salt/client/ssh/ssh_py_shim.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/ssh_py_shim.py#L143-L156 | def get_hash(path, form='sha1', chunk_size=4096):
'''
Generate a hash digest string for a file.
'''
try:
hash_type = getattr(hashlib, form)
except AttributeError:
raise ValueError('Invalid hash type: {0}'.format(form))
with open(path, 'rb') as ifile:
hash_obj = hash_type()
# read the file in in chunks, not the entire file
for chunk in iter(lambda: ifile.read(chunk_size), b''):
hash_obj.update(chunk)
return hash_obj.hexdigest() | [
"def",
"get_hash",
"(",
"path",
",",
"form",
"=",
"'sha1'",
",",
"chunk_size",
"=",
"4096",
")",
":",
"try",
":",
"hash_type",
"=",
"getattr",
"(",
"hashlib",
",",
"form",
")",
"except",
"AttributeError",
":",
"raise",
"ValueError",
"(",
"'Invalid hash typ... | Generate a hash digest string for a file. | [
"Generate",
"a",
"hash",
"digest",
"string",
"for",
"a",
"file",
"."
] | python | train |
mbakker7/timml | timml/element.py | https://github.com/mbakker7/timml/blob/91e99ad573cb8a9ad8ac1fa041c3ca44520c2390/timml/element.py#L41-L46 | def potentiallayers(self, x, y, layers, aq=None):
'''Returns array of size len(layers)
only used in building equations'''
if aq is None: aq = self.model.aq.find_aquifer_data(x, y)
pot = np.sum(self.potential(x, y, aq) * aq.eigvec, 1 )
return pot[layers] | [
"def",
"potentiallayers",
"(",
"self",
",",
"x",
",",
"y",
",",
"layers",
",",
"aq",
"=",
"None",
")",
":",
"if",
"aq",
"is",
"None",
":",
"aq",
"=",
"self",
".",
"model",
".",
"aq",
".",
"find_aquifer_data",
"(",
"x",
",",
"y",
")",
"pot",
"="... | Returns array of size len(layers)
only used in building equations | [
"Returns",
"array",
"of",
"size",
"len",
"(",
"layers",
")",
"only",
"used",
"in",
"building",
"equations"
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py#L121-L132 | def create_tab_with_current_kernel(self):
"""create a new frontend attached to the same kernel as the current tab"""
current_widget = self.tab_widget.currentWidget()
current_widget_index = self.tab_widget.indexOf(current_widget)
current_widget_name = self.tab_widget.tabText(current_widget_index)
widget = self.slave_frontend_factory(current_widget)
if 'slave' in current_widget_name:
# don't keep stacking slaves
name = current_widget_name
else:
name = '(%s) slave' % current_widget_name
self.add_tab_with_frontend(widget,name=name) | [
"def",
"create_tab_with_current_kernel",
"(",
"self",
")",
":",
"current_widget",
"=",
"self",
".",
"tab_widget",
".",
"currentWidget",
"(",
")",
"current_widget_index",
"=",
"self",
".",
"tab_widget",
".",
"indexOf",
"(",
"current_widget",
")",
"current_widget_name... | create a new frontend attached to the same kernel as the current tab | [
"create",
"a",
"new",
"frontend",
"attached",
"to",
"the",
"same",
"kernel",
"as",
"the",
"current",
"tab"
] | python | test |
Rapptz/discord.py | discord/ext/commands/core.py | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1039-L1075 | def get_command(self, name):
"""Get a :class:`.Command` or subclasses from the internal list
of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. ``'foo bar'``) will get
the subcommand ``bar`` of the group command ``foo``. If a
subcommand is not found then ``None`` is returned just as usual.
Parameters
-----------
name: :class:`str`
The name of the command to get.
Returns
--------
:class:`Command` or subclass
The command that was requested. If not found, returns ``None``.
"""
# fast path, no space in name.
if ' ' not in name:
return self.all_commands.get(name)
names = name.split()
obj = self.all_commands.get(names[0])
if not isinstance(obj, GroupMixin):
return obj
for name in names[1:]:
try:
obj = obj.all_commands[name]
except (AttributeError, KeyError):
return None
return obj | [
"def",
"get_command",
"(",
"self",
",",
"name",
")",
":",
"# fast path, no space in name.",
"if",
"' '",
"not",
"in",
"name",
":",
"return",
"self",
".",
"all_commands",
".",
"get",
"(",
"name",
")",
"names",
"=",
"name",
".",
"split",
"(",
")",
"obj",
... | Get a :class:`.Command` or subclasses from the internal list
of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. ``'foo bar'``) will get
the subcommand ``bar`` of the group command ``foo``. If a
subcommand is not found then ``None`` is returned just as usual.
Parameters
-----------
name: :class:`str`
The name of the command to get.
Returns
--------
:class:`Command` or subclass
The command that was requested. If not found, returns ``None``. | [
"Get",
"a",
":",
"class",
":",
".",
"Command",
"or",
"subclasses",
"from",
"the",
"internal",
"list",
"of",
"commands",
"."
] | python | train |
adrianoveiga/django-media-fixtures | django_media_fixtures/finders.py | https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/finders.py#L180-L189 | def get_finder(import_path):
"""
Imports the media fixtures files finder class described by import_path, where
import_path is the full Python path to the class.
"""
Finder = import_string(import_path)
if not issubclass(Finder, BaseFinder):
raise ImproperlyConfigured('Finder "%s" is not a subclass of "%s"' %
(Finder, BaseFinder))
return Finder() | [
"def",
"get_finder",
"(",
"import_path",
")",
":",
"Finder",
"=",
"import_string",
"(",
"import_path",
")",
"if",
"not",
"issubclass",
"(",
"Finder",
",",
"BaseFinder",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"'Finder \"%s\" is not a subclass of \"%s\"'",
"%... | Imports the media fixtures files finder class described by import_path, where
import_path is the full Python path to the class. | [
"Imports",
"the",
"media",
"fixtures",
"files",
"finder",
"class",
"described",
"by",
"import_path",
"where",
"import_path",
"is",
"the",
"full",
"Python",
"path",
"to",
"the",
"class",
"."
] | python | valid |
Hackerfleet/hfos | hfos/ui/clientmanager.py | https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L825-L834 | def getlanguages(self, event):
"""Compile and return a human readable list of registered translations"""
self.log('Client requests all languages.', lvl=verbose)
result = {
'component': 'hfos.ui.clientmanager',
'action': 'getlanguages',
'data': language_token_to_name(all_languages())
}
self.fireEvent(send(event.client.uuid, result)) | [
"def",
"getlanguages",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"log",
"(",
"'Client requests all languages.'",
",",
"lvl",
"=",
"verbose",
")",
"result",
"=",
"{",
"'component'",
":",
"'hfos.ui.clientmanager'",
",",
"'action'",
":",
"'getlanguages'",
... | Compile and return a human readable list of registered translations | [
"Compile",
"and",
"return",
"a",
"human",
"readable",
"list",
"of",
"registered",
"translations"
] | python | train |
tansey/gfl | pygfl/trails.py | https://github.com/tansey/gfl/blob/ae0f078bab57aba9e827ed6162f247ff9dc2aa19/pygfl/trails.py#L50-L79 | def calc_euler_tour(g, start, end):
'''Calculates an Euler tour over the graph g from vertex start to vertex end.
Assumes start and end are odd-degree vertices and that there are no other odd-degree
vertices.'''
even_g = nx.subgraph(g, g.nodes()).copy()
if end in even_g.neighbors(start):
# If start and end are neighbors, remove the edge
even_g.remove_edge(start, end)
comps = list(nx.connected_components(even_g))
# If the graph did not split, just find the euler circuit
if len(comps) == 1:
trail = list(nx.eulerian_circuit(even_g, start))
trail.append((start, end))
elif len(comps) == 2:
subg1 = nx.subgraph(even_g, comps[0])
subg2 = nx.subgraph(even_g, comps[1])
start_subg, end_subg = (subg1, subg2) if start in subg1.nodes() else (subg2, subg1)
trail = list(nx.eulerian_circuit(start_subg, start)) + [(start, end)] + list(nx.eulerian_circuit(end_subg, end))
else:
raise Exception('Unknown edge case with connected components of size {0}:\n{1}'.format(len(comps), comps))
else:
# If they are not neighbors, we add an imaginary edge and calculate the euler circuit
even_g.add_edge(start, end)
circ = list(nx.eulerian_circuit(even_g, start))
try:
trail_start = circ.index((start, end))
except:
trail_start = circ.index((end, start))
trail = circ[trail_start+1:] + circ[:trail_start]
return trail | [
"def",
"calc_euler_tour",
"(",
"g",
",",
"start",
",",
"end",
")",
":",
"even_g",
"=",
"nx",
".",
"subgraph",
"(",
"g",
",",
"g",
".",
"nodes",
"(",
")",
")",
".",
"copy",
"(",
")",
"if",
"end",
"in",
"even_g",
".",
"neighbors",
"(",
"start",
"... | Calculates an Euler tour over the graph g from vertex start to vertex end.
Assumes start and end are odd-degree vertices and that there are no other odd-degree
vertices. | [
"Calculates",
"an",
"Euler",
"tour",
"over",
"the",
"graph",
"g",
"from",
"vertex",
"start",
"to",
"vertex",
"end",
".",
"Assumes",
"start",
"and",
"end",
"are",
"odd",
"-",
"degree",
"vertices",
"and",
"that",
"there",
"are",
"no",
"other",
"odd",
"-",
... | python | train |
PatrikValkovic/grammpy | grammpy/transforms/UnitRulesRemove/remove_unit_rules.py | https://github.com/PatrikValkovic/grammpy/blob/879ce0ef794ac2823acc19314fcd7a8aba53e50f/grammpy/transforms/UnitRulesRemove/remove_unit_rules.py#L31-L45 | def _create_rule(path, rule):
# type: (List[Type[Rule]], Type[Rule]) -> Type[ReducedUnitRule]
"""
Create ReducedUnitRule based on sequence of unit rules and end, generating rule.
:param path: Sequence of unit rules.
:param rule: Rule that is attached after sequence of unit rules.
:return: ReducedUnitRule class.
"""
created = type('Reduced[' + rule.__name__ + ']',
(ReducedUnitRule,),
ReducedUnitRule.__dict__.copy()) # type: Type[ReducedUnitRule]
created.rule = ([path[0].fromSymbol], rule.right)
created.end_rule = rule
created.by_rules = path
return created | [
"def",
"_create_rule",
"(",
"path",
",",
"rule",
")",
":",
"# type: (List[Type[Rule]], Type[Rule]) -> Type[ReducedUnitRule]",
"created",
"=",
"type",
"(",
"'Reduced['",
"+",
"rule",
".",
"__name__",
"+",
"']'",
",",
"(",
"ReducedUnitRule",
",",
")",
",",
"ReducedU... | Create ReducedUnitRule based on sequence of unit rules and end, generating rule.
:param path: Sequence of unit rules.
:param rule: Rule that is attached after sequence of unit rules.
:return: ReducedUnitRule class. | [
"Create",
"ReducedUnitRule",
"based",
"on",
"sequence",
"of",
"unit",
"rules",
"and",
"end",
"generating",
"rule",
".",
":",
"param",
"path",
":",
"Sequence",
"of",
"unit",
"rules",
".",
":",
"param",
"rule",
":",
"Rule",
"that",
"is",
"attached",
"after",... | python | train |
trailofbits/manticore | manticore/core/smtlib/solver.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L294-L315 | def _is_sat(self) -> bool:
"""
Check the satisfiability of the current state
:return: whether current state is satisfiable or not.
"""
logger.debug("Solver.check() ")
start = time.time()
self._send('(check-sat)')
status = self._recv()
logger.debug("Check took %s seconds (%s)", time.time() - start, status)
if status not in ('sat', 'unsat', 'unknown'):
raise SolverError(status)
if consider_unknown_as_unsat:
if status == 'unknown':
logger.info('Found an unknown core, probably a solver timeout')
status = 'unsat'
if status == 'unknown':
raise SolverUnknown(status)
return status == 'sat' | [
"def",
"_is_sat",
"(",
"self",
")",
"->",
"bool",
":",
"logger",
".",
"debug",
"(",
"\"Solver.check() \"",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_send",
"(",
"'(check-sat)'",
")",
"status",
"=",
"self",
".",
"_recv",
"(",
")... | Check the satisfiability of the current state
:return: whether current state is satisfiable or not. | [
"Check",
"the",
"satisfiability",
"of",
"the",
"current",
"state"
] | python | valid |
readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L212-L221 | def nonspeech_fragments(self):
"""
Iterates through the nonspeech fragments in the list
(which are sorted).
:rtype: generator of (int, :class:`~aeneas.syncmap.SyncMapFragment`)
"""
for i, fragment in enumerate(self.__fragments):
if fragment.fragment_type == SyncMapFragment.NONSPEECH:
yield (i, fragment) | [
"def",
"nonspeech_fragments",
"(",
"self",
")",
":",
"for",
"i",
",",
"fragment",
"in",
"enumerate",
"(",
"self",
".",
"__fragments",
")",
":",
"if",
"fragment",
".",
"fragment_type",
"==",
"SyncMapFragment",
".",
"NONSPEECH",
":",
"yield",
"(",
"i",
",",
... | Iterates through the nonspeech fragments in the list
(which are sorted).
:rtype: generator of (int, :class:`~aeneas.syncmap.SyncMapFragment`) | [
"Iterates",
"through",
"the",
"nonspeech",
"fragments",
"in",
"the",
"list",
"(",
"which",
"are",
"sorted",
")",
"."
] | python | train |
kxgames/vecrec | vecrec/shapes.py | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L468-L472 | def get_rotated(self, angle):
""" Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """
result = self.copy()
result.rotate(angle)
return result | [
"def",
"get_rotated",
"(",
"self",
",",
"angle",
")",
":",
"result",
"=",
"self",
".",
"copy",
"(",
")",
"result",
".",
"rotate",
"(",
"angle",
")",
"return",
"result"
] | Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. | [
"Return",
"a",
"vector",
"rotated",
"by",
"angle",
"from",
"the",
"given",
"vector",
".",
"Angle",
"measured",
"in",
"radians",
"counter",
"-",
"clockwise",
"."
] | python | train |
pycontribs/pyrax | pyrax/cloudmonitoring.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudmonitoring.py#L42-L52 | def assure_check(fnc):
"""
Converts an checkID passed as the check to a CloudMonitorCheck object.
"""
@wraps(fnc)
def _wrapped(self, check, *args, **kwargs):
if not isinstance(check, CloudMonitorCheck):
# Must be the ID
check = self._check_manager.get(check)
return fnc(self, check, *args, **kwargs)
return _wrapped | [
"def",
"assure_check",
"(",
"fnc",
")",
":",
"@",
"wraps",
"(",
"fnc",
")",
"def",
"_wrapped",
"(",
"self",
",",
"check",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"check",
",",
"CloudMonitorCheck",
")",
"... | Converts an checkID passed as the check to a CloudMonitorCheck object. | [
"Converts",
"an",
"checkID",
"passed",
"as",
"the",
"check",
"to",
"a",
"CloudMonitorCheck",
"object",
"."
] | python | train |
NiklasRosenstein-Python/nr-deprecated | nr/stream.py | https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/stream.py#L136-L141 | def of_type(cls, iterable, types):
"""
Filters using #isinstance().
"""
return cls(x for x in iterable if isinstance(x, types)) | [
"def",
"of_type",
"(",
"cls",
",",
"iterable",
",",
"types",
")",
":",
"return",
"cls",
"(",
"x",
"for",
"x",
"in",
"iterable",
"if",
"isinstance",
"(",
"x",
",",
"types",
")",
")"
] | Filters using #isinstance(). | [
"Filters",
"using",
"#isinstance",
"()",
"."
] | python | train |
tcpcloud/python-aptly | aptly/publisher/__init__.py | https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L603-L612 | def _find_snapshot(self, name):
"""
Find snapshot on remote by name or regular expression
"""
remote_snapshots = self._get_snapshots(self.client)
for remote in reversed(remote_snapshots):
if remote["Name"] == name or \
re.match(name, remote["Name"]):
return remote
return None | [
"def",
"_find_snapshot",
"(",
"self",
",",
"name",
")",
":",
"remote_snapshots",
"=",
"self",
".",
"_get_snapshots",
"(",
"self",
".",
"client",
")",
"for",
"remote",
"in",
"reversed",
"(",
"remote_snapshots",
")",
":",
"if",
"remote",
"[",
"\"Name\"",
"]"... | Find snapshot on remote by name or regular expression | [
"Find",
"snapshot",
"on",
"remote",
"by",
"name",
"or",
"regular",
"expression"
] | python | train |
Microsoft/nni | src/sdk/pynni/nni/metis_tuner/metis_tuner.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/metis_tuner.py#L167-L181 | def _pack_output(self, init_parameter):
"""Pack the output
Parameters
----------
init_parameter : dict
Returns
-------
output : dict
"""
output = {}
for i, param in enumerate(init_parameter):
output[self.key_order[i]] = param
return output | [
"def",
"_pack_output",
"(",
"self",
",",
"init_parameter",
")",
":",
"output",
"=",
"{",
"}",
"for",
"i",
",",
"param",
"in",
"enumerate",
"(",
"init_parameter",
")",
":",
"output",
"[",
"self",
".",
"key_order",
"[",
"i",
"]",
"]",
"=",
"param",
"re... | Pack the output
Parameters
----------
init_parameter : dict
Returns
-------
output : dict | [
"Pack",
"the",
"output"
] | python | train |
FNNDSC/pfurl | pfurl/pfurl.py | https://github.com/FNNDSC/pfurl/blob/572f634ab582b7b7b7a3fbfd5bf12aadc1ba7958/pfurl/pfurl.py#L1350-L1373 | def zipdir(path, ziph, **kwargs):
"""
Zip up a directory.
:param path:
:param ziph:
:param kwargs:
:return:
"""
str_arcroot = ""
for k, v in kwargs.items():
if k == 'arcroot': str_arcroot = v
for root, dirs, files in os.walk(path):
for file in files:
str_arcfile = os.path.join(root, file)
if len(str_arcroot):
str_arcname = str_arcroot.split('/')[-1] + str_arcfile.split(str_arcroot)[1]
else:
str_arcname = str_arcfile
try:
ziph.write(str_arcfile, arcname = str_arcname)
except:
print("Skipping %s" % str_arcfile) | [
"def",
"zipdir",
"(",
"path",
",",
"ziph",
",",
"*",
"*",
"kwargs",
")",
":",
"str_arcroot",
"=",
"\"\"",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'arcroot'",
":",
"str_arcroot",
"=",
"v",
"for",
"root"... | Zip up a directory.
:param path:
:param ziph:
:param kwargs:
:return: | [
"Zip",
"up",
"a",
"directory",
"."
] | python | train |
jayvdb/flake8-putty | flake8_putty/extension.py | https://github.com/jayvdb/flake8-putty/blob/854b2c6daef409974c2f5e9c5acaf0a069b0ff23/flake8_putty/extension.py#L137-L157 | def parse_options(cls, options):
"""Parse options and activate `ignore_code` handler."""
if (not options.putty_select and not options.putty_ignore and
not options.putty_auto_ignore):
return
options._orig_select = options.select
options._orig_ignore = options.ignore
options.putty_select = Parser(options.putty_select)._rules
options.putty_ignore = Parser(options.putty_ignore)._rules
if options.putty_auto_ignore:
options.putty_ignore.append(AutoLineDisableRule())
options.ignore_code = functools.partial(
putty_ignore_code,
options,
)
options.report._ignore_code = options.ignore_code | [
"def",
"parse_options",
"(",
"cls",
",",
"options",
")",
":",
"if",
"(",
"not",
"options",
".",
"putty_select",
"and",
"not",
"options",
".",
"putty_ignore",
"and",
"not",
"options",
".",
"putty_auto_ignore",
")",
":",
"return",
"options",
".",
"_orig_select... | Parse options and activate `ignore_code` handler. | [
"Parse",
"options",
"and",
"activate",
"ignore_code",
"handler",
"."
] | python | train |
rootpy/rootpy | rootpy/plotting/contrib/plot_corrcoef_matrix.py | https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/contrib/plot_corrcoef_matrix.py#L13-L133 | def plot_corrcoef_matrix(matrix, names=None,
cmap=None, cmap_text=None,
fontsize=12, grid=False,
axes=None):
"""
This function will draw a lower-triangular correlation matrix
Parameters
----------
matrix : 2-dimensional numpy array/matrix
A correlation coefficient matrix
names : list of strings, optional (default=None)
List of the parameter names corresponding to the rows in ``matrix``.
cmap : matplotlib color map, optional (default=None)
Color map used to color the matrix cells.
cmap_text : matplotlib color map, optional (default=None)
Color map used to color the cell value text. If None, then
all values will be black.
fontsize : int, optional (default=12)
Font size of parameter name and correlation value text.
grid : bool, optional (default=False)
If True, then draw dashed grid lines around the matrix elements.
axes : matplotlib Axes instance, optional (default=None)
The axes to plot on. If None then use the global current axes.
Notes
-----
NumPy and matplotlib are required
Examples
--------
>>> matrix = corrcoef(data.T, weights=weights)
>>> plot_corrcoef_matrix(matrix, names)
"""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm
if axes is None:
axes = plt.gca()
matrix = np.asarray(matrix)
if matrix.ndim != 2:
raise ValueError("matrix is not a 2-dimensional array or matrix")
if matrix.shape[0] != matrix.shape[1]:
raise ValueError("matrix is not square")
if names is not None and len(names) != matrix.shape[0]:
raise ValueError("the number of names does not match the number of "
"rows/columns in the matrix")
# mask out the upper triangular matrix
matrix[np.triu_indices(matrix.shape[0])] = np.nan
if isinstance(cmap_text, string_types):
cmap_text = cm.get_cmap(cmap_text, 201)
if cmap is None:
cmap = cm.get_cmap('jet', 201)
elif isinstance(cmap, string_types):
cmap = cm.get_cmap(cmap, 201)
# make NaN pixels white
cmap.set_bad('w')
axes.imshow(matrix, interpolation='nearest',
cmap=cmap, origin='upper',
vmin=-1, vmax=1)
axes.set_frame_on(False)
plt.setp(axes.get_yticklabels(), visible=False)
plt.setp(axes.get_yticklines(), visible=False)
plt.setp(axes.get_xticklabels(), visible=False)
plt.setp(axes.get_xticklines(), visible=False)
if grid:
# draw grid lines
for slot in range(1, matrix.shape[0] - 1):
# vertical
axes.plot((slot - 0.5, slot - 0.5),
(slot - 0.5, matrix.shape[0] - 0.5), 'k:', linewidth=1)
# horizontal
axes.plot((-0.5, slot + 0.5),
(slot + 0.5, slot + 0.5), 'k:', linewidth=1)
if names is not None:
for slot in range(1, matrix.shape[0]):
# diagonal
axes.plot((slot - 0.5, slot + 1.5),
(slot - 0.5, slot - 2.5), 'k:', linewidth=1)
# label cell values
for row, col in zip(*np.tril_indices(matrix.shape[0], k=-1)):
value = matrix[row][col]
if cmap_text is not None:
color = cmap_text((value + 1.) / 2.)
else:
color = 'black'
axes.text(
col, row,
"{0:d}%".format(int(value * 100)),
color=color,
ha='center', va='center',
fontsize=fontsize)
if names is not None:
# write parameter names
for i, name in enumerate(names):
axes.annotate(
name, (i, i),
rotation=45,
ha='left', va='bottom',
transform=axes.transData,
fontsize=fontsize) | [
"def",
"plot_corrcoef_matrix",
"(",
"matrix",
",",
"names",
"=",
"None",
",",
"cmap",
"=",
"None",
",",
"cmap_text",
"=",
"None",
",",
"fontsize",
"=",
"12",
",",
"grid",
"=",
"False",
",",
"axes",
"=",
"None",
")",
":",
"import",
"numpy",
"as",
"np"... | This function will draw a lower-triangular correlation matrix
Parameters
----------
matrix : 2-dimensional numpy array/matrix
A correlation coefficient matrix
names : list of strings, optional (default=None)
List of the parameter names corresponding to the rows in ``matrix``.
cmap : matplotlib color map, optional (default=None)
Color map used to color the matrix cells.
cmap_text : matplotlib color map, optional (default=None)
Color map used to color the cell value text. If None, then
all values will be black.
fontsize : int, optional (default=12)
Font size of parameter name and correlation value text.
grid : bool, optional (default=False)
If True, then draw dashed grid lines around the matrix elements.
axes : matplotlib Axes instance, optional (default=None)
The axes to plot on. If None then use the global current axes.
Notes
-----
NumPy and matplotlib are required
Examples
--------
>>> matrix = corrcoef(data.T, weights=weights)
>>> plot_corrcoef_matrix(matrix, names) | [
"This",
"function",
"will",
"draw",
"a",
"lower",
"-",
"triangular",
"correlation",
"matrix"
] | python | train |
ibis-project/ibis | ibis/sql/sqlite/client.py | https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/sql/sqlite/client.py#L113-L129 | def _ibis_sqlite_regex_extract(string, pattern, index):
"""Extract match of regular expression `pattern` from `string` at `index`.
Parameters
----------
string : str
pattern : str
index : int
Returns
-------
result : str or None
"""
result = re.search(pattern, string)
if result is not None and 0 <= index <= (result.lastindex or -1):
return result.group(index)
return None | [
"def",
"_ibis_sqlite_regex_extract",
"(",
"string",
",",
"pattern",
",",
"index",
")",
":",
"result",
"=",
"re",
".",
"search",
"(",
"pattern",
",",
"string",
")",
"if",
"result",
"is",
"not",
"None",
"and",
"0",
"<=",
"index",
"<=",
"(",
"result",
"."... | Extract match of regular expression `pattern` from `string` at `index`.
Parameters
----------
string : str
pattern : str
index : int
Returns
-------
result : str or None | [
"Extract",
"match",
"of",
"regular",
"expression",
"pattern",
"from",
"string",
"at",
"index",
"."
] | python | train |
osrg/ryu | ryu/services/protocols/bgp/peer.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/services/protocols/bgp/peer.py#L826-L844 | def _session_next_hop(self, path):
"""Returns nexthop address relevant to current session
Nexthop used can depend on capabilities of the session. If VPNv6
capability is active and session is on IPv4 connection, we have to use
IPv4 mapped IPv6 address. In other cases we can use connection end
point/local ip address.
"""
route_family = path.route_family
# By default we use BGPS's interface IP with this peer as next_hop.
if self._neigh_conf.next_hop:
next_hop = self._neigh_conf.next_hop
else:
next_hop = self.host_bind_ip
if route_family == RF_IPv6_VPN:
next_hop = self._ipv4_mapped_ipv6(next_hop)
return next_hop | [
"def",
"_session_next_hop",
"(",
"self",
",",
"path",
")",
":",
"route_family",
"=",
"path",
".",
"route_family",
"# By default we use BGPS's interface IP with this peer as next_hop.",
"if",
"self",
".",
"_neigh_conf",
".",
"next_hop",
":",
"next_hop",
"=",
"self",
".... | Returns nexthop address relevant to current session
Nexthop used can depend on capabilities of the session. If VPNv6
capability is active and session is on IPv4 connection, we have to use
IPv4 mapped IPv6 address. In other cases we can use connection end
point/local ip address. | [
"Returns",
"nexthop",
"address",
"relevant",
"to",
"current",
"session"
] | python | train |
owncloud/pyocclient | owncloud/owncloud.py | https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1089-L1109 | def get_user_groups(self, user_name):
"""Get a list of groups associated to a user.
:param user_name: name of user to list groups
:returns: list of groups
:raises: HTTPResponseError in case an HTTP error status was returned
"""
res = self._make_ocs_request(
'GET',
self.OCS_SERVICE_CLOUD,
'users/' + user_name + '/groups',
)
if res.status_code == 200:
tree = ET.fromstring(res.content)
self._check_ocs_status(tree, [100])
return [group.text for group in tree.find('data/groups')]
raise HTTPResponseError(res) | [
"def",
"get_user_groups",
"(",
"self",
",",
"user_name",
")",
":",
"res",
"=",
"self",
".",
"_make_ocs_request",
"(",
"'GET'",
",",
"self",
".",
"OCS_SERVICE_CLOUD",
",",
"'users/'",
"+",
"user_name",
"+",
"'/groups'",
",",
")",
"if",
"res",
".",
"status_c... | Get a list of groups associated to a user.
:param user_name: name of user to list groups
:returns: list of groups
:raises: HTTPResponseError in case an HTTP error status was returned | [
"Get",
"a",
"list",
"of",
"groups",
"associated",
"to",
"a",
"user",
"."
] | python | train |
sourceperl/pyModbusTCP | pyModbusTCP/client.py | https://github.com/sourceperl/pyModbusTCP/blob/993f6e2f5ab52eba164be049e42cea560c3751a5/pyModbusTCP/client.py#L251-L287 | def open(self):
"""Connect to modbus server (open TCP connection)
:returns: connect status (True if open)
:rtype: bool
"""
# restart TCP if already open
if self.is_open():
self.close()
# init socket and connect
# list available sockets on the target host/port
# AF_xxx : AF_INET -> IPv4, AF_INET6 -> IPv6,
# AF_UNSPEC -> IPv6 (priority on some system) or 4
# list available socket on target host
for res in socket.getaddrinfo(self.__hostname, self.__port,
socket.AF_UNSPEC, socket.SOCK_STREAM):
af, sock_type, proto, canon_name, sa = res
try:
self.__sock = socket.socket(af, sock_type, proto)
except socket.error:
self.__sock = None
continue
try:
self.__sock.settimeout(self.__timeout)
self.__sock.connect(sa)
except socket.error:
self.__sock.close()
self.__sock = None
continue
break
# check connect status
if self.__sock is not None:
return True
else:
self.__last_error = const.MB_CONNECT_ERR
self.__debug_msg('connect error')
return False | [
"def",
"open",
"(",
"self",
")",
":",
"# restart TCP if already open",
"if",
"self",
".",
"is_open",
"(",
")",
":",
"self",
".",
"close",
"(",
")",
"# init socket and connect",
"# list available sockets on the target host/port",
"# AF_xxx : AF_INET -> IPv4, AF_INET6 -> IPv6... | Connect to modbus server (open TCP connection)
:returns: connect status (True if open)
:rtype: bool | [
"Connect",
"to",
"modbus",
"server",
"(",
"open",
"TCP",
"connection",
")"
] | python | train |
saltstack/salt | salt/utils/stringutils.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L30-L63 | def to_bytes(s, encoding=None, errors='strict'):
'''
Given bytes, bytearray, str, or unicode (python 2), return bytes (str for
python 2)
'''
if encoding is None:
# Try utf-8 first, and fall back to detected encoding
encoding = ('utf-8', __salt_system_encoding__)
if not isinstance(encoding, (tuple, list)):
encoding = (encoding,)
if not encoding:
raise ValueError('encoding cannot be empty')
exc = None
if six.PY3:
if isinstance(s, bytes):
return s
if isinstance(s, bytearray):
return bytes(s)
if isinstance(s, six.string_types):
for enc in encoding:
try:
return s.encode(enc, errors)
except UnicodeEncodeError as err:
exc = err
continue
# The only way we get this far is if a UnicodeEncodeError was
# raised, otherwise we would have already returned (or raised some
# other exception).
raise exc # pylint: disable=raising-bad-type
raise TypeError('expected bytes, bytearray, or str')
else:
return to_str(s, encoding, errors) | [
"def",
"to_bytes",
"(",
"s",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"# Try utf-8 first, and fall back to detected encoding",
"encoding",
"=",
"(",
"'utf-8'",
",",
"__salt_system_encoding__",
")"... | Given bytes, bytearray, str, or unicode (python 2), return bytes (str for
python 2) | [
"Given",
"bytes",
"bytearray",
"str",
"or",
"unicode",
"(",
"python",
"2",
")",
"return",
"bytes",
"(",
"str",
"for",
"python",
"2",
")"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.