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 |
|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/modules/syslog_ng.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L458-L471 | def _parse_typed_parameter_typed_value(values):
'''
Creates Arguments in a TypedParametervalue.
'''
type_, value = _expand_one_key_dictionary(values)
_current_parameter_value.type = type_
if _is_simple_type(value):
arg = Argument(value)
_current_parameter_value.add_argument(arg)... | [
"def",
"_parse_typed_parameter_typed_value",
"(",
"values",
")",
":",
"type_",
",",
"value",
"=",
"_expand_one_key_dictionary",
"(",
"values",
")",
"_current_parameter_value",
".",
"type",
"=",
"type_",
"if",
"_is_simple_type",
"(",
"value",
")",
":",
"arg",
"=",
... | Creates Arguments in a TypedParametervalue. | [
"Creates",
"Arguments",
"in",
"a",
"TypedParametervalue",
"."
] | python | train |
square/pylink | pylink/jlink.py | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L498-L517 | def supported_device(self, index=0):
"""Gets the device at the given ``index``.
Args:
self (JLink): the ``JLink`` instance
index (int): the index of the device whose information to get
Returns:
A ``JLinkDeviceInfo`` describing the requested device.
Raises... | [
"def",
"supported_device",
"(",
"self",
",",
"index",
"=",
"0",
")",
":",
"if",
"not",
"util",
".",
"is_natural",
"(",
"index",
")",
"or",
"index",
">=",
"self",
".",
"num_supported_devices",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid index.'",
... | Gets the device at the given ``index``.
Args:
self (JLink): the ``JLink`` instance
index (int): the index of the device whose information to get
Returns:
A ``JLinkDeviceInfo`` describing the requested device.
Raises:
ValueError: if index is less than 0 ... | [
"Gets",
"the",
"device",
"at",
"the",
"given",
"index",
"."
] | python | train |
quantopian/serializable-traitlets | straitlets/traits.py | https://github.com/quantopian/serializable-traitlets/blob/dd334366d1130825aea55d3dfecd6756973594e0/straitlets/traits.py#L208-L217 | def example_value(self):
"""
If we're an instance of a Serializable, fall back to its
`example_instance()` method.
"""
from .serializable import Serializable
inst = self._static_example_value()
if inst is tr.Undefined and issubclass(self.klass, Serializable):
... | [
"def",
"example_value",
"(",
"self",
")",
":",
"from",
".",
"serializable",
"import",
"Serializable",
"inst",
"=",
"self",
".",
"_static_example_value",
"(",
")",
"if",
"inst",
"is",
"tr",
".",
"Undefined",
"and",
"issubclass",
"(",
"self",
".",
"klass",
"... | If we're an instance of a Serializable, fall back to its
`example_instance()` method. | [
"If",
"we",
"re",
"an",
"instance",
"of",
"a",
"Serializable",
"fall",
"back",
"to",
"its",
"example_instance",
"()",
"method",
"."
] | python | train |
tornadoweb/tornado | tornado/routing.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L608-L640 | def _find_groups(self) -> Tuple[Optional[str], Optional[int]]:
"""Returns a tuple (reverse string, group count) for a url.
For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method
would return ('/%s/%s/', 2).
"""
pattern = self.regex.pattern
if pattern.star... | [
"def",
"_find_groups",
"(",
"self",
")",
"->",
"Tuple",
"[",
"Optional",
"[",
"str",
"]",
",",
"Optional",
"[",
"int",
"]",
"]",
":",
"pattern",
"=",
"self",
".",
"regex",
".",
"pattern",
"if",
"pattern",
".",
"startswith",
"(",
"\"^\"",
")",
":",
... | Returns a tuple (reverse string, group count) for a url.
For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method
would return ('/%s/%s/', 2). | [
"Returns",
"a",
"tuple",
"(",
"reverse",
"string",
"group",
"count",
")",
"for",
"a",
"url",
"."
] | python | train |
xenon-middleware/pyxenon | xenon/oop.py | https://github.com/xenon-middleware/pyxenon/blob/d61109ad339ee9bb9f0723471d532727b0f235ad/xenon/oop.py#L118-L127 | def request_type(self):
"""Retrieve the type of the request, by fetching it from
`xenon.proto.xenon_pb2`."""
if self.static and not self.uses_request:
return getattr(xenon_pb2, 'Empty')
if not self.uses_request:
return None
return getattr(xenon_pb2, self... | [
"def",
"request_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"static",
"and",
"not",
"self",
".",
"uses_request",
":",
"return",
"getattr",
"(",
"xenon_pb2",
",",
"'Empty'",
")",
"if",
"not",
"self",
".",
"uses_request",
":",
"return",
"None",
"retur... | Retrieve the type of the request, by fetching it from
`xenon.proto.xenon_pb2`. | [
"Retrieve",
"the",
"type",
"of",
"the",
"request",
"by",
"fetching",
"it",
"from",
"xenon",
".",
"proto",
".",
"xenon_pb2",
"."
] | python | train |
JamesRamm/longclaw | longclaw/orders/wagtail_hooks.py | https://github.com/JamesRamm/longclaw/blob/8bbf2e6d703271b815ec111813c7c5d1d4e4e810/longclaw/orders/wagtail_hooks.py#L111-L122 | def get_admin_urls_for_registration(self):
"""
Utilised by Wagtail's 'register_admin_urls' hook to register urls for
our the views that class offers.
"""
urls = super(OrderModelAdmin, self).get_admin_urls_for_registration()
urls = urls + (
url(self.url_helper.... | [
"def",
"get_admin_urls_for_registration",
"(",
"self",
")",
":",
"urls",
"=",
"super",
"(",
"OrderModelAdmin",
",",
"self",
")",
".",
"get_admin_urls_for_registration",
"(",
")",
"urls",
"=",
"urls",
"+",
"(",
"url",
"(",
"self",
".",
"url_helper",
".",
"get... | Utilised by Wagtail's 'register_admin_urls' hook to register urls for
our the views that class offers. | [
"Utilised",
"by",
"Wagtail",
"s",
"register_admin_urls",
"hook",
"to",
"register",
"urls",
"for",
"our",
"the",
"views",
"that",
"class",
"offers",
"."
] | python | train |
philgyford/django-spectator | spectator/events/templatetags/spectator_events.py | https://github.com/philgyford/django-spectator/blob/f3c72004f9caa1fde0f5a3b2f0d2bf285fc01ada/spectator/events/templatetags/spectator_events.py#L40-L58 | def annual_event_counts_card(kind='all', current_year=None):
"""
Displays years and the number of events per year.
kind is an Event kind (like 'cinema', 'gig', etc.) or 'all' (default).
current_year is an optional date object representing the year we're already
showing information about.
""... | [
"def",
"annual_event_counts_card",
"(",
"kind",
"=",
"'all'",
",",
"current_year",
"=",
"None",
")",
":",
"if",
"kind",
"==",
"'all'",
":",
"card_title",
"=",
"'Events per year'",
"else",
":",
"card_title",
"=",
"'{} per year'",
".",
"format",
"(",
"Event",
... | Displays years and the number of events per year.
kind is an Event kind (like 'cinema', 'gig', etc.) or 'all' (default).
current_year is an optional date object representing the year we're already
showing information about. | [
"Displays",
"years",
"and",
"the",
"number",
"of",
"events",
"per",
"year",
"."
] | python | train |
sdispater/pendulum | pendulum/__init__.py | https://github.com/sdispater/pendulum/blob/94d28b0d3cb524ae02361bd1ed7ea03e2e655e4e/pendulum/__init__.py#L308-L314 | def period(
start, end, absolute=False # type: DateTime # type: DateTime # type: bool
): # type: (...) -> Period
"""
Create a Period instance.
"""
return Period(start, end, absolute=absolute) | [
"def",
"period",
"(",
"start",
",",
"end",
",",
"absolute",
"=",
"False",
"# type: DateTime # type: DateTime # type: bool",
")",
":",
"# type: (...) -> Period",
"return",
"Period",
"(",
"start",
",",
"end",
",",
"absolute",
"=",
"absolute",
")"
] | Create a Period instance. | [
"Create",
"a",
"Period",
"instance",
"."
] | python | train |
xiongchiamiov/pyfixit | pyfixit/step.py | https://github.com/xiongchiamiov/pyfixit/blob/808a0c852a26e4211b2e3a72da972ab34a586dc4/pyfixit/step.py#L38-L51 | def refresh(self):
'''Refetch instance data from the API.
'''
# There's no GET endpoint for steps, so get the parent guide and loop
# through its steps until we find the right one.
response = requests.get('%s/guides/%s' % (API_BASE_URL, self.guideid))
attributes = response.json()
... | [
"def",
"refresh",
"(",
"self",
")",
":",
"# There's no GET endpoint for steps, so get the parent guide and loop",
"# through its steps until we find the right one.",
"response",
"=",
"requests",
".",
"get",
"(",
"'%s/guides/%s'",
"%",
"(",
"API_BASE_URL",
",",
"self",
".",
... | Refetch instance data from the API. | [
"Refetch",
"instance",
"data",
"from",
"the",
"API",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xcalendarwidget/xcalendarscene.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcalendarwidget/xcalendarscene.py#L70-L81 | def addItem( self, item ):
"""
Adds the item to the scene and redraws the item.
:param item | <QGraphicsItem>
"""
result = super(XCalendarScene, self).addItem(item)
if ( isinstance(item, XCalendarItem) ):
item.rebuild()
... | [
"def",
"addItem",
"(",
"self",
",",
"item",
")",
":",
"result",
"=",
"super",
"(",
"XCalendarScene",
",",
"self",
")",
".",
"addItem",
"(",
"item",
")",
"if",
"(",
"isinstance",
"(",
"item",
",",
"XCalendarItem",
")",
")",
":",
"item",
".",
"rebuild"... | Adds the item to the scene and redraws the item.
:param item | <QGraphicsItem> | [
"Adds",
"the",
"item",
"to",
"the",
"scene",
"and",
"redraws",
"the",
"item",
".",
":",
"param",
"item",
"|",
"<QGraphicsItem",
">"
] | python | train |
p3trus/slave | slave/protocol.py | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/protocol.py#L177-L185 | def clear(self, transport):
"""Issues a device clear command."""
logger.debug('IEC60488 clear')
with transport:
try:
transport.clear()
except AttributeError:
clear_msg = self.create_message('*CLS')
transport.write(clear_msg) | [
"def",
"clear",
"(",
"self",
",",
"transport",
")",
":",
"logger",
".",
"debug",
"(",
"'IEC60488 clear'",
")",
"with",
"transport",
":",
"try",
":",
"transport",
".",
"clear",
"(",
")",
"except",
"AttributeError",
":",
"clear_msg",
"=",
"self",
".",
"cre... | Issues a device clear command. | [
"Issues",
"a",
"device",
"clear",
"command",
"."
] | python | train |
wbond/asn1crypto | asn1crypto/core.py | https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L2510-L2523 | def native(self):
"""
The native Python datatype representation of this value
:return:
An integer or None
"""
if self.contents is None:
return None
if self._native is None:
self._native = int_from_bytes(self._merge_chunks())
... | [
"def",
"native",
"(",
"self",
")",
":",
"if",
"self",
".",
"contents",
"is",
"None",
":",
"return",
"None",
"if",
"self",
".",
"_native",
"is",
"None",
":",
"self",
".",
"_native",
"=",
"int_from_bytes",
"(",
"self",
".",
"_merge_chunks",
"(",
")",
"... | The native Python datatype representation of this value
:return:
An integer or None | [
"The",
"native",
"Python",
"datatype",
"representation",
"of",
"this",
"value"
] | python | train |
eventifyio/eventify | eventify/drivers/base.py | https://github.com/eventifyio/eventify/blob/0e519964a56bd07a879b266f21f177749c63aaed/eventify/drivers/base.py#L20-L66 | async def onConnect(self):
"""
Configure the component
"""
# Add extra attribute
# This allows for following crossbar/autobahn spec
# without changing legacy configuration
if not hasattr(self.config, 'extra'):
original_config = {'config': self.config}
... | [
"async",
"def",
"onConnect",
"(",
"self",
")",
":",
"# Add extra attribute",
"# This allows for following crossbar/autobahn spec",
"# without changing legacy configuration",
"if",
"not",
"hasattr",
"(",
"self",
".",
"config",
",",
"'extra'",
")",
":",
"original_config",
"... | Configure the component | [
"Configure",
"the",
"component"
] | python | train |
wummel/patool | patoolib/programs/py_lzma.py | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_lzma.py#L95-L97 | def create_xz(archive, compression, cmd, verbosity, interactive, filenames):
"""Create an XZ archive with the lzma Python module."""
return _create(archive, compression, cmd, 'xz', verbosity, filenames) | [
"def",
"create_xz",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"filenames",
")",
":",
"return",
"_create",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"'xz'",
",",
"verbosity",
",",
"filenames",
")"
... | Create an XZ archive with the lzma Python module. | [
"Create",
"an",
"XZ",
"archive",
"with",
"the",
"lzma",
"Python",
"module",
"."
] | python | train |
ricequant/rqalpha | rqalpha/model/portfolio.py | https://github.com/ricequant/rqalpha/blob/ac40a62d4e7eca9494b4d0a14f46facf5616820c/rqalpha/model/portfolio.py#L190-L194 | def cash(self):
"""
[float] 可用资金
"""
return sum(account.cash for account in six.itervalues(self._accounts)) | [
"def",
"cash",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"account",
".",
"cash",
"for",
"account",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"_accounts",
")",
")"
] | [float] 可用资金 | [
"[",
"float",
"]",
"可用资金"
] | python | train |
ladybug-tools/ladybug | ladybug/rootfind.py | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/rootfind.py#L6-L53 | def secant(a, b, fn, epsilon):
"""
One of the fasest root-finding algorithms.
The method calculates the slope of the function fn and this enables it to converge
to a solution very fast. However, if started too far away from a root, the method
may not converge (returning a None). For this reason,... | [
"def",
"secant",
"(",
"a",
",",
"b",
",",
"fn",
",",
"epsilon",
")",
":",
"f1",
"=",
"fn",
"(",
"a",
")",
"if",
"abs",
"(",
"f1",
")",
"<=",
"epsilon",
":",
"return",
"a",
"f2",
"=",
"fn",
"(",
"b",
")",
"if",
"abs",
"(",
"f2",
")",
"<=",... | One of the fasest root-finding algorithms.
The method calculates the slope of the function fn and this enables it to converge
to a solution very fast. However, if started too far away from a root, the method
may not converge (returning a None). For this reason, it is recommended that this
function b... | [
"One",
"of",
"the",
"fasest",
"root",
"-",
"finding",
"algorithms",
".",
"The",
"method",
"calculates",
"the",
"slope",
"of",
"the",
"function",
"fn",
"and",
"this",
"enables",
"it",
"to",
"converge",
"to",
"a",
"solution",
"very",
"fast",
".",
"However",
... | python | train |
gem/oq-engine | openquake/hazardlib/gsim/cauzzi_2014.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_2014.py#L89-L103 | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extract dictionaries of coefficients specific to required
# ... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"# extract dictionaries of coefficients specific to required",
"# intensity measure type",
"C",
"=",
"self",
".",
"COEFFS",
"[",
"imt",
"]"... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. | [
"See",
":",
"meth",
":",
"superclass",
"method",
"<",
".",
"base",
".",
"GroundShakingIntensityModel",
".",
"get_mean_and_stddevs",
">",
"for",
"spec",
"of",
"input",
"and",
"result",
"values",
"."
] | python | train |
CI-WATER/gsshapy | gsshapy/orm/prj.py | https://github.com/CI-WATER/gsshapy/blob/00fd4af0fd65f1614d75a52fe950a04fb0867f4c/gsshapy/orm/prj.py#L464-L509 | def readOutput(self, directory, projectFileName, session, spatial=False, spatialReferenceID=None):
"""
Read only output files for a GSSHA project to the database.
Use this method to read a project when only post-processing tasks need to be performed.
Args:
directory (str): ... | [
"def",
"readOutput",
"(",
"self",
",",
"directory",
",",
"projectFileName",
",",
"session",
",",
"spatial",
"=",
"False",
",",
"spatialReferenceID",
"=",
"None",
")",
":",
"self",
".",
"project_directory",
"=",
"directory",
"with",
"tmp_chdir",
"(",
"directory... | Read only output files for a GSSHA project to the database.
Use this method to read a project when only post-processing tasks need to be performed.
Args:
directory (str): Directory containing all GSSHA model files. This method assumes that all files are located
in the same ... | [
"Read",
"only",
"output",
"files",
"for",
"a",
"GSSHA",
"project",
"to",
"the",
"database",
"."
] | python | train |
tensorlayer/tensorlayer | tensorlayer/layers/core.py | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/layers/core.py#L258-L286 | def _get_init_args(self, skip=4):
"""Get all arguments of current layer for saving the graph."""
stack = inspect.stack()
if len(stack) < skip + 1:
raise ValueError("The length of the inspection stack is shorter than the requested start position.")
args, _, _, values = inspe... | [
"def",
"_get_init_args",
"(",
"self",
",",
"skip",
"=",
"4",
")",
":",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"if",
"len",
"(",
"stack",
")",
"<",
"skip",
"+",
"1",
":",
"raise",
"ValueError",
"(",
"\"The length of the inspection stack is shorter... | Get all arguments of current layer for saving the graph. | [
"Get",
"all",
"arguments",
"of",
"current",
"layer",
"for",
"saving",
"the",
"graph",
"."
] | python | valid |
googleapis/google-cloud-python | bigquery/google/cloud/bigquery/schema.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/schema.py#L132-L147 | def _key(self):
"""A tuple key that uniquely describes this field.
Used to compute this instance's hashcode and evaluate equality.
Returns:
tuple: The contents of this
:class:`~google.cloud.bigquery.schema.SchemaField`.
"""
return (
se... | [
"def",
"_key",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_name",
",",
"self",
".",
"_field_type",
".",
"upper",
"(",
")",
",",
"self",
".",
"_mode",
".",
"upper",
"(",
")",
",",
"self",
".",
"_description",
",",
"self",
".",
"_fields",
... | A tuple key that uniquely describes this field.
Used to compute this instance's hashcode and evaluate equality.
Returns:
tuple: The contents of this
:class:`~google.cloud.bigquery.schema.SchemaField`. | [
"A",
"tuple",
"key",
"that",
"uniquely",
"describes",
"this",
"field",
"."
] | python | train |
wummel/linkchecker | linkcheck/logconf.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/logconf.py#L67-L72 | def add_loghandler (handler):
"""Add log handler to root logger and LOG_ROOT and set formatting."""
format = "%(levelname)s %(name)s %(asctime)s %(threadName)s %(message)s"
handler.setFormatter(logging.Formatter(format))
logging.getLogger(LOG_ROOT).addHandler(handler)
logging.getLogger().addHandler(... | [
"def",
"add_loghandler",
"(",
"handler",
")",
":",
"format",
"=",
"\"%(levelname)s %(name)s %(asctime)s %(threadName)s %(message)s\"",
"handler",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"format",
")",
")",
"logging",
".",
"getLogger",
"(",
"LOG_ROO... | Add log handler to root logger and LOG_ROOT and set formatting. | [
"Add",
"log",
"handler",
"to",
"root",
"logger",
"and",
"LOG_ROOT",
"and",
"set",
"formatting",
"."
] | python | train |
modlinltd/django-advanced-filters | advanced_filters/q_serializer.py | https://github.com/modlinltd/django-advanced-filters/blob/ba51e6946d1652796a82b2b95cceffbe1190a227/advanced_filters/q_serializer.py#L87-L117 | def get_field_values_list(self, d):
"""
Iterate over a (possibly nested) dict, and return a list
of all children queries, as a dict of the following structure:
{
'field': 'some_field__iexact',
'value': 'some_value',
'value_from': 'optional_range_val1',... | [
"def",
"get_field_values_list",
"(",
"self",
",",
"d",
")",
":",
"fields",
"=",
"[",
"]",
"children",
"=",
"d",
".",
"get",
"(",
"'children'",
",",
"[",
"]",
")",
"for",
"child",
"in",
"children",
":",
"if",
"isinstance",
"(",
"child",
",",
"dict",
... | Iterate over a (possibly nested) dict, and return a list
of all children queries, as a dict of the following structure:
{
'field': 'some_field__iexact',
'value': 'some_value',
'value_from': 'optional_range_val1',
'value_to': 'optional_range_val2',
... | [
"Iterate",
"over",
"a",
"(",
"possibly",
"nested",
")",
"dict",
"and",
"return",
"a",
"list",
"of",
"all",
"children",
"queries",
"as",
"a",
"dict",
"of",
"the",
"following",
"structure",
":",
"{",
"field",
":",
"some_field__iexact",
"value",
":",
"some_va... | python | train |
rwl/pylon | pyreto/util.py | https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pyreto/util.py#L129-L147 | def plotGenCost(generators):
""" Plots the costs of the given generators.
"""
figure()
plots = []
for generator in generators:
if generator.pcost_model == PW_LINEAR:
x = [x for x, _ in generator.p_cost]
y = [y for _, y in generator.p_cost]
elif generator.pcost... | [
"def",
"plotGenCost",
"(",
"generators",
")",
":",
"figure",
"(",
")",
"plots",
"=",
"[",
"]",
"for",
"generator",
"in",
"generators",
":",
"if",
"generator",
".",
"pcost_model",
"==",
"PW_LINEAR",
":",
"x",
"=",
"[",
"x",
"for",
"x",
",",
"_",
"in",... | Plots the costs of the given generators. | [
"Plots",
"the",
"costs",
"of",
"the",
"given",
"generators",
"."
] | python | train |
tradenity/python-sdk | tradenity/resources/customer.py | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/customer.py#L627-L647 | def get_customer_by_id(cls, customer_id, **kwargs):
"""Find Customer
Return single instance of Customer by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_customer_by_id(customer_i... | [
"def",
"get_customer_by_id",
"(",
"cls",
",",
"customer_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_get_customer_by_id_with... | Find Customer
Return single instance of Customer by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_customer_by_id(customer_id, async=True)
>>> result = thread.get()
:para... | [
"Find",
"Customer"
] | python | train |
clalancette/pycdlib | pycdlib/dates.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/dates.py#L220-L260 | def new(self, tm=0.0):
# type: (float) -> None
'''
Create a new Volume Descriptor Date. If tm is None, then this Volume
Descriptor Date will be full of zeros (meaning not specified). If tm
is not None, it is expected to be a struct_time object, at which point
this Volum... | [
"def",
"new",
"(",
"self",
",",
"tm",
"=",
"0.0",
")",
":",
"# type: (float) -> None",
"if",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'This Volume Descriptor Date object is already initialized'",
")",
"if",
"tm"... | Create a new Volume Descriptor Date. If tm is None, then this Volume
Descriptor Date will be full of zeros (meaning not specified). If tm
is not None, it is expected to be a struct_time object, at which point
this Volume Descriptor Date object will be filled in with data from that
stru... | [
"Create",
"a",
"new",
"Volume",
"Descriptor",
"Date",
".",
"If",
"tm",
"is",
"None",
"then",
"this",
"Volume",
"Descriptor",
"Date",
"will",
"be",
"full",
"of",
"zeros",
"(",
"meaning",
"not",
"specified",
")",
".",
"If",
"tm",
"is",
"not",
"None",
"it... | python | train |
jaysonsantos/python-binary-memcached | bmemcached/protocol.py | https://github.com/jaysonsantos/python-binary-memcached/blob/6a792829349c69204d9c5045e5c34b4231216dd6/bmemcached/protocol.py#L472-L538 | def get_multi(self, keys):
"""
Get multiple keys from server.
Since keys are converted to b'' when six.PY3 the keys need to be decoded back
into string . e.g key='test' is read as b'test' and then decoded back to 'test'
This encode/decode does not work when key is already a six.... | [
"def",
"get_multi",
"(",
"self",
",",
"keys",
")",
":",
"# pipeline N-1 getkq requests, followed by a regular getk to uncork the",
"# server",
"o_keys",
"=",
"keys",
"keys",
",",
"last",
"=",
"keys",
"[",
":",
"-",
"1",
"]",
",",
"str_to_bytes",
"(",
"keys",
"["... | Get multiple keys from server.
Since keys are converted to b'' when six.PY3 the keys need to be decoded back
into string . e.g key='test' is read as b'test' and then decoded back to 'test'
This encode/decode does not work when key is already a six.binary_type hence
this function remembe... | [
"Get",
"multiple",
"keys",
"from",
"server",
"."
] | python | train |
datadesk/slackdown | slackdown/__init__.py | https://github.com/datadesk/slackdown/blob/2c5c2faf2673d0d58183f590f234d2c7e1fe8508/slackdown/__init__.py#L297-L313 | def clean(self):
"""
Goes through the txt input and cleans up any problematic HTML.
"""
# Calls handle_starttag, handle_endtag, and handle_data
self.feed()
# Clean up any parent tags left open
if self.current_parent_element['tag'] != '':
self.cleaned_... | [
"def",
"clean",
"(",
"self",
")",
":",
"# Calls handle_starttag, handle_endtag, and handle_data",
"self",
".",
"feed",
"(",
")",
"# Clean up any parent tags left open",
"if",
"self",
".",
"current_parent_element",
"[",
"'tag'",
"]",
"!=",
"''",
":",
"self",
".",
"cl... | Goes through the txt input and cleans up any problematic HTML. | [
"Goes",
"through",
"the",
"txt",
"input",
"and",
"cleans",
"up",
"any",
"problematic",
"HTML",
"."
] | python | train |
PMEAL/OpenPNM | openpnm/models/phases/thermal_conductivity.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/models/phases/thermal_conductivity.py#L4-L54 | def water(target, temperature='pore.temperature', salinity='pore.salinity'):
r"""
Calculates thermal conductivity of pure water or seawater at atmospheric
pressure using the correlation given by Jamieson and Tudhope. Values at
temperature higher the normal boiling temperature are calculated at the
... | [
"def",
"water",
"(",
"target",
",",
"temperature",
"=",
"'pore.temperature'",
",",
"salinity",
"=",
"'pore.salinity'",
")",
":",
"T",
"=",
"target",
"[",
"temperature",
"]",
"if",
"salinity",
"in",
"target",
".",
"keys",
"(",
")",
":",
"S",
"=",
"target"... | r"""
Calculates thermal conductivity of pure water or seawater at atmospheric
pressure using the correlation given by Jamieson and Tudhope. Values at
temperature higher the normal boiling temperature are calculated at the
saturation pressure.
Parameters
----------
target : OpenPNM Object
... | [
"r",
"Calculates",
"thermal",
"conductivity",
"of",
"pure",
"water",
"or",
"seawater",
"at",
"atmospheric",
"pressure",
"using",
"the",
"correlation",
"given",
"by",
"Jamieson",
"and",
"Tudhope",
".",
"Values",
"at",
"temperature",
"higher",
"the",
"normal",
"bo... | python | train |
LogicalDash/LiSE | allegedb/allegedb/graph.py | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/graph.py#L65-L75 | def disconnect(self, func):
"""No longer call the function when something changes here."""
if id(self) not in _alleged_receivers:
return
l = _alleged_receivers[id(self)]
try:
l.remove(func)
except ValueError:
return
if not l:
... | [
"def",
"disconnect",
"(",
"self",
",",
"func",
")",
":",
"if",
"id",
"(",
"self",
")",
"not",
"in",
"_alleged_receivers",
":",
"return",
"l",
"=",
"_alleged_receivers",
"[",
"id",
"(",
"self",
")",
"]",
"try",
":",
"l",
".",
"remove",
"(",
"func",
... | No longer call the function when something changes here. | [
"No",
"longer",
"call",
"the",
"function",
"when",
"something",
"changes",
"here",
"."
] | python | train |
marshallward/f90nml | f90nml/tokenizer.py | https://github.com/marshallward/f90nml/blob/4932cabc5221afc844ee6a5b4a05ceb8bd4a2711/f90nml/tokenizer.py#L186-L190 | def update_chars(self):
"""Update the current charters in the tokenizer."""
# NOTE: We spoof non-Unix files by returning '\n' on StopIteration
self.prior_char, self.char = self.char, next(self.characters, '\n')
self.idx += 1 | [
"def",
"update_chars",
"(",
"self",
")",
":",
"# NOTE: We spoof non-Unix files by returning '\\n' on StopIteration",
"self",
".",
"prior_char",
",",
"self",
".",
"char",
"=",
"self",
".",
"char",
",",
"next",
"(",
"self",
".",
"characters",
",",
"'\\n'",
")",
"s... | Update the current charters in the tokenizer. | [
"Update",
"the",
"current",
"charters",
"in",
"the",
"tokenizer",
"."
] | python | train |
chaoss/grimoirelab-manuscripts | manuscripts2/metrics/git.py | https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts2/metrics/git.py#L145-L166 | def overview(index, start, end):
"""Compute metrics in the overview section for enriched git indexes.
Returns a dictionary. Each key in the dictionary is the name of
a metric, the value is the value of that metric. Value can be
a complex object (eg, a time series).
:param index: index object
:... | [
"def",
"overview",
"(",
"index",
",",
"start",
",",
"end",
")",
":",
"results",
"=",
"{",
"\"activity_metrics\"",
":",
"[",
"Commits",
"(",
"index",
",",
"start",
",",
"end",
")",
"]",
",",
"\"author_metrics\"",
":",
"[",
"Authors",
"(",
"index",
",",
... | Compute metrics in the overview section for enriched git indexes.
Returns a dictionary. Each key in the dictionary is the name of
a metric, the value is the value of that metric. Value can be
a complex object (eg, a time series).
:param index: index object
:param start: start date to get the data ... | [
"Compute",
"metrics",
"in",
"the",
"overview",
"section",
"for",
"enriched",
"git",
"indexes",
"."
] | python | train |
smarie/python-valid8 | valid8/base.py | https://github.com/smarie/python-valid8/blob/5e15d1de11602933c5114eb9f73277ad91d97800/valid8/base.py#L406-L410 | def get_context_for_help_msgs(self, context_dict):
""" We override this method from HelpMsgMixIn to replace wrapped_func with its name """
context_dict = copy(context_dict)
context_dict['wrapped_func'] = get_callable_name(context_dict['wrapped_func'])
return context_dict | [
"def",
"get_context_for_help_msgs",
"(",
"self",
",",
"context_dict",
")",
":",
"context_dict",
"=",
"copy",
"(",
"context_dict",
")",
"context_dict",
"[",
"'wrapped_func'",
"]",
"=",
"get_callable_name",
"(",
"context_dict",
"[",
"'wrapped_func'",
"]",
")",
"retu... | We override this method from HelpMsgMixIn to replace wrapped_func with its name | [
"We",
"override",
"this",
"method",
"from",
"HelpMsgMixIn",
"to",
"replace",
"wrapped_func",
"with",
"its",
"name"
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/external/decorators/_decorators.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/external/decorators/_decorators.py#L99-L173 | def skipif(skip_condition, msg=None):
"""
Make function raise SkipTest exception if a given condition is true.
If the condition is a callable, it is used at runtime to dynamically
make the decision. This is useful for tests that may require costly
imports, to delay the cost until the test suite is ... | [
"def",
"skipif",
"(",
"skip_condition",
",",
"msg",
"=",
"None",
")",
":",
"def",
"skip_decorator",
"(",
"f",
")",
":",
"# Local import to avoid a hard nose dependency and only incur the",
"# import time overhead at actual test-time.",
"import",
"nose",
"# Allow for both bool... | Make function raise SkipTest exception if a given condition is true.
If the condition is a callable, it is used at runtime to dynamically
make the decision. This is useful for tests that may require costly
imports, to delay the cost until the test suite is actually executed.
Parameters
----------
... | [
"Make",
"function",
"raise",
"SkipTest",
"exception",
"if",
"a",
"given",
"condition",
"is",
"true",
"."
] | python | test |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L1174-L1182 | def _get_url(self, session, uri):
"""
Helper method to get the full url
"""
url = session.url
if uri:
slash = '' if uri.startswith('/') else '/'
url = "%s%s%s" % (session.url, slash, uri)
return url | [
"def",
"_get_url",
"(",
"self",
",",
"session",
",",
"uri",
")",
":",
"url",
"=",
"session",
".",
"url",
"if",
"uri",
":",
"slash",
"=",
"''",
"if",
"uri",
".",
"startswith",
"(",
"'/'",
")",
"else",
"'/'",
"url",
"=",
"\"%s%s%s\"",
"%",
"(",
"se... | Helper method to get the full url | [
"Helper",
"method",
"to",
"get",
"the",
"full",
"url"
] | python | train |
ask/bundle | bundle/utils.py | https://github.com/ask/bundle/blob/bcd8f685f1039beeacce9fdf78dccf2d2e34d81f/bundle/utils.py#L17-L24 | def quote(text, ws=plain):
"""Quote special characters in shell command arguments.
E.g ``--foo bar>=10.1`` becomes "--foo bar\>\=10\.1``.
"""
return "".join(chr in ws and chr or '\\' + chr
for chr in text) | [
"def",
"quote",
"(",
"text",
",",
"ws",
"=",
"plain",
")",
":",
"return",
"\"\"",
".",
"join",
"(",
"chr",
"in",
"ws",
"and",
"chr",
"or",
"'\\\\'",
"+",
"chr",
"for",
"chr",
"in",
"text",
")"
] | Quote special characters in shell command arguments.
E.g ``--foo bar>=10.1`` becomes "--foo bar\>\=10\.1``. | [
"Quote",
"special",
"characters",
"in",
"shell",
"command",
"arguments",
"."
] | python | train |
tensorflow/tensorboard | tensorboard/plugins/interactive_inference/interactive_inference_plugin.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/interactive_inference/interactive_inference_plugin.py#L301-L314 | def _eligible_features_from_example_handler(self, request):
"""Returns a list of JSON objects for each feature in the example.
Args:
request: A request for features.
Returns:
A list with a JSON object for each feature.
Numeric features are represented as {name: observedMin: observedMax:}... | [
"def",
"_eligible_features_from_example_handler",
"(",
"self",
",",
"request",
")",
":",
"features_list",
"=",
"inference_utils",
".",
"get_eligible_features",
"(",
"self",
".",
"examples",
"[",
"0",
":",
"NUM_EXAMPLES_TO_SCAN",
"]",
",",
"NUM_MUTANTS",
")",
"return... | Returns a list of JSON objects for each feature in the example.
Args:
request: A request for features.
Returns:
A list with a JSON object for each feature.
Numeric features are represented as {name: observedMin: observedMax:}.
Categorical features are repesented as {name: samples:[]}. | [
"Returns",
"a",
"list",
"of",
"JSON",
"objects",
"for",
"each",
"feature",
"in",
"the",
"example",
"."
] | python | train |
MrYsLab/pymata-aio | pymata_aio/pymata_iot.py | https://github.com/MrYsLab/pymata-aio/blob/015081a4628b9d47dfe3f8d6c698ff903f107810/pymata_aio/pymata_iot.py#L127-L140 | async def digital_read(self, command):
"""
This method reads and returns the last reported value for a digital pin.
Normally not used since digital pin updates will be provided automatically
as they occur with the digital_message_reply being sent to the client after set_pin_mode is calle... | [
"async",
"def",
"digital_read",
"(",
"self",
",",
"command",
")",
":",
"pin",
"=",
"int",
"(",
"command",
"[",
"0",
"]",
")",
"data_val",
"=",
"await",
"self",
".",
"core",
".",
"digital_read",
"(",
"pin",
")",
"reply",
"=",
"json",
".",
"dumps",
"... | This method reads and returns the last reported value for a digital pin.
Normally not used since digital pin updates will be provided automatically
as they occur with the digital_message_reply being sent to the client after set_pin_mode is called..
(see enable_digital_reporting for message forma... | [
"This",
"method",
"reads",
"and",
"returns",
"the",
"last",
"reported",
"value",
"for",
"a",
"digital",
"pin",
".",
"Normally",
"not",
"used",
"since",
"digital",
"pin",
"updates",
"will",
"be",
"provided",
"automatically",
"as",
"they",
"occur",
"with",
"th... | python | train |
serge-sans-paille/pythran | pythran/analyses/range_values.py | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L306-L324 | def visit_IfExp(self, node):
""" Use worst case for both possible values.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2 or 3
... b = 4 or 5
... c = a if a else b''')
... | [
"def",
"visit_IfExp",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"visit",
"(",
"node",
".",
"test",
")",
"body_res",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"body",
")",
"orelse_res",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"orelse"... | Use worst case for both possible values.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2 or 3
... b = 4 or 5
... c = a if a else b''')
>>> pm = passmanager.PassManager("test... | [
"Use",
"worst",
"case",
"for",
"both",
"possible",
"values",
"."
] | python | train |
openstack/horizon | openstack_dashboard/dashboards/project/instances/utils.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/dashboards/project/instances/utils.py#L143-L168 | def keypair_field_data(request, include_empty_option=False):
"""Returns a list of tuples of all keypairs.
Generates a list of keypairs available to the user (request). And returns
a list of (id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a... | [
"def",
"keypair_field_data",
"(",
"request",
",",
"include_empty_option",
"=",
"False",
")",
":",
"keypair_list",
"=",
"[",
"]",
"try",
":",
"keypairs",
"=",
"api",
".",
"nova",
".",
"keypair_list",
"(",
"request",
")",
"keypair_list",
"=",
"[",
"(",
"kp",... | Returns a list of tuples of all keypairs.
Generates a list of keypairs available to the user (request). And returns
a list of (id, name) tuples.
:param request: django http request object
:param include_empty_option: flag to include a empty tuple in the front of
the list
:return: list of (... | [
"Returns",
"a",
"list",
"of",
"tuples",
"of",
"all",
"keypairs",
"."
] | python | train |
google/grr | grr/server/grr_response_server/throttle.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/throttle.py#L48-L82 | def _LoadFlows(self, client_id, min_create_time, token):
"""Yields all flows for the given client_id and time range.
Args:
client_id: client URN
min_create_time: minimum creation time (inclusive)
token: acl token
Yields: flow_objects.Flow objects
"""
if data_store.RelationalDBEnab... | [
"def",
"_LoadFlows",
"(",
"self",
",",
"client_id",
",",
"min_create_time",
",",
"token",
")",
":",
"if",
"data_store",
".",
"RelationalDBEnabled",
"(",
")",
":",
"if",
"isinstance",
"(",
"client_id",
",",
"rdfvalue",
".",
"RDFURN",
")",
":",
"client_id",
... | Yields all flows for the given client_id and time range.
Args:
client_id: client URN
min_create_time: minimum creation time (inclusive)
token: acl token
Yields: flow_objects.Flow objects | [
"Yields",
"all",
"flows",
"for",
"the",
"given",
"client_id",
"and",
"time",
"range",
"."
] | python | train |
rosenbrockc/acorn | acorn/logging/decoration.py | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/acorn/logging/decoration.py#L606-L624 | def pre(fqdn, parent, stackdepth, *argl, **argd):
"""Adds logging for a call to the specified function that is being handled
by an external module.
Args:
fqdn (str): fully-qualified domain name of the function being logged.
parent: *object* that the function belongs to.
stackdepth (... | [
"def",
"pre",
"(",
"fqdn",
",",
"parent",
",",
"stackdepth",
",",
"*",
"argl",
",",
"*",
"*",
"argd",
")",
":",
"global",
"_atdepth_call",
",",
"_cstack_call",
"#We add +1 to stackdepth because this method had to be called in",
"#addition to the wrapper method, so we woul... | Adds logging for a call to the specified function that is being handled
by an external module.
Args:
fqdn (str): fully-qualified domain name of the function being logged.
parent: *object* that the function belongs to.
stackdepth (int): maximum stack depth before entries are ignored.
... | [
"Adds",
"logging",
"for",
"a",
"call",
"to",
"the",
"specified",
"function",
"that",
"is",
"being",
"handled",
"by",
"an",
"external",
"module",
"."
] | python | train |
secure-systems-lab/securesystemslib | securesystemslib/formats.py | https://github.com/secure-systems-lab/securesystemslib/blob/beb3109d5bb462e5a60eed88fb40ed1167bd354e/securesystemslib/formats.py#L618-L643 | def format_base64(data):
"""
<Purpose>
Return the base64 encoding of 'data' with whitespace and '=' signs omitted.
<Arguments>
data:
Binary or buffer of data to convert.
<Exceptions>
securesystemslib.exceptions.FormatError, if the base64 encoding fails or the
argument is invalid.
<Sid... | [
"def",
"format_base64",
"(",
"data",
")",
":",
"try",
":",
"return",
"binascii",
".",
"b2a_base64",
"(",
"data",
")",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"rstrip",
"(",
"'=\\n '",
")",
"except",
"(",
"TypeError",
",",
"binascii",
".",
"Error",
")"... | <Purpose>
Return the base64 encoding of 'data' with whitespace and '=' signs omitted.
<Arguments>
data:
Binary or buffer of data to convert.
<Exceptions>
securesystemslib.exceptions.FormatError, if the base64 encoding fails or the
argument is invalid.
<Side Effects>
None.
<Returns>... | [
"<Purpose",
">",
"Return",
"the",
"base64",
"encoding",
"of",
"data",
"with",
"whitespace",
"and",
"=",
"signs",
"omitted",
"."
] | python | train |
saltstack/salt | salt/modules/x509.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L1109-L1585 | def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
... | [
"def",
"create_certificate",
"(",
"path",
"=",
"None",
",",
"text",
"=",
"False",
",",
"overwrite",
"=",
"True",
",",
"ca_server",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"path",
"and",
"not",
"text",
"and",
"(",
"'testrun'",
"no... | Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
If True(default), create_certificate will overwrite the entire pem
file. Set False to preserve existi... | [
"Create",
"an",
"X509",
"certificate",
"."
] | python | train |
tevino/mongu | mongu.py | https://github.com/tevino/mongu/blob/98f15cdb9e5906062f2d5088c7bf774ab007c6e5/mongu.py#L34-L46 | def register_model(self, model_cls):
"""Decorator for registering model."""
if not getattr(model_cls, '_database_'):
raise ModelAttributeError('_database_ missing '
'on %s!' % model_cls.__name__)
if not getattr(model_cls, '_collection_'):
... | [
"def",
"register_model",
"(",
"self",
",",
"model_cls",
")",
":",
"if",
"not",
"getattr",
"(",
"model_cls",
",",
"'_database_'",
")",
":",
"raise",
"ModelAttributeError",
"(",
"'_database_ missing '",
"'on %s!'",
"%",
"model_cls",
".",
"__name__",
")",
"if",
"... | Decorator for registering model. | [
"Decorator",
"for",
"registering",
"model",
"."
] | python | train |
sernst/cauldron | cauldron/session/projects/project.py | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/project.py#L81-L107 | def library_directories(self) -> typing.List[str]:
"""
The list of directories to all of the library locations
"""
def listify(value):
return [value] if isinstance(value, str) else list(value)
# If this is a project running remotely remove external library
# ... | [
"def",
"library_directories",
"(",
"self",
")",
"->",
"typing",
".",
"List",
"[",
"str",
"]",
":",
"def",
"listify",
"(",
"value",
")",
":",
"return",
"[",
"value",
"]",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
"else",
"list",
"(",
"value",... | The list of directories to all of the library locations | [
"The",
"list",
"of",
"directories",
"to",
"all",
"of",
"the",
"library",
"locations"
] | python | train |
mongodb/mongo-python-driver | pymongo/collection.py | https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/pymongo/collection.py#L1847-L1875 | def __create_index(self, keys, index_options, session, **kwargs):
"""Internal create index helper.
:Parameters:
- `keys`: a list of tuples [(key, type), (key, type), ...]
- `index_options`: a dict of index options.
- `session` (optional): a
:class:`~pymongo.cli... | [
"def",
"__create_index",
"(",
"self",
",",
"keys",
",",
"index_options",
",",
"session",
",",
"*",
"*",
"kwargs",
")",
":",
"index_doc",
"=",
"helpers",
".",
"_index_document",
"(",
"keys",
")",
"index",
"=",
"{",
"\"key\"",
":",
"index_doc",
"}",
"colla... | Internal create index helper.
:Parameters:
- `keys`: a list of tuples [(key, type), (key, type), ...]
- `index_options`: a dict of index options.
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`. | [
"Internal",
"create",
"index",
"helper",
"."
] | python | train |
PMBio/limix-backup | limix/deprecated/core.py | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/core.py#L2799-L2832 | def check_covariance_Kgrad_x(covar, relchange=1E-5, threshold=1E-2, check_diag=True):
"""
check_covariance_Kgrad_x(ACovarianceFunction covar, limix::mfloat_t relchange=1E-5, limix::mfloat_t threshold=1E-2, bool check_diag=True) -> bool
Parameters
----------
covar: limix::ACovari... | [
"def",
"check_covariance_Kgrad_x",
"(",
"covar",
",",
"relchange",
"=",
"1E-5",
",",
"threshold",
"=",
"1E-2",
",",
"check_diag",
"=",
"True",
")",
":",
"return",
"_core",
".",
"ACovarianceFunction_check_covariance_Kgrad_x",
"(",
"covar",
",",
"relchange",
",",
... | check_covariance_Kgrad_x(ACovarianceFunction covar, limix::mfloat_t relchange=1E-5, limix::mfloat_t threshold=1E-2, bool check_diag=True) -> bool
Parameters
----------
covar: limix::ACovarianceFunction &
relchange: limix::mfloat_t
threshold: limix::mfloat_t
check_diag: b... | [
"check_covariance_Kgrad_x",
"(",
"ACovarianceFunction",
"covar",
"limix",
"::",
"mfloat_t",
"relchange",
"=",
"1E",
"-",
"5",
"limix",
"::",
"mfloat_t",
"threshold",
"=",
"1E",
"-",
"2",
"bool",
"check_diag",
"=",
"True",
")",
"-",
">",
"bool"
] | python | train |
sibirrer/lenstronomy | lenstronomy/Util/simulation_util.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/Util/simulation_util.py#L10-L33 | def data_configure_simple(numPix, deltaPix, exposure_time=1, sigma_bkg=1, inverse=False):
"""
configures the data keyword arguments with a coordinate grid centered at zero.
:param numPix: number of pixel (numPix x numPix)
:param deltaPix: pixel size (in angular units)
:param exposure_time: exposure... | [
"def",
"data_configure_simple",
"(",
"numPix",
",",
"deltaPix",
",",
"exposure_time",
"=",
"1",
",",
"sigma_bkg",
"=",
"1",
",",
"inverse",
"=",
"False",
")",
":",
"mean",
"=",
"0.",
"# background mean flux (default zero)",
"# 1d list of coordinates (x,y) of a numPix ... | configures the data keyword arguments with a coordinate grid centered at zero.
:param numPix: number of pixel (numPix x numPix)
:param deltaPix: pixel size (in angular units)
:param exposure_time: exposure time
:param sigma_bkg: background noise (Gaussian sigma)
:param inverse: if True, coordinate ... | [
"configures",
"the",
"data",
"keyword",
"arguments",
"with",
"a",
"coordinate",
"grid",
"centered",
"at",
"zero",
"."
] | python | train |
geographika/mappyfile | mappyfile/transformer.py | https://github.com/geographika/mappyfile/blob/aecbc5e66ec06896bc4c5db41313503468829d00/mappyfile/transformer.py#L293-L316 | def check_composite_tokens(self, name, tokens):
"""
Return the key and contents of a KEY..END block
for PATTERN, POINTS, and PROJECTION
"""
assert len(tokens) >= 2
key = tokens[0]
assert key.value.lower() == name
assert tokens[-1].value.lower() == "end"
... | [
"def",
"check_composite_tokens",
"(",
"self",
",",
"name",
",",
"tokens",
")",
":",
"assert",
"len",
"(",
"tokens",
")",
">=",
"2",
"key",
"=",
"tokens",
"[",
"0",
"]",
"assert",
"key",
".",
"value",
".",
"lower",
"(",
")",
"==",
"name",
"assert",
... | Return the key and contents of a KEY..END block
for PATTERN, POINTS, and PROJECTION | [
"Return",
"the",
"key",
"and",
"contents",
"of",
"a",
"KEY",
"..",
"END",
"block",
"for",
"PATTERN",
"POINTS",
"and",
"PROJECTION"
] | python | train |
iotaledger/iota.lib.py | iota/bin/__init__.py | https://github.com/iotaledger/iota.lib.py/blob/97cdd1e241498446b46157b79b2a1ea2ec6d387a/iota/bin/__init__.py#L63-L78 | def run_from_argv(self, argv=None):
# type: (Optional[tuple]) -> int
"""
Executes the command from a collection of arguments (e.g.,
:py:data`sys.argv`) and returns the exit code.
:param argv:
Arguments to pass to the argument parser.
If ``None``, defaults... | [
"def",
"run_from_argv",
"(",
"self",
",",
"argv",
"=",
"None",
")",
":",
"# type: (Optional[tuple]) -> int",
"exit_code",
"=",
"self",
".",
"execute",
"(",
"*",
"*",
"self",
".",
"parse_argv",
"(",
"argv",
")",
")",
"if",
"exit_code",
"is",
"None",
":",
... | Executes the command from a collection of arguments (e.g.,
:py:data`sys.argv`) and returns the exit code.
:param argv:
Arguments to pass to the argument parser.
If ``None``, defaults to ``sys.argv[1:]``. | [
"Executes",
"the",
"command",
"from",
"a",
"collection",
"of",
"arguments",
"(",
"e",
".",
"g",
".",
":",
"py",
":",
"data",
"sys",
".",
"argv",
")",
"and",
"returns",
"the",
"exit",
"code",
"."
] | python | test |
mozilla-releng/scriptworker | scriptworker/ed25519.py | https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/ed25519.py#L42-L57 | def ed25519_public_key_from_string(string):
"""Create an ed25519 public key from ``string``, which is a seed.
Args:
string (str): the string to use as a seed.
Returns:
Ed25519PublicKey: the public key
"""
try:
return Ed25519PublicKey.from_public_bytes(
base64.b... | [
"def",
"ed25519_public_key_from_string",
"(",
"string",
")",
":",
"try",
":",
"return",
"Ed25519PublicKey",
".",
"from_public_bytes",
"(",
"base64",
".",
"b64decode",
"(",
"string",
")",
")",
"except",
"(",
"UnsupportedAlgorithm",
",",
"Base64Error",
")",
"as",
... | Create an ed25519 public key from ``string``, which is a seed.
Args:
string (str): the string to use as a seed.
Returns:
Ed25519PublicKey: the public key | [
"Create",
"an",
"ed25519",
"public",
"key",
"from",
"string",
"which",
"is",
"a",
"seed",
"."
] | python | train |
jbloomlab/phydms | phydmslib/models.py | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2011-L2017 | def dlogprior(self, param):
"""Equal to value of `basemodel.dlogprior`."""
assert param in self.freeparams, "Invalid param: {0}".format(param)
if param in self.distributionparams:
return 0.0
else:
return self._models[0].dlogprior(param) | [
"def",
"dlogprior",
"(",
"self",
",",
"param",
")",
":",
"assert",
"param",
"in",
"self",
".",
"freeparams",
",",
"\"Invalid param: {0}\"",
".",
"format",
"(",
"param",
")",
"if",
"param",
"in",
"self",
".",
"distributionparams",
":",
"return",
"0.0",
"els... | Equal to value of `basemodel.dlogprior`. | [
"Equal",
"to",
"value",
"of",
"basemodel",
".",
"dlogprior",
"."
] | python | train |
wmayner/pyphi | pyphi/macro.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/macro.py#L610-L630 | def reindex(self):
"""Squeeze the indices of this blackboxing to ``0..n``.
Returns:
Blackbox: a new, reindexed |Blackbox|.
Example:
>>> partition = ((3,), (2, 4))
>>> output_indices = (2, 3)
>>> blackbox = Blackbox(partition, output_indices)
... | [
"def",
"reindex",
"(",
"self",
")",
":",
"_map",
"=",
"dict",
"(",
"zip",
"(",
"self",
".",
"micro_indices",
",",
"reindex",
"(",
"self",
".",
"micro_indices",
")",
")",
")",
"partition",
"=",
"tuple",
"(",
"tuple",
"(",
"_map",
"[",
"index",
"]",
... | Squeeze the indices of this blackboxing to ``0..n``.
Returns:
Blackbox: a new, reindexed |Blackbox|.
Example:
>>> partition = ((3,), (2, 4))
>>> output_indices = (2, 3)
>>> blackbox = Blackbox(partition, output_indices)
>>> blackbox.reindex()... | [
"Squeeze",
"the",
"indices",
"of",
"this",
"blackboxing",
"to",
"0",
"..",
"n",
"."
] | python | train |
programa-stic/barf-project | barf/core/smt/smttranslator.py | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/smt/smttranslator.py#L385-L405 | def _translate_div(self, oprnd1, oprnd2, oprnd3):
"""Return a formula representation of an DIV instruction.
"""
assert oprnd1.size and oprnd2.size and oprnd3.size
assert oprnd1.size == oprnd2.size
op1_var = self._translate_src_oprnd(oprnd1)
op2_var = self._translate_src_... | [
"def",
"_translate_div",
"(",
"self",
",",
"oprnd1",
",",
"oprnd2",
",",
"oprnd3",
")",
":",
"assert",
"oprnd1",
".",
"size",
"and",
"oprnd2",
".",
"size",
"and",
"oprnd3",
".",
"size",
"assert",
"oprnd1",
".",
"size",
"==",
"oprnd2",
".",
"size",
"op1... | Return a formula representation of an DIV instruction. | [
"Return",
"a",
"formula",
"representation",
"of",
"an",
"DIV",
"instruction",
"."
] | python | train |
Qiskit/qiskit-terra | qiskit/providers/basicaer/qasm_simulator.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/qasm_simulator.py#L374-L404 | def run(self, qobj, backend_options=None):
"""Run qobj asynchronously.
Args:
qobj (Qobj): payload of the experiment
backend_options (dict): backend options
Returns:
BasicAerJob: derived from BaseJob
Additional Information:
backend_option... | [
"def",
"run",
"(",
"self",
",",
"qobj",
",",
"backend_options",
"=",
"None",
")",
":",
"self",
".",
"_set_options",
"(",
"qobj_config",
"=",
"qobj",
".",
"config",
",",
"backend_options",
"=",
"backend_options",
")",
"job_id",
"=",
"str",
"(",
"uuid",
".... | Run qobj asynchronously.
Args:
qobj (Qobj): payload of the experiment
backend_options (dict): backend options
Returns:
BasicAerJob: derived from BaseJob
Additional Information:
backend_options: Is a dict of options for the backend. It may contai... | [
"Run",
"qobj",
"asynchronously",
"."
] | python | test |
gtalarico/airtable-python-wrapper | airtable/airtable.py | https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L512-L534 | def delete_by_field(self, field_name, field_value, **options):
"""
Deletes first record to match provided ``field_name`` and
``field_value``.
>>> record = airtable.delete_by_field('Employee Id', 'DD13332454')
Args:
field_name (``str``): Name of field to mat... | [
"def",
"delete_by_field",
"(",
"self",
",",
"field_name",
",",
"field_value",
",",
"*",
"*",
"options",
")",
":",
"record",
"=",
"self",
".",
"match",
"(",
"field_name",
",",
"field_value",
",",
"*",
"*",
"options",
")",
"record_url",
"=",
"self",
".",
... | Deletes first record to match provided ``field_name`` and
``field_value``.
>>> record = airtable.delete_by_field('Employee Id', 'DD13332454')
Args:
field_name (``str``): Name of field to match (column name).
field_value (``str``): Value of field to match.
... | [
"Deletes",
"first",
"record",
"to",
"match",
"provided",
"field_name",
"and",
"field_value",
".",
">>>",
"record",
"=",
"airtable",
".",
"delete_by_field",
"(",
"Employee",
"Id",
"DD13332454",
")",
"Args",
":",
"field_name",
"(",
"str",
")",
":",
"Name",
"of... | python | train |
EmbodiedCognition/pagoda | pagoda/skeleton.py | https://github.com/EmbodiedCognition/pagoda/blob/8892f847026d98aba8646ecbc4589397e6dec7bd/pagoda/skeleton.py#L348-L372 | def set_target_angles(self, angles):
'''Move each joint toward a target angle.
This method uses a PID controller to set a target angular velocity for
each degree of freedom in the skeleton, based on the difference between
the current and the target angle for the respective DOF.
... | [
"def",
"set_target_angles",
"(",
"self",
",",
"angles",
")",
":",
"j",
"=",
"0",
"for",
"joint",
"in",
"self",
".",
"joints",
":",
"velocities",
"=",
"[",
"ctrl",
"(",
"tgt",
"-",
"cur",
",",
"self",
".",
"world",
".",
"dt",
")",
"for",
"cur",
",... | Move each joint toward a target angle.
This method uses a PID controller to set a target angular velocity for
each degree of freedom in the skeleton, based on the difference between
the current and the target angle for the respective DOF.
PID parameters are by default set to achieve a ... | [
"Move",
"each",
"joint",
"toward",
"a",
"target",
"angle",
"."
] | python | valid |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L283-L308 | def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs):
"""Returns the list of RRSets in the specified zone of the specified type.
Arguments:
zone_name -- The name of the zone.
rtype -- The type of the RRSets. This can be numeric (1) or
if a... | [
"def",
"get_rrsets_by_type_owner",
"(",
"self",
",",
"zone_name",
",",
"rtype",
",",
"owner_name",
",",
"q",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"uri",
"=",
"\"/v1/zones/\"",
"+",
"zone_name",
"+",
"\"/rrsets/\"",
"+",
"rtype",
"+",
"\"/\"",
... | Returns the list of RRSets in the specified zone of the specified type.
Arguments:
zone_name -- The name of the zone.
rtype -- The type of the RRSets. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
owner_name -- The... | [
"Returns",
"the",
"list",
"of",
"RRSets",
"in",
"the",
"specified",
"zone",
"of",
"the",
"specified",
"type",
"."
] | python | train |
adafruit/Adafruit_Python_PN532 | Adafruit_PN532/PN532.py | https://github.com/adafruit/Adafruit_Python_PN532/blob/343521a8ec842ea82f680a5ed868fee16e9609bd/Adafruit_PN532/PN532.py#L301-L330 | def call_function(self, command, response_length=0, params=[], timeout_sec=1):
"""Send specified command to the PN532 and expect up to response_length
bytes back in a response. Note that less than the expected bytes might
be returned! Params can optionally specify an array of bytes to send as
... | [
"def",
"call_function",
"(",
"self",
",",
"command",
",",
"response_length",
"=",
"0",
",",
"params",
"=",
"[",
"]",
",",
"timeout_sec",
"=",
"1",
")",
":",
"# Build frame data with command and parameters.",
"data",
"=",
"bytearray",
"(",
"2",
"+",
"len",
"(... | Send specified command to the PN532 and expect up to response_length
bytes back in a response. Note that less than the expected bytes might
be returned! Params can optionally specify an array of bytes to send as
parameters to the function call. Will wait up to timeout_secs seconds
for... | [
"Send",
"specified",
"command",
"to",
"the",
"PN532",
"and",
"expect",
"up",
"to",
"response_length",
"bytes",
"back",
"in",
"a",
"response",
".",
"Note",
"that",
"less",
"than",
"the",
"expected",
"bytes",
"might",
"be",
"returned!",
"Params",
"can",
"optio... | python | train |
ehansis/ozelot | ozelot/cache.py | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/cache.py#L224-L239 | def has(self, url, xpath=None):
"""Check if a URL (and xpath) exists in the cache
If DB has not been initialized yet, returns ``False`` for any URL.
Args:
url (str): If given, clear specific item only. Otherwise remove the DB file.
xpath (str): xpath to search (may be `... | [
"def",
"has",
"(",
"self",
",",
"url",
",",
"xpath",
"=",
"None",
")",
":",
"if",
"not",
"path",
".",
"exists",
"(",
"self",
".",
"db_path",
")",
":",
"return",
"False",
"return",
"self",
".",
"_query",
"(",
"url",
",",
"xpath",
")",
".",
"count"... | Check if a URL (and xpath) exists in the cache
If DB has not been initialized yet, returns ``False`` for any URL.
Args:
url (str): If given, clear specific item only. Otherwise remove the DB file.
xpath (str): xpath to search (may be ``None``)
Returns:
bool... | [
"Check",
"if",
"a",
"URL",
"(",
"and",
"xpath",
")",
"exists",
"in",
"the",
"cache"
] | python | train |
zengbin93/zb | zb/dev/decorator.py | https://github.com/zengbin93/zb/blob/ccdb384a0b5801b459933220efcb71972c2b89a7/zb/dev/decorator.py#L63-L71 | def _update_doc(self, func_doc):
"""更新文档信息,把原来的文档信息进行合并格式化,
即第一行为deprecated_doc(Deprecated: tip_info),下一行为原始func_doc"""
deprecated_doc = "Deprecated"
if self.tip_info:
deprecated_doc = "{}: {}".format(deprecated_doc, self.tip_info)
if func_doc:
func_doc = ... | [
"def",
"_update_doc",
"(",
"self",
",",
"func_doc",
")",
":",
"deprecated_doc",
"=",
"\"Deprecated\"",
"if",
"self",
".",
"tip_info",
":",
"deprecated_doc",
"=",
"\"{}: {}\"",
".",
"format",
"(",
"deprecated_doc",
",",
"self",
".",
"tip_info",
")",
"if",
"fu... | 更新文档信息,把原来的文档信息进行合并格式化,
即第一行为deprecated_doc(Deprecated: tip_info),下一行为原始func_doc | [
"更新文档信息,把原来的文档信息进行合并格式化",
"即第一行为deprecated_doc",
"(",
"Deprecated",
":",
"tip_info",
")",
",下一行为原始func_doc"
] | python | train |
zhanglab/psamm | psamm/fluxanalysis.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/fluxanalysis.py#L293-L320 | def flux_balance(model, reaction, tfba, solver):
"""Run flux balance analysis on the given model.
Yields the reaction id and flux value for each reaction in the model.
This is a convenience function for sertting up and running the
FluxBalanceProblem. If the FBA is solved for more than one parameter
... | [
"def",
"flux_balance",
"(",
"model",
",",
"reaction",
",",
"tfba",
",",
"solver",
")",
":",
"fba",
"=",
"_get_fba_problem",
"(",
"model",
",",
"tfba",
",",
"solver",
")",
"fba",
".",
"maximize",
"(",
"reaction",
")",
"for",
"reaction",
"in",
"model",
"... | Run flux balance analysis on the given model.
Yields the reaction id and flux value for each reaction in the model.
This is a convenience function for sertting up and running the
FluxBalanceProblem. If the FBA is solved for more than one parameter
it is recommended to setup and reuse the FluxBalancePr... | [
"Run",
"flux",
"balance",
"analysis",
"on",
"the",
"given",
"model",
"."
] | python | train |
Yelp/kafka-utils | kafka_utils/util/offsets.py | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/util/offsets.py#L526-L536 | def nullify_offsets(offsets):
"""Modify offsets metadata so that the partition offsets
have null payloads.
:param offsets: dict {<topic>: {<partition>: <offset>}}
:returns: a dict topic: partition: offset
"""
result = {}
for topic, partition_offsets in six.iteritems(offsets):
result... | [
"def",
"nullify_offsets",
"(",
"offsets",
")",
":",
"result",
"=",
"{",
"}",
"for",
"topic",
",",
"partition_offsets",
"in",
"six",
".",
"iteritems",
"(",
"offsets",
")",
":",
"result",
"[",
"topic",
"]",
"=",
"_nullify_partition_offsets",
"(",
"partition_of... | Modify offsets metadata so that the partition offsets
have null payloads.
:param offsets: dict {<topic>: {<partition>: <offset>}}
:returns: a dict topic: partition: offset | [
"Modify",
"offsets",
"metadata",
"so",
"that",
"the",
"partition",
"offsets",
"have",
"null",
"payloads",
"."
] | python | train |
dddomodossola/remi | remi/gui.py | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L526-L537 | def set_style(self, style):
""" Allows to set style properties for the widget.
Args:
style (str or dict): The style property dictionary or json string.
"""
if style is not None:
try:
self.style.update(style)
except ValueError:
... | [
"def",
"set_style",
"(",
"self",
",",
"style",
")",
":",
"if",
"style",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"style",
".",
"update",
"(",
"style",
")",
"except",
"ValueError",
":",
"for",
"s",
"in",
"style",
".",
"split",
"(",
"';'",
... | Allows to set style properties for the widget.
Args:
style (str or dict): The style property dictionary or json string. | [
"Allows",
"to",
"set",
"style",
"properties",
"for",
"the",
"widget",
".",
"Args",
":",
"style",
"(",
"str",
"or",
"dict",
")",
":",
"The",
"style",
"property",
"dictionary",
"or",
"json",
"string",
"."
] | python | train |
drericstrong/pyedna | pyedna/ezdna.py | https://github.com/drericstrong/pyedna/blob/b8f8f52def4f26bb4f3a993ce3400769518385f6/pyedna/ezdna.py#L609-L642 | def GetTagDescription(tag_name):
"""
Gets the current description of a point configured in a real-time eDNA
service.
:param tag_name: fully-qualified (site.service.tag) eDNA tag
:return: tag description
"""
# Check if the point even exists
if not DoesIDExist(tag_name):
... | [
"def",
"GetTagDescription",
"(",
"tag_name",
")",
":",
"# Check if the point even exists\r",
"if",
"not",
"DoesIDExist",
"(",
"tag_name",
")",
":",
"warnings",
".",
"warn",
"(",
"\"WARNING- \"",
"+",
"tag_name",
"+",
"\" does not exist or \"",
"+",
"\"connection was d... | Gets the current description of a point configured in a real-time eDNA
service.
:param tag_name: fully-qualified (site.service.tag) eDNA tag
:return: tag description | [
"Gets",
"the",
"current",
"description",
"of",
"a",
"point",
"configured",
"in",
"a",
"real",
"-",
"time",
"eDNA",
"service",
".",
":",
"param",
"tag_name",
":",
"fully",
"-",
"qualified",
"(",
"site",
".",
"service",
".",
"tag",
")",
"eDNA",
"tag",
":... | python | train |
pywbem/pywbem | pywbem/cim_types.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_types.py#L997-L1071 | def cimtype(obj):
"""
Return the CIM data type name of a CIM typed object, as a string.
For an array, the type is determined from the first array element
(CIM arrays must be homogeneous w.r.t. the type of their elements).
If the array is empty, that is not possible and
:exc:`~py:exceptions.Valu... | [
"def",
"cimtype",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"CIMType",
")",
":",
"return",
"obj",
".",
"cimtype",
"if",
"isinstance",
"(",
"obj",
",",
"bool",
")",
":",
"return",
"'boolean'",
"if",
"isinstance",
"(",
"obj",
",",
"(",... | Return the CIM data type name of a CIM typed object, as a string.
For an array, the type is determined from the first array element
(CIM arrays must be homogeneous w.r.t. the type of their elements).
If the array is empty, that is not possible and
:exc:`~py:exceptions.ValueError` is raised.
Note t... | [
"Return",
"the",
"CIM",
"data",
"type",
"name",
"of",
"a",
"CIM",
"typed",
"object",
"as",
"a",
"string",
"."
] | python | train |
PBR/MQ2 | MQ2/__init__.py | https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/__init__.py#L51-L92 | def extract_zip(filename, extract_dir):
""" Extract the sources in a temporary folder.
:arg filename, name of the zip file containing the data from MapQTL
which will be extracted
:arg extract_dir, folder in which to extract the archive.
"""
LOG.info("Extracting %s in %s " % (filename, extract_di... | [
"def",
"extract_zip",
"(",
"filename",
",",
"extract_dir",
")",
":",
"LOG",
".",
"info",
"(",
"\"Extracting %s in %s \"",
"%",
"(",
"filename",
",",
"extract_dir",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"extract_dir",
")",
":",
"tr... | Extract the sources in a temporary folder.
:arg filename, name of the zip file containing the data from MapQTL
which will be extracted
:arg extract_dir, folder in which to extract the archive. | [
"Extract",
"the",
"sources",
"in",
"a",
"temporary",
"folder",
".",
":",
"arg",
"filename",
"name",
"of",
"the",
"zip",
"file",
"containing",
"the",
"data",
"from",
"MapQTL",
"which",
"will",
"be",
"extracted",
":",
"arg",
"extract_dir",
"folder",
"in",
"w... | python | train |
jxtech/wechatpy | wechatpy/enterprise/client/api/chat.py | https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/enterprise/client/api/chat.py#L161-L170 | def send_single_text(self, sender, receiver, content):
"""
发送单聊文本消息
:param sender: 发送人
:param receiver: 接收人成员 ID
:param content: 消息内容
:return: 返回的 JSON 数据包
"""
return self.send_text(sender, 'single', receiver, content) | [
"def",
"send_single_text",
"(",
"self",
",",
"sender",
",",
"receiver",
",",
"content",
")",
":",
"return",
"self",
".",
"send_text",
"(",
"sender",
",",
"'single'",
",",
"receiver",
",",
"content",
")"
] | 发送单聊文本消息
:param sender: 发送人
:param receiver: 接收人成员 ID
:param content: 消息内容
:return: 返回的 JSON 数据包 | [
"发送单聊文本消息"
] | python | train |
codelv/enaml-native-maps | src/googlemaps/android/android_map_view.py | https://github.com/codelv/enaml-native-maps/blob/5b6dda745cede05755dd40d29775cc0544226c29/src/googlemaps/android/android_map_view.py#L980-L1002 | def on_marker(self, marker):
""" Convert our options into the actual marker object"""
mid, pos = marker
self.marker = Marker(__id__=mid)
mapview = self.parent()
# Save ref
mapview.markers[mid] = self
# Required so the packer can pass the id
self.marker.se... | [
"def",
"on_marker",
"(",
"self",
",",
"marker",
")",
":",
"mid",
",",
"pos",
"=",
"marker",
"self",
".",
"marker",
"=",
"Marker",
"(",
"__id__",
"=",
"mid",
")",
"mapview",
"=",
"self",
".",
"parent",
"(",
")",
"# Save ref",
"mapview",
".",
"markers"... | Convert our options into the actual marker object | [
"Convert",
"our",
"options",
"into",
"the",
"actual",
"marker",
"object"
] | python | valid |
ladybug-tools/ladybug | ladybug/designday.py | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/designday.py#L1357-L1365 | def to_json(self):
"""Convert the Sky Condition to a dictionary."""
return {
'solar_model': self.solar_model,
'month': self.month,
'day_of_month': self.day_of_month,
'clearness': self.clearness,
'daylight_savings_indicator': self.daylight_savin... | [
"def",
"to_json",
"(",
"self",
")",
":",
"return",
"{",
"'solar_model'",
":",
"self",
".",
"solar_model",
",",
"'month'",
":",
"self",
".",
"month",
",",
"'day_of_month'",
":",
"self",
".",
"day_of_month",
",",
"'clearness'",
":",
"self",
".",
"clearness",... | Convert the Sky Condition to a dictionary. | [
"Convert",
"the",
"Sky",
"Condition",
"to",
"a",
"dictionary",
"."
] | python | train |
hfaran/progressive | progressive/bar.py | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/bar.py#L169-L184 | def full_line_width(self):
"""Find actual length of bar_str
e.g., Progress [ | ] 10/10
"""
bar_str_len = sum([
self._indent,
((len(self.title) + 1) if self._title_pos in ["left", "right"]
else 0), # Title if present
len(self.start... | [
"def",
"full_line_width",
"(",
"self",
")",
":",
"bar_str_len",
"=",
"sum",
"(",
"[",
"self",
".",
"_indent",
",",
"(",
"(",
"len",
"(",
"self",
".",
"title",
")",
"+",
"1",
")",
"if",
"self",
".",
"_title_pos",
"in",
"[",
"\"left\"",
",",
"\"right... | Find actual length of bar_str
e.g., Progress [ | ] 10/10 | [
"Find",
"actual",
"length",
"of",
"bar_str"
] | python | train |
saltstack/salt | salt/modules/drbd.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drbd.py#L70-L84 | def _add_res(line):
'''
Analyse the line of local resource of ``drbdadm status``
'''
global resource
fields = line.strip().split()
if resource:
ret.append(resource)
resource = {}
resource["resource name"] = fields[0]
resource["local role"] = fields[1].split(":")[1]
... | [
"def",
"_add_res",
"(",
"line",
")",
":",
"global",
"resource",
"fields",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"if",
"resource",
":",
"ret",
".",
"append",
"(",
"resource",
")",
"resource",
"=",
"{",
"}",
"resource",
"[",
"\... | Analyse the line of local resource of ``drbdadm status`` | [
"Analyse",
"the",
"line",
"of",
"local",
"resource",
"of",
"drbdadm",
"status"
] | python | train |
markovmodel/PyEMMA | pyemma/coordinates/data/util/reader_utils.py | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/util/reader_utils.py#L134-L151 | def copy_traj_attributes(target, origin, start):
""" Inserts certain attributes of origin into target
:param target: target trajectory object
:param origin: origin trajectory object
:param start: :py:obj:`origin` attributes will be inserted in :py:obj:`target` starting at this index
:return: target:... | [
"def",
"copy_traj_attributes",
"(",
"target",
",",
"origin",
",",
"start",
")",
":",
"# The list of copied attributes can be extended here with time",
"# Or perhaps ask the mdtraj guys to implement something similar?",
"stop",
"=",
"start",
"+",
"origin",
".",
"n_frames",
"targ... | Inserts certain attributes of origin into target
:param target: target trajectory object
:param origin: origin trajectory object
:param start: :py:obj:`origin` attributes will be inserted in :py:obj:`target` starting at this index
:return: target: the md trajectory with the attributes of :py:obj:`origin... | [
"Inserts",
"certain",
"attributes",
"of",
"origin",
"into",
"target",
":",
"param",
"target",
":",
"target",
"trajectory",
"object",
":",
"param",
"origin",
":",
"origin",
"trajectory",
"object",
":",
"param",
"start",
":",
":",
"py",
":",
"obj",
":",
"ori... | python | train |
heronotears/lazyxml | lazyxml/parser.py | https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L102-L109 | def guess_xml_encoding(self, content):
r"""Guess encoding from xml header declaration.
:param content: xml content
:rtype: str or None
"""
matchobj = self.__regex['xml_encoding'].match(content)
return matchobj and matchobj.group(1).lower() | [
"def",
"guess_xml_encoding",
"(",
"self",
",",
"content",
")",
":",
"matchobj",
"=",
"self",
".",
"__regex",
"[",
"'xml_encoding'",
"]",
".",
"match",
"(",
"content",
")",
"return",
"matchobj",
"and",
"matchobj",
".",
"group",
"(",
"1",
")",
".",
"lower"... | r"""Guess encoding from xml header declaration.
:param content: xml content
:rtype: str or None | [
"r",
"Guess",
"encoding",
"from",
"xml",
"header",
"declaration",
"."
] | python | train |
mikedh/trimesh | trimesh/path/path.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/path/path.py#L1381-L1387 | def identifier_md5(self):
"""
Return an MD5 of the identifier
"""
as_int = (self.identifier * 1e4).astype(np.int64)
hashed = util.md5_object(as_int.tostring(order='C'))
return hashed | [
"def",
"identifier_md5",
"(",
"self",
")",
":",
"as_int",
"=",
"(",
"self",
".",
"identifier",
"*",
"1e4",
")",
".",
"astype",
"(",
"np",
".",
"int64",
")",
"hashed",
"=",
"util",
".",
"md5_object",
"(",
"as_int",
".",
"tostring",
"(",
"order",
"=",
... | Return an MD5 of the identifier | [
"Return",
"an",
"MD5",
"of",
"the",
"identifier"
] | python | train |
mmp2/megaman | megaman/utils/k_means_clustering.py | https://github.com/mmp2/megaman/blob/faccaf267aad0a8b18ec8a705735fd9dd838ca1e/megaman/utils/k_means_clustering.py#L49-L74 | def orthogonal_initialization(X,K):
"""
Initialize the centrodis by orthogonal_initialization.
Parameters
--------------------
X(data): array-like, shape= (m_samples,n_samples)
K: integer
number of K clusters
Returns
-------
centroids: array-like, shape (K,n_samples) ... | [
"def",
"orthogonal_initialization",
"(",
"X",
",",
"K",
")",
":",
"N",
",",
"M",
"=",
"X",
".",
"shape",
"centroids",
"=",
"X",
"[",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"N",
"-",
"1",
",",
"1",
")",
",",
":",
"]",
"data_norms",
... | Initialize the centrodis by orthogonal_initialization.
Parameters
--------------------
X(data): array-like, shape= (m_samples,n_samples)
K: integer
number of K clusters
Returns
-------
centroids: array-like, shape (K,n_samples)
data_norms: array-like, shape=(1,n_samples) | [
"Initialize",
"the",
"centrodis",
"by",
"orthogonal_initialization",
".",
"Parameters",
"--------------------",
"X",
"(",
"data",
")",
":",
"array",
"-",
"like",
"shape",
"=",
"(",
"m_samples",
"n_samples",
")",
"K",
":",
"integer",
"number",
"of",
"K",
"clust... | python | train |
rosenbrockc/fortpy | fortpy/elements.py | https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/elements.py#L1870-L1881 | def charindex(self, line, column):
"""Gets the absolute character index of the line and column
in the continuous string."""
#Make sure that we have chars and lines to work from if this
#gets called before linenum() does.
if len(self._lines) == 0:
self.linenum(1)
... | [
"def",
"charindex",
"(",
"self",
",",
"line",
",",
"column",
")",
":",
"#Make sure that we have chars and lines to work from if this",
"#gets called before linenum() does.",
"if",
"len",
"(",
"self",
".",
"_lines",
")",
"==",
"0",
":",
"self",
".",
"linenum",
"(",
... | Gets the absolute character index of the line and column
in the continuous string. | [
"Gets",
"the",
"absolute",
"character",
"index",
"of",
"the",
"line",
"and",
"column",
"in",
"the",
"continuous",
"string",
"."
] | python | train |
tensorflow/probability | tensorflow_probability/python/distributions/variational_gaussian_process.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/variational_gaussian_process.py#L728-L842 | def variational_loss(self,
observations,
observation_index_points=None,
kl_weight=1.,
name='variational_loss'):
"""Variational loss for the VGP.
Given `observations` and `observation_index_points`, compute the
negat... | [
"def",
"variational_loss",
"(",
"self",
",",
"observations",
",",
"observation_index_points",
"=",
"None",
",",
"kl_weight",
"=",
"1.",
",",
"name",
"=",
"'variational_loss'",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
"or",
"'variational_gp_loss'",... | Variational loss for the VGP.
Given `observations` and `observation_index_points`, compute the
negative variational lower bound as specified in [Hensman, 2013][1].
Args:
observations: `float` `Tensor` representing collection, or batch of
collections, of observations corresponding to
... | [
"Variational",
"loss",
"for",
"the",
"VGP",
"."
] | python | test |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/identity/identity_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/identity/identity_client.py#L148-L184 | def read_identities(self, descriptors=None, identity_ids=None, subject_descriptors=None, search_filter=None, filter_value=None, query_membership=None, properties=None, include_restricted_visibility=None, options=None):
"""ReadIdentities.
:param str descriptors:
:param str identity_ids:
:... | [
"def",
"read_identities",
"(",
"self",
",",
"descriptors",
"=",
"None",
",",
"identity_ids",
"=",
"None",
",",
"subject_descriptors",
"=",
"None",
",",
"search_filter",
"=",
"None",
",",
"filter_value",
"=",
"None",
",",
"query_membership",
"=",
"None",
",",
... | ReadIdentities.
:param str descriptors:
:param str identity_ids:
:param str subject_descriptors:
:param str search_filter:
:param str filter_value:
:param str query_membership:
:param str properties:
:param bool include_restricted_visibility:
:para... | [
"ReadIdentities",
".",
":",
"param",
"str",
"descriptors",
":",
":",
"param",
"str",
"identity_ids",
":",
":",
"param",
"str",
"subject_descriptors",
":",
":",
"param",
"str",
"search_filter",
":",
":",
"param",
"str",
"filter_value",
":",
":",
"param",
"str... | python | train |
tanghaibao/goatools | goatools/cli/compare_gos.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/compare_gos.py#L129-L135 | def _get_fncsortnt(flds):
"""Return a sort function for sorting header GO IDs found in sections."""
if 'tinfo' in flds:
return lambda ntgo: [ntgo.NS, -1*ntgo.tinfo, ntgo.depth, ntgo.alt]
if 'dcnt' in flds:
return lambda ntgo: [ntgo.NS, -1*ntgo.dcnt, ntgo.depth, ntgo.alt]
... | [
"def",
"_get_fncsortnt",
"(",
"flds",
")",
":",
"if",
"'tinfo'",
"in",
"flds",
":",
"return",
"lambda",
"ntgo",
":",
"[",
"ntgo",
".",
"NS",
",",
"-",
"1",
"*",
"ntgo",
".",
"tinfo",
",",
"ntgo",
".",
"depth",
",",
"ntgo",
".",
"alt",
"]",
"if",
... | Return a sort function for sorting header GO IDs found in sections. | [
"Return",
"a",
"sort",
"function",
"for",
"sorting",
"header",
"GO",
"IDs",
"found",
"in",
"sections",
"."
] | python | train |
tensorlayer/tensorlayer | examples/data_process/tutorial_tfrecord3.py | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/examples/data_process/tutorial_tfrecord3.py#L41-L45 | def _int64_feature_list(values):
"""Wrapper for inserting an int64 FeatureList into a SequenceExample proto,
e.g, sentence in list of ints
"""
return tf.train.FeatureList(feature=[_int64_feature(v) for v in values]) | [
"def",
"_int64_feature_list",
"(",
"values",
")",
":",
"return",
"tf",
".",
"train",
".",
"FeatureList",
"(",
"feature",
"=",
"[",
"_int64_feature",
"(",
"v",
")",
"for",
"v",
"in",
"values",
"]",
")"
] | Wrapper for inserting an int64 FeatureList into a SequenceExample proto,
e.g, sentence in list of ints | [
"Wrapper",
"for",
"inserting",
"an",
"int64",
"FeatureList",
"into",
"a",
"SequenceExample",
"proto",
"e",
".",
"g",
"sentence",
"in",
"list",
"of",
"ints"
] | python | valid |
hermanschaaf/mafan | mafan/third_party/jianfan/__init__.py | https://github.com/hermanschaaf/mafan/blob/373ddf299aeb2bd8413bf921c71768af7a8170ea/mafan/third_party/jianfan/__init__.py#L23-L45 | def _t(unistr, charset_from, charset_to):
"""
This is a unexposed function, is responsibility for translation internal.
"""
# if type(unistr) is str:
# try:
# unistr = unistr.decode('utf-8')
# # Python 3 returns AttributeError when .decode() is called on a str
# #... | [
"def",
"_t",
"(",
"unistr",
",",
"charset_from",
",",
"charset_to",
")",
":",
"# if type(unistr) is str:",
"# try:",
"# unistr = unistr.decode('utf-8')",
"# # Python 3 returns AttributeError when .decode() is called on a str",
"# # This means it is already unicode.",
... | This is a unexposed function, is responsibility for translation internal. | [
"This",
"is",
"a",
"unexposed",
"function",
"is",
"responsibility",
"for",
"translation",
"internal",
"."
] | python | train |
xflr6/bitsets | bitsets/transform.py | https://github.com/xflr6/bitsets/blob/ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf/bitsets/transform.py#L106-L116 | def unpackbools(integers, dtype='L'):
"""Yield booleans unpacking integers of dtype bit-length.
>>> list(unpackbools([42], 'B'))
[False, True, False, True, False, True, False, False]
"""
atoms = ATOMS[dtype]
for chunk in integers:
for a in atoms:
yield not not chunk & a | [
"def",
"unpackbools",
"(",
"integers",
",",
"dtype",
"=",
"'L'",
")",
":",
"atoms",
"=",
"ATOMS",
"[",
"dtype",
"]",
"for",
"chunk",
"in",
"integers",
":",
"for",
"a",
"in",
"atoms",
":",
"yield",
"not",
"not",
"chunk",
"&",
"a"
] | Yield booleans unpacking integers of dtype bit-length.
>>> list(unpackbools([42], 'B'))
[False, True, False, True, False, True, False, False] | [
"Yield",
"booleans",
"unpacking",
"integers",
"of",
"dtype",
"bit",
"-",
"length",
"."
] | python | train |
OSSOS/MOP | src/ossos/core/ossos/planning/obs_planner.py | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/planning/obs_planner.py#L893-L1058 | def save_pointings(self):
"""Print the currently defined FOVs"""
i = 0
if self.pointing_format.get() in ['GEMINI ET', 'CFHT ET', 'CFHT API']:
logging.info('Beginning table pointing save.')
for pointing in self.pointings:
name = pointing["label"]["text"]
... | [
"def",
"save_pointings",
"(",
"self",
")",
":",
"i",
"=",
"0",
"if",
"self",
".",
"pointing_format",
".",
"get",
"(",
")",
"in",
"[",
"'GEMINI ET'",
",",
"'CFHT ET'",
",",
"'CFHT API'",
"]",
":",
"logging",
".",
"info",
"(",
"'Beginning table pointing save... | Print the currently defined FOVs | [
"Print",
"the",
"currently",
"defined",
"FOVs"
] | python | train |
sdispater/cleo | cleo/commands/command.py | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L112-L122 | def call_silent(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, NullIO()) | [
"def",
"call_silent",
"(",
"self",
",",
"name",
",",
"args",
"=",
"None",
")",
":",
"# type: (str, Optional[str]) -> int",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"\"\"",
"args",
"=",
"StringArgs",
"(",
"args",
")",
"command",
"=",
"self",
".",
"ap... | Call another command. | [
"Call",
"another",
"command",
"."
] | python | train |
databio/pypiper | pypiper/utils.py | https://github.com/databio/pypiper/blob/00e6c2b94033c4187d47ff14c5580bbfc2ff097f/pypiper/utils.py#L459-L480 | def parse_cores(cores, pm, default):
"""
Framework to finalize number of cores for an operation.
Some calls to a function may directly provide a desired number of cores,
others may not. Similarly, some pipeline managers may define a cores count
while others will not. This utility provides a single ... | [
"def",
"parse_cores",
"(",
"cores",
",",
"pm",
",",
"default",
")",
":",
"cores",
"=",
"cores",
"or",
"getattr",
"(",
"pm",
",",
"\"cores\"",
",",
"default",
")",
"return",
"int",
"(",
"cores",
")"
] | Framework to finalize number of cores for an operation.
Some calls to a function may directly provide a desired number of cores,
others may not. Similarly, some pipeline managers may define a cores count
while others will not. This utility provides a single via which the
count of cores to use for an op... | [
"Framework",
"to",
"finalize",
"number",
"of",
"cores",
"for",
"an",
"operation",
"."
] | python | train |
geomet/geomet | geomet/wkt.py | https://github.com/geomet/geomet/blob/b82d7118113ab723751eba3de5df98c368423c2b/geomet/wkt.py#L236-L250 | def _dump_polygon(obj, decimals):
"""
Dump a GeoJSON-like Polygon object to WKT.
Input parameters and return value are the POLYGON equivalent to
:func:`_dump_point`.
"""
coords = obj['coordinates']
poly = 'POLYGON (%s)'
rings = (', '.join(' '.join(_round_and_pad(c, decimals)
... | [
"def",
"_dump_polygon",
"(",
"obj",
",",
"decimals",
")",
":",
"coords",
"=",
"obj",
"[",
"'coordinates'",
"]",
"poly",
"=",
"'POLYGON (%s)'",
"rings",
"=",
"(",
"', '",
".",
"join",
"(",
"' '",
".",
"join",
"(",
"_round_and_pad",
"(",
"c",
",",
"decim... | Dump a GeoJSON-like Polygon object to WKT.
Input parameters and return value are the POLYGON equivalent to
:func:`_dump_point`. | [
"Dump",
"a",
"GeoJSON",
"-",
"like",
"Polygon",
"object",
"to",
"WKT",
"."
] | python | train |
resync/resync | resync/client.py | https://github.com/resync/resync/blob/98292c17b2c00f2d6f5191c6ab51fef8c292a018/resync/client.py#L74-L84 | def sitemap_uri(self, basename):
"""Get full URI (filepath) for sitemap based on basename."""
if (re.match(r"\w+:", basename)):
# looks like URI
return(basename)
elif (re.match(r"/", basename)):
# looks like full path
return(basename)
else:... | [
"def",
"sitemap_uri",
"(",
"self",
",",
"basename",
")",
":",
"if",
"(",
"re",
".",
"match",
"(",
"r\"\\w+:\"",
",",
"basename",
")",
")",
":",
"# looks like URI",
"return",
"(",
"basename",
")",
"elif",
"(",
"re",
".",
"match",
"(",
"r\"/\"",
",",
"... | Get full URI (filepath) for sitemap based on basename. | [
"Get",
"full",
"URI",
"(",
"filepath",
")",
"for",
"sitemap",
"based",
"on",
"basename",
"."
] | python | train |
dhylands/rshell | rshell/main.py | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1489-L1496 | def remote_eval_last(self, func, *args, **kwargs):
"""Calls func with the indicated args on the micropython board, and
converts the response back into python by using eval.
"""
result = self.remote(func, *args, **kwargs).split(b'\r\n')
messages = result[0:-2]
messages ... | [
"def",
"remote_eval_last",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"self",
".",
"remote",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
".",
"split",
"(",
"b'\\r\\n'",
")",
"mes... | Calls func with the indicated args on the micropython board, and
converts the response back into python by using eval. | [
"Calls",
"func",
"with",
"the",
"indicated",
"args",
"on",
"the",
"micropython",
"board",
"and",
"converts",
"the",
"response",
"back",
"into",
"python",
"by",
"using",
"eval",
"."
] | python | train |
graphql-python/graphql-core-next | graphql/execution/execute.py | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/execute.py#L306-L327 | def build_response(
self, data: AwaitableOrValue[Optional[Dict[str, Any]]]
) -> AwaitableOrValue[ExecutionResult]:
"""Build response.
Given a completed execution context and data, build the (data, errors) response
defined by the "Response" section of the GraphQL spec.
"""
... | [
"def",
"build_response",
"(",
"self",
",",
"data",
":",
"AwaitableOrValue",
"[",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
"]",
")",
"->",
"AwaitableOrValue",
"[",
"ExecutionResult",
"]",
":",
"if",
"isawaitable",
"(",
"data",
")",
":",
... | Build response.
Given a completed execution context and data, build the (data, errors) response
defined by the "Response" section of the GraphQL spec. | [
"Build",
"response",
"."
] | python | train |
raiden-network/raiden | raiden/transfer/node.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/node.py#L1183-L1232 | def is_transaction_invalidated(transaction, state_change):
""" True if the `transaction` is made invalid by `state_change`.
Some transactions will fail due to race conditions. The races are:
- Another transaction which has the same side effect is executed before.
- Another transaction which *invalidat... | [
"def",
"is_transaction_invalidated",
"(",
"transaction",
",",
"state_change",
")",
":",
"# Most transactions cannot be invalidated by others. These are:",
"#",
"# - close transactions",
"# - settle transactions",
"# - batch unlocks",
"#",
"# Deposits and withdraws are invalidated by the ... | True if the `transaction` is made invalid by `state_change`.
Some transactions will fail due to race conditions. The races are:
- Another transaction which has the same side effect is executed before.
- Another transaction which *invalidates* the state of the smart contract
required by the local trans... | [
"True",
"if",
"the",
"transaction",
"is",
"made",
"invalid",
"by",
"state_change",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/assessment/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/sessions.py#L9180-L9196 | def get_child_bank_ids(self, bank_id):
"""Gets the child ``Ids`` of the given bank.
arg: bank_id (osid.id.Id): the ``Id`` to query
return: (osid.id.IdList) - the children of the bank
raise: NotFound - ``bank_id`` is not found
raise: NullArgument - ``bank_id`` is ``null``
... | [
"def",
"get_child_bank_ids",
"(",
"self",
",",
"bank_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.get_child_bin_ids",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_session",
".",... | Gets the child ``Ids`` of the given bank.
arg: bank_id (osid.id.Id): the ``Id`` to query
return: (osid.id.IdList) - the children of the bank
raise: NotFound - ``bank_id`` is not found
raise: NullArgument - ``bank_id`` is ``null``
raise: OperationFailed - unable to complete... | [
"Gets",
"the",
"child",
"Ids",
"of",
"the",
"given",
"bank",
"."
] | python | train |
datasift/datasift-python | datasift/historics.py | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/historics.py#L160-L176 | def pause(self, historics_id, reason=""):
""" Pause an existing Historics query.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicspause
:param historics_id: id of the job to pause
:type historics_id: str
:param reason: optional... | [
"def",
"pause",
"(",
"self",
",",
"historics_id",
",",
"reason",
"=",
"\"\"",
")",
":",
"params",
"=",
"{",
"\"id\"",
":",
"historics_id",
"}",
"if",
"reason",
"!=",
"\"\"",
":",
"params",
"[",
"\"reason\"",
"]",
"=",
"reason",
"return",
"self",
".",
... | Pause an existing Historics query.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicspause
:param historics_id: id of the job to pause
:type historics_id: str
:param reason: optional reason for pausing it
:type reason: str
... | [
"Pause",
"an",
"existing",
"Historics",
"query",
"."
] | python | train |
rckclmbr/pyportify | pyportify/pkcs1/primitives.py | https://github.com/rckclmbr/pyportify/blob/696a1caad8a47b191f3bec44cc8fc3c437779512/pyportify/pkcs1/primitives.py#L121-L126 | def constant_time_cmp(a, b):
'''Compare two strings using constant time.'''
result = True
for x, y in zip(a, b):
result &= (x == y)
return result | [
"def",
"constant_time_cmp",
"(",
"a",
",",
"b",
")",
":",
"result",
"=",
"True",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"a",
",",
"b",
")",
":",
"result",
"&=",
"(",
"x",
"==",
"y",
")",
"return",
"result"
] | Compare two strings using constant time. | [
"Compare",
"two",
"strings",
"using",
"constant",
"time",
"."
] | python | train |
OzymandiasTheGreat/python-libinput | libinput/device.py | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/device.py#L1800-L1811 | def capabilities(self):
"""A tuple of capabilities this device supports.
Returns:
(~libinput.constant.DeviceCapability): Device capabilities.
"""
caps = []
for cap in DeviceCapability:
if self._libinput.libinput_device_has_capability(self._handle, cap):
caps.append(cap)
return tuple(caps) | [
"def",
"capabilities",
"(",
"self",
")",
":",
"caps",
"=",
"[",
"]",
"for",
"cap",
"in",
"DeviceCapability",
":",
"if",
"self",
".",
"_libinput",
".",
"libinput_device_has_capability",
"(",
"self",
".",
"_handle",
",",
"cap",
")",
":",
"caps",
".",
"appe... | A tuple of capabilities this device supports.
Returns:
(~libinput.constant.DeviceCapability): Device capabilities. | [
"A",
"tuple",
"of",
"capabilities",
"this",
"device",
"supports",
"."
] | python | train |
ralphbean/taskw | taskw/task.py | https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/task.py#L149-L191 | def get_changes(self, serialized=False, keep=False):
""" Get a journal of changes that have occurred
:param `serialized`:
Return changes in the serialized format used by TaskWarrior.
:param `keep_changes`:
By default, the list of changes is reset after running
... | [
"def",
"get_changes",
"(",
"self",
",",
"serialized",
"=",
"False",
",",
"keep",
"=",
"False",
")",
":",
"results",
"=",
"{",
"}",
"# Check for explicitly-registered changes",
"for",
"k",
",",
"f",
",",
"t",
"in",
"self",
".",
"_changes",
":",
"if",
"k",... | Get a journal of changes that have occurred
:param `serialized`:
Return changes in the serialized format used by TaskWarrior.
:param `keep_changes`:
By default, the list of changes is reset after running
``.get_changes``; set this to `True` if you would like to
... | [
"Get",
"a",
"journal",
"of",
"changes",
"that",
"have",
"occurred"
] | python | train |
datastore/datastore | datastore/core/basic.py | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L932-L954 | def delete(self, key):
'''Removes the object named by `key`.
DirectoryTreeDatastore removes the directory entry.
'''
super(DirectoryTreeDatastore, self).delete(key)
str_key = str(key)
# ignore root
if str_key == '/':
return
# retrieve directory, to remove entry
dir_key = ... | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"super",
"(",
"DirectoryTreeDatastore",
",",
"self",
")",
".",
"delete",
"(",
"key",
")",
"str_key",
"=",
"str",
"(",
"key",
")",
"# ignore root",
"if",
"str_key",
"==",
"'/'",
":",
"return",
"# retri... | Removes the object named by `key`.
DirectoryTreeDatastore removes the directory entry. | [
"Removes",
"the",
"object",
"named",
"by",
"key",
".",
"DirectoryTreeDatastore",
"removes",
"the",
"directory",
"entry",
"."
] | python | train |
KelSolaar/Umbra | umbra/managers/layouts_manager.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/managers/layouts_manager.py#L476-L489 | def restore_startup_layout(self):
"""
Restores the startup layout.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Restoring startup layout.")
if self.restore_layout(UiConstants.startup_layout):
not self.__restore_geometry_on_layout_change... | [
"def",
"restore_startup_layout",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Restoring startup layout.\"",
")",
"if",
"self",
".",
"restore_layout",
"(",
"UiConstants",
".",
"startup_layout",
")",
":",
"not",
"self",
".",
"__restore_geometry_on_layout_c... | Restores the startup layout.
:return: Method success.
:rtype: bool | [
"Restores",
"the",
"startup",
"layout",
"."
] | python | train |
pyroscope/pyrocore | src/pyrocore/torrent/queue.py | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/queue.py#L63-L132 | def _start(self, items):
""" Start some items if conditions are met.
"""
# TODO: Filter by a custom date field, for scheduled downloads starting at a certain time, or after a given delay
# TODO: Don't start anything more if download BW is used >= config threshold in %
# Check i... | [
"def",
"_start",
"(",
"self",
",",
"items",
")",
":",
"# TODO: Filter by a custom date field, for scheduled downloads starting at a certain time, or after a given delay",
"# TODO: Don't start anything more if download BW is used >= config threshold in %",
"# Check if anything more is ready to st... | Start some items if conditions are met. | [
"Start",
"some",
"items",
"if",
"conditions",
"are",
"met",
"."
] | 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#L685-L704 | def _send_command(self, cmd_class, command, payload, timeout=3.0):
"""
Send a BGAPI packet to the dongle and return the response
"""
if len(payload) > 60:
return ValueError("Attempting to send a BGAPI packet with length > 60 is not allowed", actual_length=len(payload), comma... | [
"def",
"_send_command",
"(",
"self",
",",
"cmd_class",
",",
"command",
",",
"payload",
",",
"timeout",
"=",
"3.0",
")",
":",
"if",
"len",
"(",
"payload",
")",
">",
"60",
":",
"return",
"ValueError",
"(",
"\"Attempting to send a BGAPI packet with length > 60 is n... | Send a BGAPI packet to the dongle and return the response | [
"Send",
"a",
"BGAPI",
"packet",
"to",
"the",
"dongle",
"and",
"return",
"the",
"response"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.