repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
wummel/patool | patoolib/programs/py_echo.py | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_echo.py#L34-L36 | def list_ape (archive, compression, cmd, verbosity, interactive):
"""List an APE archive."""
return stripext(cmd, archive, verbosity, extension=".wav") | [
"def",
"list_ape",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
")",
":",
"return",
"stripext",
"(",
"cmd",
",",
"archive",
",",
"verbosity",
",",
"extension",
"=",
"\".wav\"",
")"
] | List an APE archive. | [
"List",
"an",
"APE",
"archive",
"."
] | python | train | 52.333333 |
apache/incubator-mxnet | example/ssd/evaluate/eval_metric.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/evaluate/eval_metric.py#L227-L254 | def _average_precision(self, rec, prec):
"""
calculate average precision
Params:
----------
rec : numpy.array
cumulated recall
prec : numpy.array
cumulated precision
Returns:
----------
ap as float
"""
# app... | [
"def",
"_average_precision",
"(",
"self",
",",
"rec",
",",
"prec",
")",
":",
"# append sentinel values at both ends",
"mrec",
"=",
"np",
".",
"concatenate",
"(",
"(",
"[",
"0.",
"]",
",",
"rec",
",",
"[",
"1.",
"]",
")",
")",
"mpre",
"=",
"np",
".",
... | calculate average precision
Params:
----------
rec : numpy.array
cumulated recall
prec : numpy.array
cumulated precision
Returns:
----------
ap as float | [
"calculate",
"average",
"precision"
] | python | train | 27.857143 |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L312-L333 | def augment_initial_layout(self, base_response, initial_arguments=None):
'Add application state to initial values'
if self.use_dash_layout() and not initial_arguments and False:
return base_response.data, base_response.mimetype
# Adjust the base layout response
baseDataInByt... | [
"def",
"augment_initial_layout",
"(",
"self",
",",
"base_response",
",",
"initial_arguments",
"=",
"None",
")",
":",
"if",
"self",
".",
"use_dash_layout",
"(",
")",
"and",
"not",
"initial_arguments",
"and",
"False",
":",
"return",
"base_response",
".",
"data",
... | Add application state to initial values | [
"Add",
"application",
"state",
"to",
"initial",
"values"
] | python | train | 43.136364 |
dacut/python-aws-sig | awssig/sigv4.py | https://github.com/dacut/python-aws-sig/blob/7f6054dca4b32e67ca3d39db31c1b4be5efe54bd/awssig/sigv4.py#L354-L383 | def verify(self):
"""
Verifies that the request timestamp is not beyond our allowable
timestamp mismatch and that the request signature matches our
expectations.
"""
try:
if self.timestamp_mismatch is not None:
m = _iso8601_timestamp_regex.matc... | [
"def",
"verify",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"timestamp_mismatch",
"is",
"not",
"None",
":",
"m",
"=",
"_iso8601_timestamp_regex",
".",
"match",
"(",
"self",
".",
"request_timestamp",
")",
"year",
"=",
"int",
"(",
"m",
".",
"g... | Verifies that the request timestamp is not beyond our allowable
timestamp mismatch and that the request signature matches our
expectations. | [
"Verifies",
"that",
"the",
"request",
"timestamp",
"is",
"not",
"beyond",
"our",
"allowable",
"timestamp",
"mismatch",
"and",
"that",
"the",
"request",
"signature",
"matches",
"our",
"expectations",
"."
] | python | train | 41.1 |
casacore/python-casacore | casacore/tables/tablecolumn.py | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/tablecolumn.py#L169-L172 | def putcolslice(self, value, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1):
"""Put into a slice in a table column holding arrays.
(see :func:`table.putcolslice`)"""
return self._table.putcolslice(self._column, value, blc, trc, inc, startrow, nrow, rowincr) | [
"def",
"putcolslice",
"(",
"self",
",",
"value",
",",
"blc",
",",
"trc",
",",
"inc",
"=",
"[",
"]",
",",
"startrow",
"=",
"0",
",",
"nrow",
"=",
"-",
"1",
",",
"rowincr",
"=",
"1",
")",
":",
"return",
"self",
".",
"_table",
".",
"putcolslice",
... | Put into a slice in a table column holding arrays.
(see :func:`table.putcolslice`) | [
"Put",
"into",
"a",
"slice",
"in",
"a",
"table",
"column",
"holding",
"arrays",
".",
"(",
"see",
":",
"func",
":",
"table",
".",
"putcolslice",
")"
] | python | train | 70.25 |
jbeluch/xbmcswift2 | xbmcswift2/xbmcmixin.py | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/xbmcmixin.py#L420-L434 | def end_of_directory(self, succeeded=True, update_listing=False,
cache_to_disc=True):
'''Wrapper for xbmcplugin.endOfDirectory. Records state in
self._end_of_directory.
Typically it is not necessary to call this method directly, as
calling :meth:`~xbmcswift2.Plu... | [
"def",
"end_of_directory",
"(",
"self",
",",
"succeeded",
"=",
"True",
",",
"update_listing",
"=",
"False",
",",
"cache_to_disc",
"=",
"True",
")",
":",
"self",
".",
"_update_listing",
"=",
"update_listing",
"if",
"not",
"self",
".",
"_end_of_directory",
":",
... | Wrapper for xbmcplugin.endOfDirectory. Records state in
self._end_of_directory.
Typically it is not necessary to call this method directly, as
calling :meth:`~xbmcswift2.Plugin.finish` will call this method. | [
"Wrapper",
"for",
"xbmcplugin",
".",
"endOfDirectory",
".",
"Records",
"state",
"in",
"self",
".",
"_end_of_directory",
"."
] | python | train | 48.133333 |
DecBayComp/RWA-python | rwa/generic.py | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L677-L697 | def peek_assoc(store, container, _stack=None):
"""
Deserialize association lists.
"""
assoc = []
try:
if store.getRecordAttr('key', container) == 'escaped':
for i in container:
assoc.append(store.peek(i, container, _stack=_stack))
else:
for i i... | [
"def",
"peek_assoc",
"(",
"store",
",",
"container",
",",
"_stack",
"=",
"None",
")",
":",
"assoc",
"=",
"[",
"]",
"try",
":",
"if",
"store",
".",
"getRecordAttr",
"(",
"'key'",
",",
"container",
")",
"==",
"'escaped'",
":",
"for",
"i",
"in",
"contai... | Deserialize association lists. | [
"Deserialize",
"association",
"lists",
"."
] | python | train | 33.809524 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/signals.py | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/signals.py#L35-L73 | def notify_observers(table, kind, primary_key=None):
"""Transmit ORM table change notification.
:param table: Name of the table that has changed
:param kind: Change type
:param primary_key: Primary key of the affected instance
"""
if IN_MIGRATIONS:
return
# Don't propagate events ... | [
"def",
"notify_observers",
"(",
"table",
",",
"kind",
",",
"primary_key",
"=",
"None",
")",
":",
"if",
"IN_MIGRATIONS",
":",
"return",
"# Don't propagate events when there are no observers to receive them.",
"if",
"not",
"Observer",
".",
"objects",
".",
"filter",
"(",... | Transmit ORM table change notification.
:param table: Name of the table that has changed
:param kind: Change type
:param primary_key: Primary key of the affected instance | [
"Transmit",
"ORM",
"table",
"change",
"notification",
"."
] | python | train | 31.410256 |
quantmind/pulsar | pulsar/async/monitor.py | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/monitor.py#L102-L143 | def manage_actor(self, monitor, actor, stop=False):
'''If an actor failed to notify itself to the arbiter for more than
the timeout, stop the actor.
:param actor: the :class:`Actor` to manage.
:param stop: if ``True``, stop the actor.
:return: if the actor is alive 0 if it is no... | [
"def",
"manage_actor",
"(",
"self",
",",
"monitor",
",",
"actor",
",",
"stop",
"=",
"False",
")",
":",
"if",
"not",
"monitor",
".",
"is_running",
"(",
")",
":",
"stop",
"=",
"True",
"if",
"not",
"actor",
".",
"is_alive",
"(",
")",
":",
"if",
"not",... | If an actor failed to notify itself to the arbiter for more than
the timeout, stop the actor.
:param actor: the :class:`Actor` to manage.
:param stop: if ``True``, stop the actor.
:return: if the actor is alive 0 if it is not. | [
"If",
"an",
"actor",
"failed",
"to",
"notify",
"itself",
"to",
"the",
"arbiter",
"for",
"more",
"than",
"the",
"timeout",
"stop",
"the",
"actor",
"."
] | python | train | 41.333333 |
ejhigson/nestcheck | nestcheck/pandas_functions.py | https://github.com/ejhigson/nestcheck/blob/29151c314deb89746fd674f27f6ce54b77603189/nestcheck/pandas_functions.py#L12-L36 | def summary_df_from_array(results_array, names, axis=0, **kwargs):
"""Make a panda data frame of the mean and std devs of an array of results,
including the uncertainties on the values.
This function converts the array to a DataFrame and calls summary_df on it.
Parameters
----------
results_ar... | [
"def",
"summary_df_from_array",
"(",
"results_array",
",",
"names",
",",
"axis",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"axis",
"==",
"0",
"or",
"axis",
"==",
"1",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"results_array",
")",
"if",
"a... | Make a panda data frame of the mean and std devs of an array of results,
including the uncertainties on the values.
This function converts the array to a DataFrame and calls summary_df on it.
Parameters
----------
results_array: 2d numpy array
names: list of str
Names for the output df... | [
"Make",
"a",
"panda",
"data",
"frame",
"of",
"the",
"mean",
"and",
"std",
"devs",
"of",
"an",
"array",
"of",
"results",
"including",
"the",
"uncertainties",
"on",
"the",
"values",
"."
] | python | train | 29.56 |
ArduPilot/MAVProxy | MAVProxy/modules/lib/MacOS/wxversion.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/MacOS/wxversion.py#L235-L251 | def checkInstalled(versions, optionsRequired=False):
"""
Check if there is a version of wxPython installed that matches one
of the versions given. Returns True if so, False if not. This
can be used to determine if calling `select` will succeed or not.
:param versions: Same as in `select`, eit... | [
"def",
"checkInstalled",
"(",
"versions",
",",
"optionsRequired",
"=",
"False",
")",
":",
"if",
"type",
"(",
"versions",
")",
"==",
"str",
":",
"versions",
"=",
"[",
"versions",
"]",
"installed",
"=",
"_find_installed",
"(",
")",
"bestMatch",
"=",
"_get_be... | Check if there is a version of wxPython installed that matches one
of the versions given. Returns True if so, False if not. This
can be used to determine if calling `select` will succeed or not.
:param versions: Same as in `select`, either a string or a list
of strings specifying the vers... | [
"Check",
"if",
"there",
"is",
"a",
"version",
"of",
"wxPython",
"installed",
"that",
"matches",
"one",
"of",
"the",
"versions",
"given",
".",
"Returns",
"True",
"if",
"so",
"False",
"if",
"not",
".",
"This",
"can",
"be",
"used",
"to",
"determine",
"if",
... | python | train | 38.411765 |
DLR-RM/RAFCON | source/rafcon/core/state_machine_manager.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/state_machine_manager.py#L81-L84 | def reset_dirty_flags(self):
"""Set all marked_dirty flags of the state machine to false."""
for sm_id, sm in self.state_machines.items():
sm.marked_dirty = False | [
"def",
"reset_dirty_flags",
"(",
"self",
")",
":",
"for",
"sm_id",
",",
"sm",
"in",
"self",
".",
"state_machines",
".",
"items",
"(",
")",
":",
"sm",
".",
"marked_dirty",
"=",
"False"
] | Set all marked_dirty flags of the state machine to false. | [
"Set",
"all",
"marked_dirty",
"flags",
"of",
"the",
"state",
"machine",
"to",
"false",
"."
] | python | train | 46.75 |
push-things/django-th | django_th/services/services.py | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/django_th/services/services.py#L196-L216 | def callback_oauth1(self, request, **kwargs):
"""
Process for oAuth 1
:param request: contains the current session
:param kwargs: keyword args
:type request: dict
:type kwargs: dict
:rtype: string
"""
if kwargs.get('access_t... | [
"def",
"callback_oauth1",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"'access_token'",
")",
"==",
"''",
"or",
"kwargs",
".",
"get",
"(",
"'access_token'",
")",
"is",
"None",
":",
"access_token",
"="... | Process for oAuth 1
:param request: contains the current session
:param kwargs: keyword args
:type request: dict
:type kwargs: dict
:rtype: string | [
"Process",
"for",
"oAuth",
"1",
":",
"param",
"request",
":",
"contains",
"the",
"current",
"session",
":",
"param",
"kwargs",
":",
"keyword",
"args",
":",
"type",
"request",
":",
"dict",
":",
"type",
"kwargs",
":",
"dict",
":",
"rtype",
":",
"string"
] | python | train | 42.761905 |
peopledoc/workalendar | workalendar/core.py | https://github.com/peopledoc/workalendar/blob/d044d5dfc1709ec388db34dab583dd554cc66c4e/workalendar/core.py#L789-L817 | def get_islamic_holidays(self):
"""Return a list of Islamic (month, day, label) for islamic holidays.
Please take note that these dates must be expressed using the Islamic
Calendar"""
days = list(super(IslamicMixin, self).get_islamic_holidays())
if self.include_islamic_new_year:... | [
"def",
"get_islamic_holidays",
"(",
"self",
")",
":",
"days",
"=",
"list",
"(",
"super",
"(",
"IslamicMixin",
",",
"self",
")",
".",
"get_islamic_holidays",
"(",
")",
")",
"if",
"self",
".",
"include_islamic_new_year",
":",
"days",
".",
"append",
"(",
"(",... | Return a list of Islamic (month, day, label) for islamic holidays.
Please take note that these dates must be expressed using the Islamic
Calendar | [
"Return",
"a",
"list",
"of",
"Islamic",
"(",
"month",
"day",
"label",
")",
"for",
"islamic",
"holidays",
".",
"Please",
"take",
"note",
"that",
"these",
"dates",
"must",
"be",
"expressed",
"using",
"the",
"Islamic",
"Calendar"
] | python | train | 50 |
wharris/dougrain | dougrain/document.py | https://github.com/wharris/dougrain/blob/45062a1562fc34793e40c6253a93aa91eb4cf855/dougrain/document.py#L445-L502 | def add_link(self, rel, target, wrap=False, **kwargs):
"""Adds a link to the document.
Calling code should use this method to add links instead of
modifying ``links`` directly.
This method adds a link to the given ``target`` to the document with
the given ``rel``. If one or mor... | [
"def",
"add_link",
"(",
"self",
",",
"rel",
",",
"target",
",",
"wrap",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"target",
",",
"'as_link'",
")",
":",
"link",
"=",
"target",
".",
"as_link",
"(",
")",
"else",
":",
"li... | Adds a link to the document.
Calling code should use this method to add links instead of
modifying ``links`` directly.
This method adds a link to the given ``target`` to the document with
the given ``rel``. If one or more links are already present for that
link relationship typ... | [
"Adds",
"a",
"link",
"to",
"the",
"document",
"."
] | python | train | 39.275862 |
mitsei/dlkit | dlkit/json_/learning/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/learning/sessions.py#L6284-L6304 | def get_child_objective_banks(self, objective_bank_id):
"""Gets the children of the given objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` to query
return: (osid.learning.ObjectiveBankList) - the children of the
objective bank
raise: NotFound - ``objec... | [
"def",
"get_child_objective_banks",
"(",
"self",
",",
"objective_bank_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.get_child_bins",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_se... | Gets the children of the given objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` to query
return: (osid.learning.ObjectiveBankList) - the children of the
objective bank
raise: NotFound - ``objective_bank_id`` is not found
raise: NullArgument - ``object... | [
"Gets",
"the",
"children",
"of",
"the",
"given",
"objective",
"bank",
"."
] | python | train | 48.809524 |
maaku/python-bitcoin | bitcoin/authtree.py | https://github.com/maaku/python-bitcoin/blob/1b80c284170fd3f547cc45f4700ce169f3f99641/bitcoin/authtree.py#L429-L440 | def _forward_iterator(self):
"Returns a forward iterator over the trie"
path = [(self, 0, Bits())]
while path:
node, idx, prefix = path.pop()
if idx==0 and node.value is not None and not node.prune_value:
yield (self._unpickle_key(prefix), self._unpickle_v... | [
"def",
"_forward_iterator",
"(",
"self",
")",
":",
"path",
"=",
"[",
"(",
"self",
",",
"0",
",",
"Bits",
"(",
")",
")",
"]",
"while",
"path",
":",
"node",
",",
"idx",
",",
"prefix",
"=",
"path",
".",
"pop",
"(",
")",
"if",
"idx",
"==",
"0",
"... | Returns a forward iterator over the trie | [
"Returns",
"a",
"forward",
"iterator",
"over",
"the",
"trie"
] | python | train | 47 |
trailofbits/manticore | manticore/native/cpu/x86.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L2143-L2155 | def CMOVAE(cpu, dest, src):
"""
Conditional move - Above or equal/not below.
Tests the status flags in the EFLAGS register and moves the source operand
(second operand) to the destination operand (first operand) if the given
test condition is true.
:param cpu: current C... | [
"def",
"CMOVAE",
"(",
"cpu",
",",
"dest",
",",
"src",
")",
":",
"dest",
".",
"write",
"(",
"Operators",
".",
"ITEBV",
"(",
"dest",
".",
"size",
",",
"cpu",
".",
"CF",
"==",
"False",
",",
"src",
".",
"read",
"(",
")",
",",
"dest",
".",
"read",
... | Conditional move - Above or equal/not below.
Tests the status flags in the EFLAGS register and moves the source operand
(second operand) to the destination operand (first operand) if the given
test condition is true.
:param cpu: current CPU.
:param dest: destination operand.
... | [
"Conditional",
"move",
"-",
"Above",
"or",
"equal",
"/",
"not",
"below",
"."
] | python | valid | 37.692308 |
HumanBrainProject/hbp-service-client | hbp_service_client/storage_service/client.py | https://github.com/HumanBrainProject/hbp-service-client/blob/b338fb41a7f0e7b9d654ff28fcf13a56d03bff4d/hbp_service_client/storage_service/client.py#L145-L165 | def get_parent(self, path):
'''Get the parent entity of the entity pointed by the given path.
Args:
path (str): The path of the entity whose parent is needed
Returns:
A JSON object of the parent entity if found.
Raises:
StorageArgumentException: Inv... | [
"def",
"get_parent",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"__validate_storage_path",
"(",
"path",
",",
"projects_allowed",
"=",
"False",
")",
"path_steps",
"=",
"[",
"step",
"for",
"step",
"in",
"path",
".",
"split",
"(",
"'/'",
")",
"if",
... | Get the parent entity of the entity pointed by the given path.
Args:
path (str): The path of the entity whose parent is needed
Returns:
A JSON object of the parent entity if found.
Raises:
StorageArgumentException: Invalid arguments
StorageForbi... | [
"Get",
"the",
"parent",
"entity",
"of",
"the",
"entity",
"pointed",
"by",
"the",
"given",
"path",
"."
] | python | test | 37.857143 |
pycontribs/pyrax | pyrax/base_identity.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/base_identity.py#L382-L408 | def get_client(self, service, region, public=True, cached=True,
client_class=None):
"""
Returns the client object for the specified service and region.
By default the public endpoint is used. If you wish to work with a
services internal endpoints, specify `public=False`.
... | [
"def",
"get_client",
"(",
"self",
",",
"service",
",",
"region",
",",
"public",
"=",
"True",
",",
"cached",
"=",
"True",
",",
"client_class",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"authenticated",
":",
"raise",
"exc",
".",
"NotAuthenticated",
... | Returns the client object for the specified service and region.
By default the public endpoint is used. If you wish to work with a
services internal endpoints, specify `public=False`.
By default, if a client has already been created for the given service,
region, and public values, tha... | [
"Returns",
"the",
"client",
"object",
"for",
"the",
"specified",
"service",
"and",
"region",
"."
] | python | train | 43.62963 |
BoboTiG/python-mss | mss/windows.py | https://github.com/BoboTiG/python-mss/blob/56347f781edb38a0e7a5104080bd683f49c6f074/mss/windows.py#L222-L293 | def grab(self, monitor):
# type: (Monitor) -> ScreenShot
""" Retrieve all pixels from a monitor. Pixels have to be RGB.
In the code, there are few interesting things:
[1] bmi.bmiHeader.biHeight = -height
A bottom-up DIB is specified by setting the height to a
... | [
"def",
"grab",
"(",
"self",
",",
"monitor",
")",
":",
"# type: (Monitor) -> ScreenShot",
"# Convert PIL bbox style",
"if",
"isinstance",
"(",
"monitor",
",",
"tuple",
")",
":",
"monitor",
"=",
"{",
"\"left\"",
":",
"monitor",
"[",
"0",
"]",
",",
"\"top\"",
"... | Retrieve all pixels from a monitor. Pixels have to be RGB.
In the code, there are few interesting things:
[1] bmi.bmiHeader.biHeight = -height
A bottom-up DIB is specified by setting the height to a
positive number, while a top-down DIB is specified by
sett... | [
"Retrieve",
"all",
"pixels",
"from",
"a",
"monitor",
".",
"Pixels",
"have",
"to",
"be",
"RGB",
"."
] | python | train | 36.208333 |
taskcluster/taskcluster-client.py | taskcluster/awsprovisioner.py | https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/awsprovisioner.py#L284-L296 | def state(self, *args, **kwargs):
"""
Get AWS State for a worker type
Return the state of a given workertype as stored by the provisioner.
This state is stored as three lists: 1 for running instances, 1 for
pending requests. The `summary` property contains an updated summary
... | [
"def",
"state",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"state\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Get AWS State for a worker type
Return the state of a given workertype as stored by the provisioner.
This state is stored as three lists: 1 for running instances, 1 for
pending requests. The `summary` property contains an updated summary
similar to that returned from `listWorkerTypeSum... | [
"Get",
"AWS",
"State",
"for",
"a",
"worker",
"type"
] | python | train | 37.846154 |
wiheto/teneto | teneto/classes/bids.py | https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/classes/bids.py#L164-L219 | def derive_temporalnetwork(self, params, update_pipeline=True, tag=None, njobs=1, confound_corr_report=True):
"""
Derive time-varying connectivity on the selected files.
Parameters
----------
params : dict.
See teneto.timeseries.derive_temporalnetwork for the structu... | [
"def",
"derive_temporalnetwork",
"(",
"self",
",",
"params",
",",
"update_pipeline",
"=",
"True",
",",
"tag",
"=",
"None",
",",
"njobs",
"=",
"1",
",",
"confound_corr_report",
"=",
"True",
")",
":",
"if",
"not",
"njobs",
":",
"njobs",
"=",
"self",
".",
... | Derive time-varying connectivity on the selected files.
Parameters
----------
params : dict.
See teneto.timeseries.derive_temporalnetwork for the structure of the param dictionary. Assumes dimord is time,node (output of other TenetoBIDS funcitons)
update_pipeline : bool
... | [
"Derive",
"time",
"-",
"varying",
"connectivity",
"on",
"the",
"selected",
"files",
"."
] | python | train | 38.142857 |
quantmind/pulsar | pulsar/apps/wsgi/structures.py | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/structures.py#L78-L92 | def index(self, key):
"""Get the position of an entry or raise :exc:`ValueError`.
:param key: The key to be looked up.
.. versionchanged:: 0.5
This used to raise :exc:`IndexError`, which was inconsistent
with the list API.
"""
if isinstance(key, str):
... | [
"def",
"index",
"(",
"self",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"str",
")",
":",
"for",
"idx",
",",
"(",
"item",
",",
"quality",
")",
"in",
"enumerate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_value_matches",
"(",
"key... | Get the position of an entry or raise :exc:`ValueError`.
:param key: The key to be looked up.
.. versionchanged:: 0.5
This used to raise :exc:`IndexError`, which was inconsistent
with the list API. | [
"Get",
"the",
"position",
"of",
"an",
"entry",
"or",
"raise",
":",
"exc",
":",
"ValueError",
"."
] | python | train | 34.066667 |
edx/xblock-utils | xblockutils/helpers.py | https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/helpers.py#L6-L25 | def child_isinstance(block, child_id, block_class_or_mixin):
"""
Efficiently check if a child of an XBlock is an instance of the given class.
Arguments:
block -- the parent (or ancestor) of the child block in question
child_id -- the usage key of the child block we are wondering about
block_cla... | [
"def",
"child_isinstance",
"(",
"block",
",",
"child_id",
",",
"block_class_or_mixin",
")",
":",
"def_id",
"=",
"block",
".",
"runtime",
".",
"id_reader",
".",
"get_definition_id",
"(",
"child_id",
")",
"type_name",
"=",
"block",
".",
"runtime",
".",
"id_reade... | Efficiently check if a child of an XBlock is an instance of the given class.
Arguments:
block -- the parent (or ancestor) of the child block in question
child_id -- the usage key of the child block we are wondering about
block_class_or_mixin -- We return true if block's child indentified by child_id is... | [
"Efficiently",
"check",
"if",
"a",
"child",
"of",
"an",
"XBlock",
"is",
"an",
"instance",
"of",
"the",
"given",
"class",
"."
] | python | train | 42.1 |
AutomatedTester/Bugsy | bugsy/bug.py | https://github.com/AutomatedTester/Bugsy/blob/ac14df84e744a148e81aeaae20a144bc5f3cebf1/bugsy/bug.py#L74-L87 | def status(self, value):
"""
Property for getting or setting the bug status
>>> bug.status = "REOPENED"
"""
if self._bug.get('id', None):
if value in VALID_STATUS:
self._bug['status'] = value
else:
raise BugExceptio... | [
"def",
"status",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"_bug",
".",
"get",
"(",
"'id'",
",",
"None",
")",
":",
"if",
"value",
"in",
"VALID_STATUS",
":",
"self",
".",
"_bug",
"[",
"'status'",
"]",
"=",
"value",
"else",
":",
"rais... | Property for getting or setting the bug status
>>> bug.status = "REOPENED" | [
"Property",
"for",
"getting",
"or",
"setting",
"the",
"bug",
"status"
] | python | train | 35.928571 |
mfcloud/python-zvm-sdk | zvmsdk/api.py | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L1035-L1043 | def vswitch_set_vlan_id_for_user(self, vswitch_name, userid, vlan_id):
"""Set vlan id for user when connecting to the vswitch
:param str vswitch_name: the name of the vswitch
:param str userid: the user id of the vm
:param int vlan_id: the VLAN id
"""
self._networkops.se... | [
"def",
"vswitch_set_vlan_id_for_user",
"(",
"self",
",",
"vswitch_name",
",",
"userid",
",",
"vlan_id",
")",
":",
"self",
".",
"_networkops",
".",
"set_vswitch_port_vlan_id",
"(",
"vswitch_name",
",",
"userid",
",",
"vlan_id",
")"
] | Set vlan id for user when connecting to the vswitch
:param str vswitch_name: the name of the vswitch
:param str userid: the user id of the vm
:param int vlan_id: the VLAN id | [
"Set",
"vlan",
"id",
"for",
"user",
"when",
"connecting",
"to",
"the",
"vswitch"
] | python | train | 46.111111 |
ace0/pyrelic | pyrelic/ec.py | https://github.com/ace0/pyrelic/blob/f23d4e6586674675f72304d5938548267d6413bf/pyrelic/ec.py#L245-L260 | def _serialize(element, compress, relicSizeBinFunc, relicWriteBinFunc):
"""
Serializes an @element using the proper function @relicWriteBinFunc into
a bytearray. @compress specifies whether the element should be compressed.
@relicSizeBinFunc is used to determine the size of the serialized output.
Th... | [
"def",
"_serialize",
"(",
"element",
",",
"compress",
",",
"relicSizeBinFunc",
",",
"relicWriteBinFunc",
")",
":",
"cFlag",
"=",
"c_int",
"(",
"compress",
")",
"size",
"=",
"relicSizeBinFunc",
"(",
"byref",
"(",
"element",
")",
",",
"cFlag",
")",
"# Make an ... | Serializes an @element using the proper function @relicWriteBinFunc into
a bytearray. @compress specifies whether the element should be compressed.
@relicSizeBinFunc is used to determine the size of the serialized output.
This is underlying implementation for serialize G1, G2, and Gt. | [
"Serializes",
"an"
] | python | train | 40.25 |
delfick/harpoon | harpoon/option_spec/image_objs.py | https://github.com/delfick/harpoon/blob/a2d39311d6127b7da2e15f40468bf320d598e461/harpoon/option_spec/image_objs.py#L278-L283 | def display_line(self):
"""A single line describing this image"""
msg = ["Image {0}".format(self.name)]
if self.image_index:
msg.append("Pushes to {0}".format(self.image_name))
return ' : '.join(msg) | [
"def",
"display_line",
"(",
"self",
")",
":",
"msg",
"=",
"[",
"\"Image {0}\"",
".",
"format",
"(",
"self",
".",
"name",
")",
"]",
"if",
"self",
".",
"image_index",
":",
"msg",
".",
"append",
"(",
"\"Pushes to {0}\"",
".",
"format",
"(",
"self",
".",
... | A single line describing this image | [
"A",
"single",
"line",
"describing",
"this",
"image"
] | python | train | 39.666667 |
saltstack/salt | salt/modules/deb_postgres.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/deb_postgres.py#L88-L107 | def cluster_list(verbose=False):
'''
Return a list of cluster of Postgres server (tuples of version and name).
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_list
salt '*' postgres.cluster_list verbose=True
'''
cmd = [salt.utils.path.which('pg_lsclusters'), '--no... | [
"def",
"cluster_list",
"(",
"verbose",
"=",
"False",
")",
":",
"cmd",
"=",
"[",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'pg_lsclusters'",
")",
",",
"'--no-header'",
"]",
"ret",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"' '",
".",... | Return a list of cluster of Postgres server (tuples of version and name).
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_list
salt '*' postgres.cluster_list verbose=True | [
"Return",
"a",
"list",
"of",
"cluster",
"of",
"Postgres",
"server",
"(",
"tuples",
"of",
"version",
"and",
"name",
")",
"."
] | python | train | 29.65 |
ssato/python-anyconfig | src/anyconfig/cli.py | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/cli.py#L216-L244 | def _parse_args(argv):
"""
Show supported config format types or usage.
:param argv: Argument list to parse or None (sys.argv will be set).
:return: argparse.Namespace object or None (exit before return)
"""
parser = make_parser()
args = parser.parse_args(argv)
LOGGER.setLevel(to_log_le... | [
"def",
"_parse_args",
"(",
"argv",
")",
":",
"parser",
"=",
"make_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"argv",
")",
"LOGGER",
".",
"setLevel",
"(",
"to_log_level",
"(",
"args",
".",
"loglevel",
")",
")",
"if",
"args",
".",
... | Show supported config format types or usage.
:param argv: Argument list to parse or None (sys.argv will be set).
:return: argparse.Namespace object or None (exit before return) | [
"Show",
"supported",
"config",
"format",
"types",
"or",
"usage",
"."
] | python | train | 28.551724 |
Geotab/mygeotab-python | mygeotab/py3/api_async.py | https://github.com/Geotab/mygeotab-python/blob/baa678e7df90bdd15f5dc55c1374b5c048791a94/mygeotab/py3/api_async.py#L189-L226 | async def _query(server, method, parameters, timeout=DEFAULT_TIMEOUT, verify_ssl=True,
loop: asyncio.AbstractEventLoop=None):
"""Formats and performs the asynchronous query against the API
:param server: The server to query.
:param method: The method name.
:param parameters: A dict of ... | [
"async",
"def",
"_query",
"(",
"server",
",",
"method",
",",
"parameters",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
",",
"verify_ssl",
"=",
"True",
",",
"loop",
":",
"asyncio",
".",
"AbstractEventLoop",
"=",
"None",
")",
":",
"api_endpoint",
"=",
"api",
"."... | Formats and performs the asynchronous query against the API
:param server: The server to query.
:param method: The method name.
:param parameters: A dict of parameters to send
:param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes).
:param verify_ssl... | [
"Formats",
"and",
"performs",
"the",
"asynchronous",
"query",
"against",
"the",
"API"
] | python | train | 52.894737 |
ellmetha/neojsonrpc | neojsonrpc/client.py | https://github.com/ellmetha/neojsonrpc/blob/e369b633a727482d5f9e310f0c3337ae5f7265db/neojsonrpc/client.py#L135-L144 | def get_block_hash(self, block_index, **kwargs):
""" Returns the hash value associated with a specific block index.
:param block_index: a block index (block height)
:type block_index: int
:return: hash of the block associated with the considered index
:rtype: str
"""
... | [
"def",
"get_block_hash",
"(",
"self",
",",
"block_index",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_call",
"(",
"JSONRPCMethods",
".",
"GET_BLOCK_HASH",
".",
"value",
",",
"[",
"block_index",
",",
"]",
",",
"*",
"*",
"kwargs",
")"
] | Returns the hash value associated with a specific block index.
:param block_index: a block index (block height)
:type block_index: int
:return: hash of the block associated with the considered index
:rtype: str | [
"Returns",
"the",
"hash",
"value",
"associated",
"with",
"a",
"specific",
"block",
"index",
"."
] | python | test | 39.8 |
mcs07/ChemDataExtractor | chemdataextractor/parse/actions.py | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/parse/actions.py#L64-L72 | def fix_whitespace(tokens, start, result):
"""Fix whitespace around hyphens and commas. Can be used to remove whitespace tokenization artefacts."""
for e in result:
for child in e.iter():
child.text = child.text.replace(' , ', ', ')
for hyphen in HYPHENS:
child.te... | [
"def",
"fix_whitespace",
"(",
"tokens",
",",
"start",
",",
"result",
")",
":",
"for",
"e",
"in",
"result",
":",
"for",
"child",
"in",
"e",
".",
"iter",
"(",
")",
":",
"child",
".",
"text",
"=",
"child",
".",
"text",
".",
"replace",
"(",
"' , '",
... | Fix whitespace around hyphens and commas. Can be used to remove whitespace tokenization artefacts. | [
"Fix",
"whitespace",
"around",
"hyphens",
"and",
"commas",
".",
"Can",
"be",
"used",
"to",
"remove",
"whitespace",
"tokenization",
"artefacts",
"."
] | python | train | 50 |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1687-L1696 | def auth_edit(name, **kwargs):
"""
Interactively edits an authorization group.
"""
ctx = Context(**kwargs)
ctx.timeout = None
ctx.execute_action('auth:group:edit', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | [
"def",
"auth_edit",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"timeout",
"=",
"None",
"ctx",
".",
"execute_action",
"(",
"'auth:group:edit'",
",",
"*",
"*",
"{",
"'storage'",
":",... | Interactively edits an authorization group. | [
"Interactively",
"edits",
"an",
"authorization",
"group",
"."
] | python | train | 27.3 |
slackapi/python-slackclient | slack/web/client.py | https://github.com/slackapi/python-slackclient/blob/901341c0284fd81e6d2719d6a0502308760d83e4/slack/web/client.py#L582-L589 | def files_delete(self, *, id: str, **kwargs) -> SlackResponse:
"""Deletes a file.
Args:
id (str): The file id. e.g. 'F1234467890'
"""
kwargs.update({"id": id})
return self.api_call("files.delete", json=kwargs) | [
"def",
"files_delete",
"(",
"self",
",",
"*",
",",
"id",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"SlackResponse",
":",
"kwargs",
".",
"update",
"(",
"{",
"\"id\"",
":",
"id",
"}",
")",
"return",
"self",
".",
"api_call",
"(",
"\"files.delete\"... | Deletes a file.
Args:
id (str): The file id. e.g. 'F1234467890' | [
"Deletes",
"a",
"file",
"."
] | python | train | 31.875 |
facelessuser/backrefs | backrefs/_bre_parse.py | https://github.com/facelessuser/backrefs/blob/3b3d60f5d57b02044f880aa29c9c5add0e31a34f/backrefs/_bre_parse.py#L928-L943 | def get_named_unicode(self, i):
"""Get named Unicode."""
index = i.index
value = []
try:
if next(i) != '{':
raise SyntaxError("Named Unicode missing '{'' at %d!" % (i.index - 1))
c = next(i)
while c != '}':
value.append... | [
"def",
"get_named_unicode",
"(",
"self",
",",
"i",
")",
":",
"index",
"=",
"i",
".",
"index",
"value",
"=",
"[",
"]",
"try",
":",
"if",
"next",
"(",
"i",
")",
"!=",
"'{'",
":",
"raise",
"SyntaxError",
"(",
"\"Named Unicode missing '{'' at %d!\"",
"%",
... | Get named Unicode. | [
"Get",
"named",
"Unicode",
"."
] | python | train | 28.6875 |
readbeyond/aeneas | aeneas/dtw.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/dtw.py#L226-L296 | def compute_boundaries(self, synt_anchors):
"""
Compute the min cost path between the two waves,
and return a list of boundary points,
representing the argmin values with respect to
the provided ``synt_anchors`` timings.
If ``synt_anchors`` has ``k`` elements,
th... | [
"def",
"compute_boundaries",
"(",
"self",
",",
"synt_anchors",
")",
":",
"self",
".",
"_setup_dtw",
"(",
")",
"if",
"self",
".",
"dtw",
"is",
"None",
":",
"self",
".",
"log",
"(",
"u\"Inner self.dtw is None => returning artificial boundary indices\"",
")",
"begin"... | Compute the min cost path between the two waves,
and return a list of boundary points,
representing the argmin values with respect to
the provided ``synt_anchors`` timings.
If ``synt_anchors`` has ``k`` elements,
the returned array will have ``k+1`` elements,
accounting ... | [
"Compute",
"the",
"min",
"cost",
"path",
"between",
"the",
"two",
"waves",
"and",
"return",
"a",
"list",
"of",
"boundary",
"points",
"representing",
"the",
"argmin",
"values",
"with",
"respect",
"to",
"the",
"provided",
"synt_anchors",
"timings",
"."
] | python | train | 47.676056 |
sbg/sevenbridges-python | sevenbridges/models/project.py | https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/models/project.py#L251-L276 | def add_member_email(self, email, permissions=None):
"""
Add a member to the project using member email.
:param email: Member email.
:param permissions: Permissions dictionary.
:return: Member object.
"""
data = {'email': email}
if isinstance(permissions,... | [
"def",
"add_member_email",
"(",
"self",
",",
"email",
",",
"permissions",
"=",
"None",
")",
":",
"data",
"=",
"{",
"'email'",
":",
"email",
"}",
"if",
"isinstance",
"(",
"permissions",
",",
"dict",
")",
":",
"data",
".",
"update",
"(",
"{",
"'permissio... | Add a member to the project using member email.
:param email: Member email.
:param permissions: Permissions dictionary.
:return: Member object. | [
"Add",
"a",
"member",
"to",
"the",
"project",
"using",
"member",
"email",
".",
":",
"param",
"email",
":",
"Member",
"email",
".",
":",
"param",
"permissions",
":",
"Permissions",
"dictionary",
".",
":",
"return",
":",
"Member",
"object",
"."
] | python | train | 31.653846 |
ev3dev/ev3dev-lang-python | ev3dev2/control/GyroBalancer.py | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/control/GyroBalancer.py#L185-L198 | def _set_duty(self, motor_duty_file, duty, friction_offset,
voltage_comp):
"""Function to set the duty cycle of the motors."""
# Compensate for nominal voltage and round the input
duty_int = int(round(duty*voltage_comp))
# Add or subtract offset and clamp the value bet... | [
"def",
"_set_duty",
"(",
"self",
",",
"motor_duty_file",
",",
"duty",
",",
"friction_offset",
",",
"voltage_comp",
")",
":",
"# Compensate for nominal voltage and round the input",
"duty_int",
"=",
"int",
"(",
"round",
"(",
"duty",
"*",
"voltage_comp",
")",
")",
"... | Function to set the duty cycle of the motors. | [
"Function",
"to",
"set",
"the",
"duty",
"cycle",
"of",
"the",
"motors",
"."
] | python | train | 42.142857 |
zsimic/runez | src/runez/heartbeat.py | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/heartbeat.py#L82-L87 | def start(cls):
"""Start background thread if not already started"""
if cls._thread is None:
cls._thread = threading.Thread(target=cls._run, name="Heartbeat")
cls._thread.daemon = True
cls._thread.start() | [
"def",
"start",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_thread",
"is",
"None",
":",
"cls",
".",
"_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"cls",
".",
"_run",
",",
"name",
"=",
"\"Heartbeat\"",
")",
"cls",
".",
"_thread",
"."... | Start background thread if not already started | [
"Start",
"background",
"thread",
"if",
"not",
"already",
"started"
] | python | train | 41.833333 |
mardiros/pyshop | pyshop/models.py | https://github.com/mardiros/pyshop/blob/b42510b9c3fa16e0e5710457401ac38fea5bf7a0/pyshop/models.py#L184-L202 | def by_login(cls, session, login, local=True):
"""
Get a user from a given login.
:param session: SQLAlchemy session
:type session: :class:`sqlalchemy.Session`
:param login: the user login
:type login: unicode
:return: the associated user
:rtype: :class... | [
"def",
"by_login",
"(",
"cls",
",",
"session",
",",
"login",
",",
"local",
"=",
"True",
")",
":",
"user",
"=",
"cls",
".",
"first",
"(",
"session",
",",
"where",
"=",
"(",
"(",
"cls",
".",
"login",
"==",
"login",
")",
",",
"(",
"cls",
".",
"loc... | Get a user from a given login.
:param session: SQLAlchemy session
:type session: :class:`sqlalchemy.Session`
:param login: the user login
:type login: unicode
:return: the associated user
:rtype: :class:`pyshop.models.User` | [
"Get",
"a",
"user",
"from",
"a",
"given",
"login",
"."
] | python | train | 33 |
rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L1180-L1191 | def delete_property(self, content_id, property_key, callback=None):
"""
Deletes a content property.
:param content_id (string): The ID for the content that owns the property to be deleted.
:param property_key (string): The name of the property to be deleted.
:param callback: OPTI... | [
"def",
"delete_property",
"(",
"self",
",",
"content_id",
",",
"property_key",
",",
"callback",
"=",
"None",
")",
":",
"return",
"self",
".",
"_service_delete_request",
"(",
"\"rest/api/content/{id}/property/{key}\"",
"\"\"",
".",
"format",
"(",
"id",
"=",
"conten... | Deletes a content property.
:param content_id (string): The ID for the content that owns the property to be deleted.
:param property_key (string): The name of the property to be deleted.
:param callback: OPTIONAL: The callback to execute on the resulting data, before the method returns.
... | [
"Deletes",
"a",
"content",
"property",
".",
":",
"param",
"content_id",
"(",
"string",
")",
":",
"The",
"ID",
"for",
"the",
"content",
"that",
"owns",
"the",
"property",
"to",
"be",
"deleted",
".",
":",
"param",
"property_key",
"(",
"string",
")",
":",
... | python | train | 67.25 |
blockstack-packages/blockstack-gpg | blockstack_gpg/gpg.py | https://github.com/blockstack-packages/blockstack-gpg/blob/e4d51e4e51678d9b946596ca9dec53e2d78c8710/blockstack_gpg/gpg.py#L105-L113 | def get_gpg_home( appname, config_dir=None ):
"""
Get the GPG keyring directory for a particular application.
Return the path.
"""
assert is_valid_appname(appname)
config_dir = get_config_dir( config_dir )
path = os.path.join( config_dir, "gpgkeys", appname )
return path | [
"def",
"get_gpg_home",
"(",
"appname",
",",
"config_dir",
"=",
"None",
")",
":",
"assert",
"is_valid_appname",
"(",
"appname",
")",
"config_dir",
"=",
"get_config_dir",
"(",
"config_dir",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config_dir",
... | Get the GPG keyring directory for a particular application.
Return the path. | [
"Get",
"the",
"GPG",
"keyring",
"directory",
"for",
"a",
"particular",
"application",
".",
"Return",
"the",
"path",
"."
] | python | train | 32.777778 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/io/image.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/io/image.py#L159-L194 | def imread(filename, format=None):
"""Read image data from disk
Requires imageio or PIL.
Parameters
----------
filename : str
Filename to read.
format : str | None
Format of the file. If None, it will be inferred from the filename.
Returns
-------
data : array
... | [
"def",
"imread",
"(",
"filename",
",",
"format",
"=",
"None",
")",
":",
"imageio",
",",
"PIL",
"=",
"_check_img_lib",
"(",
")",
"if",
"imageio",
"is",
"not",
"None",
":",
"return",
"imageio",
".",
"imread",
"(",
"filename",
",",
"format",
")",
"elif",
... | Read image data from disk
Requires imageio or PIL.
Parameters
----------
filename : str
Filename to read.
format : str | None
Format of the file. If None, it will be inferred from the filename.
Returns
-------
data : array
Image data.
See also
--------... | [
"Read",
"image",
"data",
"from",
"disk"
] | python | train | 24.972222 |
apache/spark | python/pyspark/sql/functions.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/functions.py#L619-L628 | def round(col, scale=0):
"""
Round the given value to `scale` decimal places using HALF_UP rounding mode if `scale` >= 0
or at integral part when `scale` < 0.
>>> spark.createDataFrame([(2.5,)], ['a']).select(round('a', 0).alias('r')).collect()
[Row(r=3.0)]
"""
sc = SparkContext._active_spa... | [
"def",
"round",
"(",
"col",
",",
"scale",
"=",
"0",
")",
":",
"sc",
"=",
"SparkContext",
".",
"_active_spark_context",
"return",
"Column",
"(",
"sc",
".",
"_jvm",
".",
"functions",
".",
"round",
"(",
"_to_java_column",
"(",
"col",
")",
",",
"scale",
")... | Round the given value to `scale` decimal places using HALF_UP rounding mode if `scale` >= 0
or at integral part when `scale` < 0.
>>> spark.createDataFrame([(2.5,)], ['a']).select(round('a', 0).alias('r')).collect()
[Row(r=3.0)] | [
"Round",
"the",
"given",
"value",
"to",
"scale",
"decimal",
"places",
"using",
"HALF_UP",
"rounding",
"mode",
"if",
"scale",
">",
"=",
"0",
"or",
"at",
"integral",
"part",
"when",
"scale",
"<",
"0",
"."
] | python | train | 39.3 |
mozillazg/bustard | bustard/router.py | https://github.com/mozillazg/bustard/blob/bd7b47f3ba5440cf6ea026c8b633060fedeb80b7/bustard/router.py#L94-L102 | def _replace_type_to_regex(cls, match):
""" /<int:id> -> r'(?P<id>\d+)' """
groupdict = match.groupdict()
_type = groupdict.get('type')
type_regex = cls.TYPE_REGEX_MAP.get(_type, '[^/]+')
name = groupdict.get('name')
return r'(?P<{name}>{type_regex})'.format(
... | [
"def",
"_replace_type_to_regex",
"(",
"cls",
",",
"match",
")",
":",
"groupdict",
"=",
"match",
".",
"groupdict",
"(",
")",
"_type",
"=",
"groupdict",
".",
"get",
"(",
"'type'",
")",
"type_regex",
"=",
"cls",
".",
"TYPE_REGEX_MAP",
".",
"get",
"(",
"_typ... | /<int:id> -> r'(?P<id>\d+)' | [
"/",
"<int",
":",
"id",
">",
"-",
">",
"r",
"(",
"?P<id",
">",
"\\",
"d",
"+",
")"
] | python | valid | 39.444444 |
romanorac/discomll | discomll/classification/logistic_regression.py | https://github.com/romanorac/discomll/blob/a4703daffb2ba3c9f614bc3dbe45ae55884aea00/discomll/classification/logistic_regression.py#L15-L40 | def map_fit(interface, state, label, inp):
"""
Function calculates sigmoid function (g) for every sample. With g it calculates part of Hessian matrix and gradient, aggregates and output them. It also calculates J function which is needed for checking the convergence of parameters theta.
"""
import numpy... | [
"def",
"map_fit",
"(",
"interface",
",",
"state",
",",
"label",
",",
"inp",
")",
":",
"import",
"numpy",
"as",
"np",
"out",
"=",
"interface",
".",
"output",
"(",
"0",
")",
"H",
",",
"J",
",",
"grad",
"=",
"0",
",",
"0",
",",
"0",
"for",
"row",
... | Function calculates sigmoid function (g) for every sample. With g it calculates part of Hessian matrix and gradient, aggregates and output them. It also calculates J function which is needed for checking the convergence of parameters theta. | [
"Function",
"calculates",
"sigmoid",
"function",
"(",
"g",
")",
"for",
"every",
"sample",
".",
"With",
"g",
"it",
"calculates",
"part",
"of",
"Hessian",
"matrix",
"and",
"gradient",
"aggregates",
"and",
"output",
"them",
".",
"It",
"also",
"calculates",
"J",... | python | train | 50.461538 |
dacker-team/pyzure | pyzure/send/send.py | https://github.com/dacker-team/pyzure/blob/1e6d202f91ca0f080635adc470d9d18585056d53/pyzure/send/send.py#L15-L121 | def send_to_azure(instance, data, replace=True, types=None, primary_key=(), sub_commit=True):
"""
data = {
"table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist,
"columns_name" : [first_column_name,second_column_name,...,last_column_name],
"row... | [
"def",
"send_to_azure",
"(",
"instance",
",",
"data",
",",
"replace",
"=",
"True",
",",
"types",
"=",
"None",
",",
"primary_key",
"=",
"(",
")",
",",
"sub_commit",
"=",
"True",
")",
":",
"# Time initialization",
"start",
"=",
"datetime",
".",
"datetime",
... | data = {
"table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist,
"columns_name" : [first_column_name,second_column_name,...,last_column_name],
"rows" : [[first_raw_value,second_raw_value,...,last_raw_value],...]
} | [
"data",
"=",
"{",
"table_name",
":",
"name_of_the_azure_schema",
"+",
".",
"+",
"name_of_the_azure_table",
"#Must",
"already",
"exist",
"columns_name",
":",
"[",
"first_column_name",
"second_column_name",
"...",
"last_column_name",
"]",
"rows",
":",
"[[",
"first_raw_v... | python | train | 34.327103 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L535-L549 | def from_yamlf(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> T:
"""From yaml file path to instance
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:param force_snake_case: Keys are transf... | [
"def",
"from_yamlf",
"(",
"cls",
",",
"fpath",
":",
"str",
",",
"encoding",
":",
"str",
"=",
"'utf8'",
",",
"force_snake_case",
"=",
"True",
",",
"force_cast",
":",
"bool",
"=",
"False",
",",
"restrict",
":",
"bool",
"=",
"True",
")",
"->",
"T",
":",... | From yaml file path to instance
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if ... | [
"From",
"yaml",
"file",
"path",
"to",
"instance"
] | python | train | 48.866667 |
gtaylor/evarify | evarify/filters/python_basics.py | https://github.com/gtaylor/evarify/blob/37cec29373c820eda96939633e2067d55598915b/evarify/filters/python_basics.py#L117-L131 | def value_to_python_log_level(config_val, evar):
"""
Convert an evar value into a Python logging level constant.
:param str config_val: The env var value.
:param EnvironmentVariable evar: The EVar object we are validating
a value for.
:return: A validated string.
:raises: ValueError if ... | [
"def",
"value_to_python_log_level",
"(",
"config_val",
",",
"evar",
")",
":",
"if",
"not",
"config_val",
":",
"config_val",
"=",
"evar",
".",
"default_val",
"config_val",
"=",
"config_val",
".",
"upper",
"(",
")",
"# noinspection PyProtectedMember",
"return",
"log... | Convert an evar value into a Python logging level constant.
:param str config_val: The env var value.
:param EnvironmentVariable evar: The EVar object we are validating
a value for.
:return: A validated string.
:raises: ValueError if the log level is invalid. | [
"Convert",
"an",
"evar",
"value",
"into",
"a",
"Python",
"logging",
"level",
"constant",
"."
] | python | valid | 34.4 |
AtteqCom/zsl | src/zsl/db/helpers/pagination.py | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/db/helpers/pagination.py#L93-L101 | def paginate(self, q):
"""
Filters the query so that a given page is returned. The record count
is computed automatically from query.
:param q: Query to be paged.
:return: Paged query.
"""
self.record_count = q.count()
return self.apply_pagination(q).all() | [
"def",
"paginate",
"(",
"self",
",",
"q",
")",
":",
"self",
".",
"record_count",
"=",
"q",
".",
"count",
"(",
")",
"return",
"self",
".",
"apply_pagination",
"(",
"q",
")",
".",
"all",
"(",
")"
] | Filters the query so that a given page is returned. The record count
is computed automatically from query.
:param q: Query to be paged.
:return: Paged query. | [
"Filters",
"the",
"query",
"so",
"that",
"a",
"given",
"page",
"is",
"returned",
".",
"The",
"record",
"count",
"is",
"computed",
"automatically",
"from",
"query",
".",
":",
"param",
"q",
":",
"Query",
"to",
"be",
"paged",
".",
":",
"return",
":",
"Pag... | python | train | 34.666667 |
boriel/zxbasic | zxbpplex.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpplex.py#L102-L107 | def t_asmcomment_NEWLINE(self, t):
r'\r?\n'
# New line => remove whatever state in top of the stack and replace it with INITIAL
t.lexer.lineno += 1
t.lexer.pop_state()
return t | [
"def",
"t_asmcomment_NEWLINE",
"(",
"self",
",",
"t",
")",
":",
"# New line => remove whatever state in top of the stack and replace it with INITIAL",
"t",
".",
"lexer",
".",
"lineno",
"+=",
"1",
"t",
".",
"lexer",
".",
"pop_state",
"(",
")",
"return",
"t"
] | r'\r?\n | [
"r",
"\\",
"r?",
"\\",
"n"
] | python | train | 35.166667 |
ssalentin/plip | plip/modules/detection.py | https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/detection.py#L120-L156 | def pistacking(rings_bs, rings_lig):
"""Return all pi-stackings between the given aromatic ring systems in receptor and ligand."""
data = namedtuple(
'pistack', 'proteinring ligandring distance angle offset type restype resnr reschain restype_l resnr_l reschain_l')
pairings = []
for r, l in iter... | [
"def",
"pistacking",
"(",
"rings_bs",
",",
"rings_lig",
")",
":",
"data",
"=",
"namedtuple",
"(",
"'pistack'",
",",
"'proteinring ligandring distance angle offset type restype resnr reschain restype_l resnr_l reschain_l'",
")",
"pairings",
"=",
"[",
"]",
"for",
"r",
",",
... | Return all pi-stackings between the given aromatic ring systems in receptor and ligand. | [
"Return",
"all",
"pi",
"-",
"stackings",
"between",
"the",
"given",
"aromatic",
"ring",
"systems",
"in",
"receptor",
"and",
"ligand",
"."
] | python | train | 52.540541 |
lordmauve/lepton | examples/fireworks.py | https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/examples/fireworks.py#L132-L155 | def on_draw():
global yrot
win.clear()
glLoadIdentity()
glTranslatef(0, 0, -100)
glRotatef(yrot, 0.0, 1.0, 0.0)
default_system.draw()
'''
glBindTexture(GL_TEXTURE_2D, 1)
glEnable(GL_TEXTURE_2D)
glEnable(GL_POINT_SPRITE)
glPointSize(100);
glBegin(GL_POINTS)
glVertex2f(0,0)
glEnd()
glBindTexture(GL_TEXTURE... | [
"def",
"on_draw",
"(",
")",
":",
"global",
"yrot",
"win",
".",
"clear",
"(",
")",
"glLoadIdentity",
"(",
")",
"glTranslatef",
"(",
"0",
",",
"0",
",",
"-",
"100",
")",
"glRotatef",
"(",
"yrot",
",",
"0.0",
",",
"1.0",
",",
"0.0",
")",
"default_syst... | glBindTexture(GL_TEXTURE_2D, 1)
glEnable(GL_TEXTURE_2D)
glEnable(GL_POINT_SPRITE)
glPointSize(100);
glBegin(GL_POINTS)
glVertex2f(0,0)
glEnd()
glBindTexture(GL_TEXTURE_2D, 2)
glEnable(GL_TEXTURE_2D)
glEnable(GL_POINT_SPRITE)
glPointSize(100);
glBegin(GL_POINTS)
glVertex2f(50,0)
glEnd()
glBindTexture(GL_TE... | [
"glBindTexture",
"(",
"GL_TEXTURE_2D",
"1",
")",
"glEnable",
"(",
"GL_TEXTURE_2D",
")",
"glEnable",
"(",
"GL_POINT_SPRITE",
")",
"glPointSize",
"(",
"100",
")",
";",
"glBegin",
"(",
"GL_POINTS",
")",
"glVertex2f",
"(",
"0",
"0",
")",
"glEnd",
"()",
"glBindTe... | python | train | 19.166667 |
mardix/Mocha | mocha/contrib/auth/__init__.py | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/auth/__init__.py#L464-L474 | def create_action_token(self, action, expires_in):
"""
Create a url safe action token attached to the user
:param action:
:param expires_in:
:return:
"""
return utils.sign_url_safe(self.user.id,
secret_key=get_jwt_secret(),
... | [
"def",
"create_action_token",
"(",
"self",
",",
"action",
",",
"expires_in",
")",
":",
"return",
"utils",
".",
"sign_url_safe",
"(",
"self",
".",
"user",
".",
"id",
",",
"secret_key",
"=",
"get_jwt_secret",
"(",
")",
",",
"salt",
"=",
"action",
",",
"exp... | Create a url safe action token attached to the user
:param action:
:param expires_in:
:return: | [
"Create",
"a",
"url",
"safe",
"action",
"token",
"attached",
"to",
"the",
"user",
":",
"param",
"action",
":",
":",
"param",
"expires_in",
":",
":",
"return",
":"
] | python | train | 37.272727 |
Clinical-Genomics/scout | scout/adapter/mongo/variant_loader.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/adapter/mongo/variant_loader.py#L37-L55 | def update_variant(self, variant_obj):
"""Update one variant document in the database.
This means that the variant in the database will be replaced by variant_obj.
Args:
variant_obj(dict)
Returns:
new_variant(dict)
"""
LOG.debug('Updating varian... | [
"def",
"update_variant",
"(",
"self",
",",
"variant_obj",
")",
":",
"LOG",
".",
"debug",
"(",
"'Updating variant %s'",
",",
"variant_obj",
".",
"get",
"(",
"'simple_id'",
")",
")",
"new_variant",
"=",
"self",
".",
"variant_collection",
".",
"find_one_and_replace... | Update one variant document in the database.
This means that the variant in the database will be replaced by variant_obj.
Args:
variant_obj(dict)
Returns:
new_variant(dict) | [
"Update",
"one",
"variant",
"document",
"in",
"the",
"database",
"."
] | python | test | 29.842105 |
crs4/hl7apy | hl7apy/core.py | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L59-L79 | def is_base_datatype(datatype, version=None):
"""
Check if the given datatype is a base datatype of the specified version
:type datatype: ``str``
:param datatype: the datatype (e.g. ST)
:type version: ``str``
:param version: the HL7 version (e.g. 2.5)
:return: ``True`` if it is a base dat... | [
"def",
"is_base_datatype",
"(",
"datatype",
",",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"version",
"=",
"get_default_version",
"(",
")",
"lib",
"=",
"load_library",
"(",
"version",
")",
"return",
"lib",
".",
"is_base_datatype",... | Check if the given datatype is a base datatype of the specified version
:type datatype: ``str``
:param datatype: the datatype (e.g. ST)
:type version: ``str``
:param version: the HL7 version (e.g. 2.5)
:return: ``True`` if it is a base datatype, ``False`` otherwise
>>> is_base_datatype('ST')... | [
"Check",
"if",
"the",
"given",
"datatype",
"is",
"a",
"base",
"datatype",
"of",
"the",
"specified",
"version"
] | python | train | 26.380952 |
mdickinson/bigfloat | bigfloat/core.py | https://github.com/mdickinson/bigfloat/blob/e5fdd1048615191ed32a2b7460e14b3b3ff24662/bigfloat/core.py#L1460-L1469 | def less(x, y):
"""
Return True if x < y and False otherwise.
This function returns False whenever x and/or y is a NaN.
"""
x = BigFloat._implicit_convert(x)
y = BigFloat._implicit_convert(y)
return mpfr.mpfr_less_p(x, y) | [
"def",
"less",
"(",
"x",
",",
"y",
")",
":",
"x",
"=",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
"y",
"=",
"BigFloat",
".",
"_implicit_convert",
"(",
"y",
")",
"return",
"mpfr",
".",
"mpfr_less_p",
"(",
"x",
",",
"y",
")"
] | Return True if x < y and False otherwise.
This function returns False whenever x and/or y is a NaN. | [
"Return",
"True",
"if",
"x",
"<",
"y",
"and",
"False",
"otherwise",
"."
] | python | train | 24.2 |
ultrabug/py3status | py3status/py3.py | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/py3.py#L337-L425 | def format_units(self, value, unit="B", optimal=5, auto=True, si=False):
"""
Takes a value and formats it for user output, we can choose the unit to
use eg B, MiB, kbits/second. This is mainly for use with bytes/bits it
converts the value into a human readable form. It has various
... | [
"def",
"format_units",
"(",
"self",
",",
"value",
",",
"unit",
"=",
"\"B\"",
",",
"optimal",
"=",
"5",
",",
"auto",
"=",
"True",
",",
"si",
"=",
"False",
")",
":",
"UNITS",
"=",
"\"KMGTPEZY\"",
"DECIMAL_SIZE",
"=",
"1000",
"BINARY_SIZE",
"=",
"1024",
... | Takes a value and formats it for user output, we can choose the unit to
use eg B, MiB, kbits/second. This is mainly for use with bytes/bits it
converts the value into a human readable form. It has various
additional options but they are really only for special cases.
The function retu... | [
"Takes",
"a",
"value",
"and",
"formats",
"it",
"for",
"user",
"output",
"we",
"can",
"choose",
"the",
"unit",
"to",
"use",
"eg",
"B",
"MiB",
"kbits",
"/",
"second",
".",
"This",
"is",
"mainly",
"for",
"use",
"with",
"bytes",
"/",
"bits",
"it",
"conve... | python | train | 36.764045 |
worstcase/blockade | blockade/chaos.py | https://github.com/worstcase/blockade/blob/3dc6ad803f0b0d56586dec9542a6a06aa06cf569/blockade/chaos.py#L333-L339 | def _sm_cleanup(self, *args, **kwargs):
"""
Delete all state associated with the chaos session
"""
if self._done_notification_func is not None:
self._done_notification_func()
self._timer.cancel() | [
"def",
"_sm_cleanup",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_done_notification_func",
"is",
"not",
"None",
":",
"self",
".",
"_done_notification_func",
"(",
")",
"self",
".",
"_timer",
".",
"cancel",
"(",
... | Delete all state associated with the chaos session | [
"Delete",
"all",
"state",
"associated",
"with",
"the",
"chaos",
"session"
] | python | valid | 34.428571 |
koszullab/metaTOR | metator/scripts/hicstuff.py | https://github.com/koszullab/metaTOR/blob/0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a/metator/scripts/hicstuff.py#L819-L880 | def to_pdb(structure, filename, contigs=None, annotations=None,
indices=None, special_bins=None):
"""From a structure (or matrix) generate the corresponding pdb file
representing each chain as a contig/chromosome and filling the occupancy
field with a custom annotation. If the matrix has been tri... | [
"def",
"to_pdb",
"(",
"structure",
",",
"filename",
",",
"contigs",
"=",
"None",
",",
"annotations",
"=",
"None",
",",
"indices",
"=",
"None",
",",
"special_bins",
"=",
"None",
")",
":",
"n",
"=",
"len",
"(",
"structure",
")",
"letters",
"=",
"(",
"s... | From a structure (or matrix) generate the corresponding pdb file
representing each chain as a contig/chromosome and filling the occupancy
field with a custom annotation. If the matrix has been trimmed somewhat,
remaining indices may be specified. | [
"From",
"a",
"structure",
"(",
"or",
"matrix",
")",
"generate",
"the",
"corresponding",
"pdb",
"file",
"representing",
"each",
"chain",
"as",
"a",
"contig",
"/",
"chromosome",
"and",
"filling",
"the",
"occupancy",
"field",
"with",
"a",
"custom",
"annotation",
... | python | train | 40.903226 |
lcharleux/argiope | argiope/mesh.py | https://github.com/lcharleux/argiope/blob/8170e431362dc760589f7d141090fd133dece259/argiope/mesh.py#L1153-L1179 | def _make_conn(shape):
"""
Connectivity builder using Numba for speed boost.
"""
shape = np.array(shape)
Ne = shape.prod()
if len(shape) == 2:
nx, ny = np.array(shape) +1
conn = np.zeros((Ne, 4), dtype = np.int32)
counter = 0
pattern = np.array([0,1,1+nx,nx])
... | [
"def",
"_make_conn",
"(",
"shape",
")",
":",
"shape",
"=",
"np",
".",
"array",
"(",
"shape",
")",
"Ne",
"=",
"shape",
".",
"prod",
"(",
")",
"if",
"len",
"(",
"shape",
")",
"==",
"2",
":",
"nx",
",",
"ny",
"=",
"np",
".",
"array",
"(",
"shape... | Connectivity builder using Numba for speed boost. | [
"Connectivity",
"builder",
"using",
"Numba",
"for",
"speed",
"boost",
"."
] | python | test | 33.37037 |
ga4gh/ga4gh-client | ga4gh/client/cli.py | https://github.com/ga4gh/ga4gh-client/blob/d23b00b89112ef0930d45ee75aa3c6de3db615c5/ga4gh/client/cli.py#L173-L184 | def getAllReadGroups(self):
"""
Get all read groups in a read group set
"""
for dataset in self.getAllDatasets():
iterator = self._client.search_read_group_sets(
dataset_id=dataset.id)
for readGroupSet in iterator:
readGroupSet = se... | [
"def",
"getAllReadGroups",
"(",
"self",
")",
":",
"for",
"dataset",
"in",
"self",
".",
"getAllDatasets",
"(",
")",
":",
"iterator",
"=",
"self",
".",
"_client",
".",
"search_read_group_sets",
"(",
"dataset_id",
"=",
"dataset",
".",
"id",
")",
"for",
"readG... | Get all read groups in a read group set | [
"Get",
"all",
"read",
"groups",
"in",
"a",
"read",
"group",
"set"
] | python | train | 39.5 |
pmneila/morphsnakes | examples.py | https://github.com/pmneila/morphsnakes/blob/aab66e70f86308d7b1927d76869a1a562120f849/examples.py#L73-L129 | def visual_callback_3d(fig=None, plot_each=1):
"""
Returns a callback than can be passed as the argument `iter_callback`
of `morphological_geodesic_active_contour` and
`morphological_chan_vese` for visualizing the evolution
of the levelsets. Only works for 3D images.
Parameters
--------... | [
"def",
"visual_callback_3d",
"(",
"fig",
"=",
"None",
",",
"plot_each",
"=",
"1",
")",
":",
"from",
"mpl_toolkits",
".",
"mplot3d",
"import",
"Axes3D",
"# PyMCubes package is required for `visual_callback_3d`",
"try",
":",
"import",
"mcubes",
"except",
"ImportError",
... | Returns a callback than can be passed as the argument `iter_callback`
of `morphological_geodesic_active_contour` and
`morphological_chan_vese` for visualizing the evolution
of the levelsets. Only works for 3D images.
Parameters
----------
fig : matplotlib.figure.Figure
Figure where ... | [
"Returns",
"a",
"callback",
"than",
"can",
"be",
"passed",
"as",
"the",
"argument",
"iter_callback",
"of",
"morphological_geodesic_active_contour",
"and",
"morphological_chan_vese",
"for",
"visualizing",
"the",
"evolution",
"of",
"the",
"levelsets",
".",
"Only",
"work... | python | train | 29.298246 |
exxeleron/qPython | qpython/qreader.py | https://github.com/exxeleron/qPython/blob/7e64a28b1e8814a8d6b9217ce79bb8de546e62f3/qpython/qreader.py#L119-L141 | def read(self, source = None, **options):
'''
Reads and optionally parses a single message.
:Parameters:
- `source` - optional data buffer to be read, if not specified data is
read from the wrapped stream
:Options:
- `raw` (`boolean`) - indicates wh... | [
"def",
"read",
"(",
"self",
",",
"source",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"message",
"=",
"self",
".",
"read_header",
"(",
"source",
")",
"message",
".",
"data",
"=",
"self",
".",
"read_data",
"(",
"message",
".",
"size",
",",
"me... | Reads and optionally parses a single message.
:Parameters:
- `source` - optional data buffer to be read, if not specified data is
read from the wrapped stream
:Options:
- `raw` (`boolean`) - indicates whether read data should parsed or
returned in raw b... | [
"Reads",
"and",
"optionally",
"parses",
"a",
"single",
"message",
".",
":",
"Parameters",
":",
"-",
"source",
"-",
"optional",
"data",
"buffer",
"to",
"be",
"read",
"if",
"not",
"specified",
"data",
"is",
"read",
"from",
"the",
"wrapped",
"stream",
":",
... | python | train | 42.565217 |
CSchoel/nolds | nolds/measures.py | https://github.com/CSchoel/nolds/blob/8a5ecc472d67ac08b571bd68967287668ca9058e/nolds/measures.py#L85-L107 | def lyap_r_len(**kwargs):
"""
Helper function that calculates the minimum number of data points required
to use lyap_r.
Note that none of the required parameters may be set to None.
Kwargs:
kwargs(dict):
arguments used for lyap_r (required: emb_dim, lag, trajectory_len and
min_tsep)
Retur... | [
"def",
"lyap_r_len",
"(",
"*",
"*",
"kwargs",
")",
":",
"# minimum length required to find single orbit vector",
"min_len",
"=",
"(",
"kwargs",
"[",
"'emb_dim'",
"]",
"-",
"1",
")",
"*",
"kwargs",
"[",
"'lag'",
"]",
"+",
"1",
"# we need trajectory_len orbit vector... | Helper function that calculates the minimum number of data points required
to use lyap_r.
Note that none of the required parameters may be set to None.
Kwargs:
kwargs(dict):
arguments used for lyap_r (required: emb_dim, lag, trajectory_len and
min_tsep)
Returns:
minimum number of data poi... | [
"Helper",
"function",
"that",
"calculates",
"the",
"minimum",
"number",
"of",
"data",
"points",
"required",
"to",
"use",
"lyap_r",
"."
] | python | train | 32.565217 |
bcbio/bcbio-nextgen | bcbio/cwl/workflow.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/workflow.py#L348-L382 | def _create_record(name, field_defs, step_name, inputs, unlist, file_vs, std_vs, parallel):
"""Create an output record by rearranging inputs.
Batching processes create records that reformat the inputs for
parallelization.
"""
if field_defs:
fields = []
inherit = []
inherit_a... | [
"def",
"_create_record",
"(",
"name",
",",
"field_defs",
",",
"step_name",
",",
"inputs",
",",
"unlist",
",",
"file_vs",
",",
"std_vs",
",",
"parallel",
")",
":",
"if",
"field_defs",
":",
"fields",
"=",
"[",
"]",
"inherit",
"=",
"[",
"]",
"inherit_all",
... | Create an output record by rearranging inputs.
Batching processes create records that reformat the inputs for
parallelization. | [
"Create",
"an",
"output",
"record",
"by",
"rearranging",
"inputs",
"."
] | python | train | 40.428571 |
regebro/hovercraft | hovercraft/position.py | https://github.com/regebro/hovercraft/blob/d9f63bfdfe1519c4d7a81697ee066e49dc26a30b/hovercraft/position.py#L131-L216 | def calculate_positions(positions):
"""Calculates position information"""
current_position = {'data-x': 0,
'data-y': 0,
'data-z': 0,
'data-rotate-x': 0,
'data-rotate-y': 0,
'data-rotate-z': 0,... | [
"def",
"calculate_positions",
"(",
"positions",
")",
":",
"current_position",
"=",
"{",
"'data-x'",
":",
"0",
",",
"'data-y'",
":",
"0",
",",
"'data-z'",
":",
"0",
",",
"'data-rotate-x'",
":",
"0",
",",
"'data-rotate-y'",
":",
"0",
",",
"'data-rotate-z'",
... | Calculates position information | [
"Calculates",
"position",
"information"
] | python | train | 33.267442 |
fastai/fastai | fastai/torch_core.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L258-L262 | def in_channels(m:nn.Module) -> List[int]:
"Return the shape of the first weight layer in `m`."
for l in flatten_model(m):
if hasattr(l, 'weight'): return l.weight.shape[1]
raise Exception('No weight layer') | [
"def",
"in_channels",
"(",
"m",
":",
"nn",
".",
"Module",
")",
"->",
"List",
"[",
"int",
"]",
":",
"for",
"l",
"in",
"flatten_model",
"(",
"m",
")",
":",
"if",
"hasattr",
"(",
"l",
",",
"'weight'",
")",
":",
"return",
"l",
".",
"weight",
".",
"... | Return the shape of the first weight layer in `m`. | [
"Return",
"the",
"shape",
"of",
"the",
"first",
"weight",
"layer",
"in",
"m",
"."
] | python | train | 44.6 |
linkedin/naarad | src/naarad/utils.py | https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/utils.py#L344-L374 | def parse_graph_section(config_obj, section, outdir_default, indir_default):
"""
Parse the GRAPH section of the config to extract useful values
:param config_obj: ConfigParser object
:param section: Section name
:param outdir_default: Default output directory passed in args
:param indir_default: Default inp... | [
"def",
"parse_graph_section",
"(",
"config_obj",
",",
"section",
",",
"outdir_default",
",",
"indir_default",
")",
":",
"graph_timezone",
"=",
"None",
"graphing_library",
"=",
"CONSTANTS",
".",
"DEFAULT_GRAPHING_LIBRARY",
"crossplots",
"=",
"[",
"]",
"if",
"config_o... | Parse the GRAPH section of the config to extract useful values
:param config_obj: ConfigParser object
:param section: Section name
:param outdir_default: Default output directory passed in args
:param indir_default: Default input directory passed in args
:return: List of options extracted from the GRAPH secti... | [
"Parse",
"the",
"GRAPH",
"section",
"of",
"the",
"config",
"to",
"extract",
"useful",
"values",
":",
"param",
"config_obj",
":",
"ConfigParser",
"object",
":",
"param",
"section",
":",
"Section",
"name",
":",
"param",
"outdir_default",
":",
"Default",
"output"... | python | valid | 48.870968 |
hollenstein/maspy | maspy/featuremethods.py | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/featuremethods.py#L257-L379 | def rtCalibration(fiContainer, allowedRtDev=60, allowedMzDev=2.5,
reference=None, specfiles=None, showPlots=False,
plotDir=None, minIntensity=1e5):
"""Performs a retention time calibration between :class:`FeatureItem` of multiple specfiles.
:ivar fiContainer: Perform alignme... | [
"def",
"rtCalibration",
"(",
"fiContainer",
",",
"allowedRtDev",
"=",
"60",
",",
"allowedMzDev",
"=",
"2.5",
",",
"reference",
"=",
"None",
",",
"specfiles",
"=",
"None",
",",
"showPlots",
"=",
"False",
",",
"plotDir",
"=",
"None",
",",
"minIntensity",
"="... | Performs a retention time calibration between :class:`FeatureItem` of multiple specfiles.
:ivar fiContainer: Perform alignment on :class:`FeatureItem` in :attr:`FeatureContainer.specfiles`
:ivar allowedRtDev: maxium retention time difference of two features in two runs to be matched
:ivar allowedMzDev: max... | [
"Performs",
"a",
"retention",
"time",
"calibration",
"between",
":",
"class",
":",
"FeatureItem",
"of",
"multiple",
"specfiles",
"."
] | python | train | 50.747967 |
arviz-devs/arviz | arviz/data/io_dict.py | https://github.com/arviz-devs/arviz/blob/d04d8da07f029fd2931f48d2f7f324cf393e5277/arviz/data/io_dict.py#L90-L96 | def prior_predictive_to_xarray(self):
"""Convert prior_predictive samples to xarray."""
data = self.prior_predictive
if not isinstance(data, dict):
raise TypeError("DictConverter.prior_predictive is not a dictionary")
return dict_to_dataset(data, library=None, coords=self.co... | [
"def",
"prior_predictive_to_xarray",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"prior_predictive",
"if",
"not",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"DictConverter.prior_predictive is not a dictionary\"",
")",
"return... | Convert prior_predictive samples to xarray. | [
"Convert",
"prior_predictive",
"samples",
"to",
"xarray",
"."
] | python | train | 47.857143 |
ehansis/ozelot | examples/leonardo/leonardo/kvstore/pipeline.py | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/examples/leonardo/leonardo/kvstore/pipeline.py#L149-L168 | def run(self):
"""Load all paintings into the database
"""
df = PaintingsInputData().load()
# rename columns
df.rename(columns={'paintingLabel': 'name'}, inplace=True)
# get artist IDs, map via artist wiki ID
artists = models.Entity.query_with_attributes('artis... | [
"def",
"run",
"(",
"self",
")",
":",
"df",
"=",
"PaintingsInputData",
"(",
")",
".",
"load",
"(",
")",
"# rename columns",
"df",
".",
"rename",
"(",
"columns",
"=",
"{",
"'paintingLabel'",
":",
"'name'",
"}",
",",
"inplace",
"=",
"True",
")",
"# get ar... | Load all paintings into the database | [
"Load",
"all",
"paintings",
"into",
"the",
"database"
] | python | train | 31.35 |
log2timeline/dfvfs | dfvfs/lib/sqlite_database.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/sqlite_database.py#L61-L93 | def GetNumberOfRows(self, table_name):
"""Retrieves the number of rows in the table.
Args:
table_name (str): name of the table.
Returns:
int: number of rows.
Raises:
IOError: if the file-like object has not been opened.
OSError: if the file-like object has not been opened.
... | [
"def",
"GetNumberOfRows",
"(",
"self",
",",
"table_name",
")",
":",
"if",
"not",
"self",
".",
"_connection",
":",
"raise",
"IOError",
"(",
"'Not opened.'",
")",
"self",
".",
"_cursor",
".",
"execute",
"(",
"self",
".",
"_NUMBER_OF_ROWS_QUERY",
".",
"format",... | Retrieves the number of rows in the table.
Args:
table_name (str): name of the table.
Returns:
int: number of rows.
Raises:
IOError: if the file-like object has not been opened.
OSError: if the file-like object has not been opened. | [
"Retrieves",
"the",
"number",
"of",
"rows",
"in",
"the",
"table",
"."
] | python | train | 29.121212 |
carpedm20/fbchat | fbchat/_client.py | https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L1005-L1045 | def fetchThreadMessages(self, thread_id=None, limit=20, before=None):
"""
Get the last messages in a thread
:param thread_id: User/Group ID to get messages from. See :ref:`intro_threads`
:param limit: Max. number of messages to retrieve
:param before: A timestamp, indicating fro... | [
"def",
"fetchThreadMessages",
"(",
"self",
",",
"thread_id",
"=",
"None",
",",
"limit",
"=",
"20",
",",
"before",
"=",
"None",
")",
":",
"thread_id",
",",
"thread_type",
"=",
"self",
".",
"_getThread",
"(",
"thread_id",
",",
"None",
")",
"params",
"=",
... | Get the last messages in a thread
:param thread_id: User/Group ID to get messages from. See :ref:`intro_threads`
:param limit: Max. number of messages to retrieve
:param before: A timestamp, indicating from which point to retrieve messages
:type limit: int
:type before: int
... | [
"Get",
"the",
"last",
"messages",
"in",
"a",
"thread"
] | python | train | 35.658537 |
zhmcclient/python-zhmcclient | zhmcclient/_metrics.py | https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_metrics.py#L272-L294 | def _setup_metric_group_definitions(self):
"""
Return the dict of MetricGroupDefinition objects for this metrics
context, by processing its 'metric-group-infos' property.
"""
# Dictionary of MetricGroupDefinition objects, by metric group name
metric_group_definitions = di... | [
"def",
"_setup_metric_group_definitions",
"(",
"self",
")",
":",
"# Dictionary of MetricGroupDefinition objects, by metric group name",
"metric_group_definitions",
"=",
"dict",
"(",
")",
"for",
"mg_info",
"in",
"self",
".",
"properties",
"[",
"'metric-group-infos'",
"]",
":... | Return the dict of MetricGroupDefinition objects for this metrics
context, by processing its 'metric-group-infos' property. | [
"Return",
"the",
"dict",
"of",
"MetricGroupDefinition",
"objects",
"for",
"this",
"metrics",
"context",
"by",
"processing",
"its",
"metric",
"-",
"group",
"-",
"infos",
"property",
"."
] | python | train | 47 |
ucsb-cs/submit | submit/helpers.py | https://github.com/ucsb-cs/submit/blob/92810c81255a4fc6bbebac1ac8aae856fd576ffe/submit/helpers.py#L106-L121 | def run(self, value, errors, request):
"""Return the object if valid and available, otherwise None."""
value = self.id_validator(value, errors, request)
if errors:
return None
if self.fetch_by:
thing = self.cls.fetch_by(**{self.fetch_by: value})
else:
... | [
"def",
"run",
"(",
"self",
",",
"value",
",",
"errors",
",",
"request",
")",
":",
"value",
"=",
"self",
".",
"id_validator",
"(",
"value",
",",
"errors",
",",
"request",
")",
"if",
"errors",
":",
"return",
"None",
"if",
"self",
".",
"fetch_by",
":",
... | Return the object if valid and available, otherwise None. | [
"Return",
"the",
"object",
"if",
"valid",
"and",
"available",
"otherwise",
"None",
"."
] | python | train | 40.875 |
Tanganelli/CoAPthon3 | coapthon/messages/message.py | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L484-L494 | def content_type(self, content_type):
"""
Set the Content-Type option of a response.
:type content_type: int
:param content_type: the Content-Type
"""
option = Option()
option.number = defines.OptionRegistry.CONTENT_TYPE.number
option.value = int(content_... | [
"def",
"content_type",
"(",
"self",
",",
"content_type",
")",
":",
"option",
"=",
"Option",
"(",
")",
"option",
".",
"number",
"=",
"defines",
".",
"OptionRegistry",
".",
"CONTENT_TYPE",
".",
"number",
"option",
".",
"value",
"=",
"int",
"(",
"content_type... | Set the Content-Type option of a response.
:type content_type: int
:param content_type: the Content-Type | [
"Set",
"the",
"Content",
"-",
"Type",
"option",
"of",
"a",
"response",
"."
] | python | train | 31.545455 |
mongolab/dex | dex/parsers.py | https://github.com/mongolab/dex/blob/f6dc27321028ef1ffdb3d4b1165fdcce7c8f20aa/dex/parsers.py#L67-L78 | def parse(self, input):
"""Passes input to each QueryLineHandler in use"""
query = None
for handler in self._line_handlers:
try:
query = handler.handle(input)
except Exception as e:
query = None
finally:
if query... | [
"def",
"parse",
"(",
"self",
",",
"input",
")",
":",
"query",
"=",
"None",
"for",
"handler",
"in",
"self",
".",
"_line_handlers",
":",
"try",
":",
"query",
"=",
"handler",
".",
"handle",
"(",
"input",
")",
"except",
"Exception",
"as",
"e",
":",
"quer... | Passes input to each QueryLineHandler in use | [
"Passes",
"input",
"to",
"each",
"QueryLineHandler",
"in",
"use"
] | python | train | 31.25 |
KelSolaar/Umbra | umbra/components/factory/script_editor/models.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/factory/script_editor/models.py#L475-L502 | def unregister_file(self, file_node, raise_exception=False):
"""
Unregisters given :class:`umbra.components.factory.script_editor.nodes.FileNode` class Node from the Model.
:param file_node: FileNode to unregister.
:type file_node: FileNode
:param raise_exception: Raise the exce... | [
"def",
"unregister_file",
"(",
"self",
",",
"file_node",
",",
"raise_exception",
"=",
"False",
")",
":",
"if",
"raise_exception",
":",
"if",
"not",
"file_node",
"in",
"self",
".",
"list_file_nodes",
"(",
")",
":",
"raise",
"foundations",
".",
"exceptions",
"... | Unregisters given :class:`umbra.components.factory.script_editor.nodes.FileNode` class Node from the Model.
:param file_node: FileNode to unregister.
:type file_node: FileNode
:param raise_exception: Raise the exception.
:type raise_exception: bool
:return: FileNode.
:rt... | [
"Unregisters",
"given",
":",
"class",
":",
"umbra",
".",
"components",
".",
"factory",
".",
"script_editor",
".",
"nodes",
".",
"FileNode",
"class",
"Node",
"from",
"the",
"Model",
"."
] | python | train | 36.071429 |
littlemo/moear-api-common | moear_api_common/utils/__init__.py | https://github.com/littlemo/moear-api-common/blob/2a89a052d92592dd8e67bd50ec2fadc0219ac5d0/moear_api_common/utils/__init__.py#L29-L46 | def get_config_dict(config):
'''
获取配置数据字典
对传入的配置包进行格式化处理,生成一个字典对象
:param object config: 配置模块
:return: 配置数据字典
:rtype: dict
'''
dst = {}
tmp = config.__dict__
key_list = dir(config)
key_list.remove('os')
for k, v in tmp.items():
if k in key_list and not k.startswi... | [
"def",
"get_config_dict",
"(",
"config",
")",
":",
"dst",
"=",
"{",
"}",
"tmp",
"=",
"config",
".",
"__dict__",
"key_list",
"=",
"dir",
"(",
"config",
")",
"key_list",
".",
"remove",
"(",
"'os'",
")",
"for",
"k",
",",
"v",
"in",
"tmp",
".",
"items"... | 获取配置数据字典
对传入的配置包进行格式化处理,生成一个字典对象
:param object config: 配置模块
:return: 配置数据字典
:rtype: dict | [
"获取配置数据字典"
] | python | train | 19.388889 |
ionelmc/python-cogen | cogen/core/events.py | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/events.py#L222-L228 | def cleanup(self, sched, coro):
"""Remove this coro from the waiting for signal queue."""
try:
sched.sigwait[self.name].remove((self, coro))
except ValueError:
pass
return True | [
"def",
"cleanup",
"(",
"self",
",",
"sched",
",",
"coro",
")",
":",
"try",
":",
"sched",
".",
"sigwait",
"[",
"self",
".",
"name",
"]",
".",
"remove",
"(",
"(",
"self",
",",
"coro",
")",
")",
"except",
"ValueError",
":",
"pass",
"return",
"True"
] | Remove this coro from the waiting for signal queue. | [
"Remove",
"this",
"coro",
"from",
"the",
"waiting",
"for",
"signal",
"queue",
"."
] | python | train | 33.142857 |
materialsproject/pymatgen | pymatgen/io/lammps/utils.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/lammps/utils.py#L137-L166 | def _add_monomer(self, monomer, mon_vector, move_direction):
"""
extend the polymer molecule by adding a monomer along mon_vector direction
Args:
monomer (Molecule): monomer molecule
mon_vector (numpy.array): monomer vector that points from head to tail.
move... | [
"def",
"_add_monomer",
"(",
"self",
",",
"monomer",
",",
"mon_vector",
",",
"move_direction",
")",
":",
"translate_by",
"=",
"self",
".",
"molecule",
".",
"cart_coords",
"[",
"self",
".",
"end",
"]",
"+",
"self",
".",
"link_distance",
"*",
"move_direction",
... | extend the polymer molecule by adding a monomer along mon_vector direction
Args:
monomer (Molecule): monomer molecule
mon_vector (numpy.array): monomer vector that points from head to tail.
move_direction (numpy.array): direction along which the monomer
will ... | [
"extend",
"the",
"polymer",
"molecule",
"by",
"adding",
"a",
"monomer",
"along",
"mon_vector",
"direction"
] | python | train | 42.833333 |
abseil/abseil-py | absl/app.py | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/app.py#L231-L251 | def _run_main(main, argv):
"""Calls main, optionally with pdb or profiler."""
if FLAGS.run_with_pdb:
sys.exit(pdb.runcall(main, argv))
elif FLAGS.run_with_profiling or FLAGS.profile_file:
# Avoid import overhead since most apps (including performance-sensitive
# ones) won't be run with profiling.
... | [
"def",
"_run_main",
"(",
"main",
",",
"argv",
")",
":",
"if",
"FLAGS",
".",
"run_with_pdb",
":",
"sys",
".",
"exit",
"(",
"pdb",
".",
"runcall",
"(",
"main",
",",
"argv",
")",
")",
"elif",
"FLAGS",
".",
"run_with_profiling",
"or",
"FLAGS",
".",
"prof... | Calls main, optionally with pdb or profiler. | [
"Calls",
"main",
"optionally",
"with",
"pdb",
"or",
"profiler",
"."
] | python | train | 32.904762 |
smdabdoub/phylotoast | bin/extract_shared_or_unique_otuids.py | https://github.com/smdabdoub/phylotoast/blob/0b74ef171e6a84761710548501dfac71285a58a3/bin/extract_shared_or_unique_otuids.py#L51-L66 | def unique_otuids(groups):
"""
Get unique OTUIDs of each category.
:type groups: Dict
:param groups: {Category name: OTUIDs in category}
:return type: dict
:return: Dict keyed on category name and unique OTUIDs as values.
"""
uniques = {key: set() for key in groups}
for i, group in... | [
"def",
"unique_otuids",
"(",
"groups",
")",
":",
"uniques",
"=",
"{",
"key",
":",
"set",
"(",
")",
"for",
"key",
"in",
"groups",
"}",
"for",
"i",
",",
"group",
"in",
"enumerate",
"(",
"groups",
")",
":",
"to_combine",
"=",
"groups",
".",
"values",
... | Get unique OTUIDs of each category.
:type groups: Dict
:param groups: {Category name: OTUIDs in category}
:return type: dict
:return: Dict keyed on category name and unique OTUIDs as values. | [
"Get",
"unique",
"OTUIDs",
"of",
"each",
"category",
"."
] | python | train | 31.9375 |
Erotemic/utool | utool/util_cplat.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_cplat.py#L66-L76 | def get_plat_specifier():
"""
Standard platform specifier used by distutils
"""
import setuptools # NOQA
import distutils
plat_name = distutils.util.get_platform()
plat_specifier = ".%s-%s" % (plat_name, sys.version[0:3])
if hasattr(sys, 'gettotalrefcount'):
plat_specifier += '-... | [
"def",
"get_plat_specifier",
"(",
")",
":",
"import",
"setuptools",
"# NOQA",
"import",
"distutils",
"plat_name",
"=",
"distutils",
".",
"util",
".",
"get_platform",
"(",
")",
"plat_specifier",
"=",
"\".%s-%s\"",
"%",
"(",
"plat_name",
",",
"sys",
".",
"versio... | Standard platform specifier used by distutils | [
"Standard",
"platform",
"specifier",
"used",
"by",
"distutils"
] | python | train | 31.272727 |
coleifer/walrus | walrus/containers.py | https://github.com/coleifer/walrus/blob/82bf15a6613487b5b5fefeb488f186d7e0106547/walrus/containers.py#L1232-L1240 | def ack(self, *id_list):
"""
Acknowledge that the message(s) were been processed by the consumer
associated with the parent :py:class:`ConsumerGroup`.
:param id_list: one or more message ids to acknowledge
:returns: number of messages marked acknowledged
"""
retu... | [
"def",
"ack",
"(",
"self",
",",
"*",
"id_list",
")",
":",
"return",
"self",
".",
"database",
".",
"xack",
"(",
"self",
".",
"key",
",",
"self",
".",
"group",
",",
"*",
"id_list",
")"
] | Acknowledge that the message(s) were been processed by the consumer
associated with the parent :py:class:`ConsumerGroup`.
:param id_list: one or more message ids to acknowledge
:returns: number of messages marked acknowledged | [
"Acknowledge",
"that",
"the",
"message",
"(",
"s",
")",
"were",
"been",
"processed",
"by",
"the",
"consumer",
"associated",
"with",
"the",
"parent",
":",
"py",
":",
"class",
":",
"ConsumerGroup",
"."
] | python | train | 40.555556 |
bolt-project/bolt | bolt/spark/array.py | https://github.com/bolt-project/bolt/blob/9cd7104aa085498da3097b72696184b9d3651c51/bolt/spark/array.py#L920-L930 | def astype(self, dtype, casting='unsafe'):
"""
Cast the array to a specified type.
Parameters
----------
dtype : str or dtype
Typecode or data-type to cast the array to (see numpy)
"""
rdd = self._rdd.mapValues(lambda v: v.astype(dtype, 'K', casting))... | [
"def",
"astype",
"(",
"self",
",",
"dtype",
",",
"casting",
"=",
"'unsafe'",
")",
":",
"rdd",
"=",
"self",
".",
"_rdd",
".",
"mapValues",
"(",
"lambda",
"v",
":",
"v",
".",
"astype",
"(",
"dtype",
",",
"'K'",
",",
"casting",
")",
")",
"return",
"... | Cast the array to a specified type.
Parameters
----------
dtype : str or dtype
Typecode or data-type to cast the array to (see numpy) | [
"Cast",
"the",
"array",
"to",
"a",
"specified",
"type",
"."
] | python | test | 34.545455 |
hydpy-dev/hydpy | hydpy/exe/servertools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/exe/servertools.py#L1086-L1093 | def GET_savedmodifiedconditionitemvalues(self) -> None:
"""ToDo: extend functionality and add tests"""
dict_ = state.modifiedconditionitemvalues.get(self._id)
if dict_ is None:
self.GET_conditionitemvalues()
else:
for name, value in dict_.items():
... | [
"def",
"GET_savedmodifiedconditionitemvalues",
"(",
"self",
")",
"->",
"None",
":",
"dict_",
"=",
"state",
".",
"modifiedconditionitemvalues",
".",
"get",
"(",
"self",
".",
"_id",
")",
"if",
"dict_",
"is",
"None",
":",
"self",
".",
"GET_conditionitemvalues",
"... | ToDo: extend functionality and add tests | [
"ToDo",
":",
"extend",
"functionality",
"and",
"add",
"tests"
] | python | train | 42.5 |
jhermann/rituals | src/rituals/acts/documentation.py | https://github.com/jhermann/rituals/blob/1534f50d81e19bbbe799e2eba0acdefbce047c06/src/rituals/acts/documentation.py#L313-L348 | def _to_webdav(self, docs_base, release):
"""Upload to WebDAV store."""
try:
git_path = subprocess.check_output('git remote get-url origin 2>/dev/null', shell=True)
except subprocess.CalledProcessError:
git_path = ''
else:
git_path = git_path.decode('a... | [
"def",
"_to_webdav",
"(",
"self",
",",
"docs_base",
",",
"release",
")",
":",
"try",
":",
"git_path",
"=",
"subprocess",
".",
"check_output",
"(",
"'git remote get-url origin 2>/dev/null'",
",",
"shell",
"=",
"True",
")",
"except",
"subprocess",
".",
"CalledProc... | Upload to WebDAV store. | [
"Upload",
"to",
"WebDAV",
"store",
"."
] | python | valid | 48.75 |
bitlabstudio/django-libs | django_libs/middleware.py | https://github.com/bitlabstudio/django-libs/blob/2c5376cda084bf16edea540e0f6999f1d844afd0/django_libs/middleware.py#L36-L41 | def process_exception(self, request, exception):
"""
Add user details.
"""
if request.user and hasattr(request.user, 'email'):
request.META['USER'] = request.user.email | [
"def",
"process_exception",
"(",
"self",
",",
"request",
",",
"exception",
")",
":",
"if",
"request",
".",
"user",
"and",
"hasattr",
"(",
"request",
".",
"user",
",",
"'email'",
")",
":",
"request",
".",
"META",
"[",
"'USER'",
"]",
"=",
"request",
".",... | Add user details. | [
"Add",
"user",
"details",
"."
] | python | train | 34.5 |
tango-controls/pytango | tango/databaseds/database.py | https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/databaseds/database.py#L846-L855 | def DbGetHostServersInfo(self, argin):
""" Get info about all servers running on specified host, name, mode and level
:param argin: Host name
:type: tango.DevString
:return: Server info for all servers running on specified host
:rtype: tango.DevVarStringArray """
self._l... | [
"def",
"DbGetHostServersInfo",
"(",
"self",
",",
"argin",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"\"In DbGetHostServersInfo()\"",
")",
"argin",
"=",
"replace_wildcard",
"(",
"argin",
")",
"return",
"self",
".",
"db",
".",
"get_host_servers_info",
"(... | Get info about all servers running on specified host, name, mode and level
:param argin: Host name
:type: tango.DevString
:return: Server info for all servers running on specified host
:rtype: tango.DevVarStringArray | [
"Get",
"info",
"about",
"all",
"servers",
"running",
"on",
"specified",
"host",
"name",
"mode",
"and",
"level"
] | python | train | 44 |
gem/oq-engine | openquake/calculators/views.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L193-L205 | def view_contents(token, dstore):
"""
Returns the size of the contents of the datastore and its total size
"""
try:
desc = dstore['oqparam'].description
except KeyError:
desc = ''
data = sorted((dstore.getsize(key), key) for key in dstore)
rows = [(key, humansize(nbytes)) for... | [
"def",
"view_contents",
"(",
"token",
",",
"dstore",
")",
":",
"try",
":",
"desc",
"=",
"dstore",
"[",
"'oqparam'",
"]",
".",
"description",
"except",
"KeyError",
":",
"desc",
"=",
"''",
"data",
"=",
"sorted",
"(",
"(",
"dstore",
".",
"getsize",
"(",
... | Returns the size of the contents of the datastore and its total size | [
"Returns",
"the",
"size",
"of",
"the",
"contents",
"of",
"the",
"datastore",
"and",
"its",
"total",
"size"
] | python | train | 37 |
zetaops/zengine | zengine/messaging/views.py | https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/messaging/views.py#L487-L528 | def add_unit_to_channel(current):
"""
Subscribe users of a given unit to given channel
JSON API:
.. code-block:: python
# request:
{
'view':'_zops_add_unit_to_channel',
'unit_key': key,
'ch... | [
"def",
"add_unit_to_channel",
"(",
"current",
")",
":",
"read_only",
"=",
"current",
".",
"input",
"[",
"'read_only'",
"]",
"newly_added",
",",
"existing",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"member_key",
"in",
"UnitModel",
".",
"get_user_keys",
"(",
"cu... | Subscribe users of a given unit to given channel
JSON API:
.. code-block:: python
# request:
{
'view':'_zops_add_unit_to_channel',
'unit_key': key,
'channel_key': key,
'read_only': ... | [
"Subscribe",
"users",
"of",
"a",
"given",
"unit",
"to",
"given",
"channel"
] | python | train | 34.071429 |
release-engineering/productmd | productmd/common.py | https://github.com/release-engineering/productmd/blob/49256bf2e8c84124f42346241140b986ad7bfc38/productmd/common.py#L172-L190 | def _open_file_obj(f, mode="r"):
"""
A context manager that provides access to a file.
:param f: the file to be opened
:type f: a file-like object or path to file
:param mode: how to open the file
:type mode: string
"""
if isinstance(f, six.string_types):
if f.startswith(("http:... | [
"def",
"_open_file_obj",
"(",
"f",
",",
"mode",
"=",
"\"r\"",
")",
":",
"if",
"isinstance",
"(",
"f",
",",
"six",
".",
"string_types",
")",
":",
"if",
"f",
".",
"startswith",
"(",
"(",
"\"http://\"",
",",
"\"https://\"",
")",
")",
":",
"file_obj",
"=... | A context manager that provides access to a file.
:param f: the file to be opened
:type f: a file-like object or path to file
:param mode: how to open the file
:type mode: string | [
"A",
"context",
"manager",
"that",
"provides",
"access",
"to",
"a",
"file",
"."
] | python | train | 27.684211 |
scrapinghub/dateparser | dateparser/languages/loader.py | https://github.com/scrapinghub/dateparser/blob/11a761c99d3ee522a3c63756b70c106a579e8b5c/dateparser/languages/loader.py#L85-L121 | def get_locales(self, languages=None, locales=None, region=None,
use_given_order=False, allow_conflicting_locales=False):
"""
Yield locale instances.
:param languages:
A list of language codes, e.g. ['en', 'es', 'zh-Hant'].
If locales are not given, l... | [
"def",
"get_locales",
"(",
"self",
",",
"languages",
"=",
"None",
",",
"locales",
"=",
"None",
",",
"region",
"=",
"None",
",",
"use_given_order",
"=",
"False",
",",
"allow_conflicting_locales",
"=",
"False",
")",
":",
"for",
"_",
",",
"locale",
"in",
"s... | Yield locale instances.
:param languages:
A list of language codes, e.g. ['en', 'es', 'zh-Hant'].
If locales are not given, languages and region are
used to construct locales to load.
:type languages: list
:param locales:
A list of codes of local... | [
"Yield",
"locale",
"instances",
"."
] | python | test | 37.837838 |
mjirik/imcut | imcut/pycut.py | https://github.com/mjirik/imcut/blob/1b38e7cd18a7a38fe683c1cabe1222fe5fa03aa3/imcut/pycut.py#L1539-L1555 | def get_node_msindex(msinds, node_seed):
"""
Convert seeds-like selection of voxel to multiscale index.
:param msinds: ndarray with indexes
:param node_seed: ndarray with 1 where selected pixel is, or list of indexes in this array
:return: multiscale index of first found seed
"""
if type(nod... | [
"def",
"get_node_msindex",
"(",
"msinds",
",",
"node_seed",
")",
":",
"if",
"type",
"(",
"node_seed",
")",
"==",
"np",
".",
"ndarray",
":",
"seed_indexes",
"=",
"np",
".",
"nonzero",
"(",
"node_seed",
")",
"elif",
"type",
"(",
"node_seed",
")",
"==",
"... | Convert seeds-like selection of voxel to multiscale index.
:param msinds: ndarray with indexes
:param node_seed: ndarray with 1 where selected pixel is, or list of indexes in this array
:return: multiscale index of first found seed | [
"Convert",
"seeds",
"-",
"like",
"selection",
"of",
"voxel",
"to",
"multiscale",
"index",
".",
":",
"param",
"msinds",
":",
"ndarray",
"with",
"indexes",
":",
"param",
"node_seed",
":",
"ndarray",
"with",
"1",
"where",
"selected",
"pixel",
"is",
"or",
"lis... | python | train | 35.352941 |
cpburnz/python-path-specification | pathspec/util.py | https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/util.py#L57-L126 | def _iter_tree_next(root_full, dir_rel, memo, on_error, follow_links):
"""
Scan the directory for all descendant files.
*root_full* (:class:`str`) the absolute path to the root directory.
*dir_rel* (:class:`str`) the path to the directory to scan relative to
*root_full*.
*memo* (:class:`dict`) keeps track of a... | [
"def",
"_iter_tree_next",
"(",
"root_full",
",",
"dir_rel",
",",
"memo",
",",
"on_error",
",",
"follow_links",
")",
":",
"dir_full",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root_full",
",",
"dir_rel",
")",
"dir_real",
"=",
"os",
".",
"path",
".",
"r... | Scan the directory for all descendant files.
*root_full* (:class:`str`) the absolute path to the root directory.
*dir_rel* (:class:`str`) the path to the directory to scan relative to
*root_full*.
*memo* (:class:`dict`) keeps track of ancestor directories
encountered. Maps each ancestor real path (:class:`str``... | [
"Scan",
"the",
"directory",
"for",
"all",
"descendant",
"files",
"."
] | python | train | 32.371429 |
Overboard/httpfind | httpfind/httpfind.py | https://github.com/Overboard/httpfind/blob/2c372daa66dcc7158e8bb179b29d8001d473bc4a/httpfind/httpfind.py#L17-L65 | async def fetch_page(session, host):
""" Perform the page fetch from an individual host.
`session` - An aiohttp
[client session](http://aiohttp.readthedocs.io/en/stable/client_reference.html#client-session)
`host` - URL to fetch
`return` tuple with the following:
* The host parameter
... | [
"async",
"def",
"fetch_page",
"(",
"session",
",",
"host",
")",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"random",
".",
"randint",
"(",
"0",
",",
"25",
")",
"*",
"0.1",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"logger",
".",
"info",
"... | Perform the page fetch from an individual host.
`session` - An aiohttp
[client session](http://aiohttp.readthedocs.io/en/stable/client_reference.html#client-session)
`host` - URL to fetch
`return` tuple with the following:
* The host parameter
* A vague status string
* Text ... | [
"Perform",
"the",
"page",
"fetch",
"from",
"an",
"individual",
"host",
"."
] | python | train | 39.183673 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.