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 |
|---|---|---|---|---|---|---|---|---|---|
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_firmware.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_firmware.py#L165-L171 | def filter_rows(self, filters, rows):
'''returns rows as filtered by filters'''
ret = []
for row in rows:
if not self.row_is_filtered(row, filters):
ret.append(row)
return ret | [
"def",
"filter_rows",
"(",
"self",
",",
"filters",
",",
"rows",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"row",
"in",
"rows",
":",
"if",
"not",
"self",
".",
"row_is_filtered",
"(",
"row",
",",
"filters",
")",
":",
"ret",
".",
"append",
"(",
"row",
... | returns rows as filtered by filters | [
"returns",
"rows",
"as",
"filtered",
"by",
"filters"
] | python | train | 32.714286 |
aparo/pyes | pyes/managers.py | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/managers.py#L406-L414 | def gateway_snapshot(self, indices=None):
"""
Gateway snapshot one or more indices
(See :ref:`es-guide-reference-api-admin-indices-gateway-snapshot`)
:keyword indices: a list of indices or None for default configured.
"""
path = self.conn._make_path(indices, (), '_gatewa... | [
"def",
"gateway_snapshot",
"(",
"self",
",",
"indices",
"=",
"None",
")",
":",
"path",
"=",
"self",
".",
"conn",
".",
"_make_path",
"(",
"indices",
",",
"(",
")",
",",
"'_gateway'",
",",
"'snapshot'",
")",
"return",
"self",
".",
"conn",
".",
"_send_req... | Gateway snapshot one or more indices
(See :ref:`es-guide-reference-api-admin-indices-gateway-snapshot`)
:keyword indices: a list of indices or None for default configured. | [
"Gateway",
"snapshot",
"one",
"or",
"more",
"indices",
"(",
"See",
":",
"ref",
":",
"es",
"-",
"guide",
"-",
"reference",
"-",
"api",
"-",
"admin",
"-",
"indices",
"-",
"gateway",
"-",
"snapshot",
")"
] | python | train | 42.222222 |
emory-libraries/eulfedora | eulfedora/api.py | https://github.com/emory-libraries/eulfedora/blob/161826f3fdcdab4007f6fa7dfd9f1ecabc4bcbe4/eulfedora/api.py#L788-L801 | def setDatastreamVersionable(self, pid, dsID, versionable):
'''Update datastream versionable setting.
:param pid: object pid
:param dsID: datastream id
:param versionable: boolean
:returns: boolean success
'''
# /objects/{pid}/datastreams/{dsID} ? [versionable]
... | [
"def",
"setDatastreamVersionable",
"(",
"self",
",",
"pid",
",",
"dsID",
",",
"versionable",
")",
":",
"# /objects/{pid}/datastreams/{dsID} ? [versionable]",
"http_args",
"=",
"{",
"'versionable'",
":",
"versionable",
"}",
"url",
"=",
"'objects/%(pid)s/datastreams/%(dsid)... | Update datastream versionable setting.
:param pid: object pid
:param dsID: datastream id
:param versionable: boolean
:returns: boolean success | [
"Update",
"datastream",
"versionable",
"setting",
"."
] | python | train | 42.214286 |
APSL/transmanager | transmanager/utils.py | https://github.com/APSL/transmanager/blob/79157085840008e146b264521681913090197ed1/transmanager/utils.py#L9-L24 | def get_application_choices():
"""
Get the select options for the application selector
:return:
"""
result = []
keys = set()
for ct in ContentType.objects.order_by('app_label', 'model'):
try:
if issubclass(ct.model_class(), TranslatableModel) and ct.app_label not in keys... | [
"def",
"get_application_choices",
"(",
")",
":",
"result",
"=",
"[",
"]",
"keys",
"=",
"set",
"(",
")",
"for",
"ct",
"in",
"ContentType",
".",
"objects",
".",
"order_by",
"(",
"'app_label'",
",",
"'model'",
")",
":",
"try",
":",
"if",
"issubclass",
"("... | Get the select options for the application selector
:return: | [
"Get",
"the",
"select",
"options",
"for",
"the",
"application",
"selector"
] | python | train | 31.8125 |
senaite/senaite.core | bika/lims/barcode.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/barcode.py#L121-L129 | def handle_Sample(self, instance):
"""If this sample has a single AR, go there.
If the sample has 0 or >1 ARs, go to the sample's view URL.
"""
ars = instance.getAnalysisRequests()
if len(ars) == 1:
return self.handle_AnalysisRequest(ars[0])
else:
... | [
"def",
"handle_Sample",
"(",
"self",
",",
"instance",
")",
":",
"ars",
"=",
"instance",
".",
"getAnalysisRequests",
"(",
")",
"if",
"len",
"(",
"ars",
")",
"==",
"1",
":",
"return",
"self",
".",
"handle_AnalysisRequest",
"(",
"ars",
"[",
"0",
"]",
")",... | If this sample has a single AR, go there.
If the sample has 0 or >1 ARs, go to the sample's view URL. | [
"If",
"this",
"sample",
"has",
"a",
"single",
"AR",
"go",
"there",
".",
"If",
"the",
"sample",
"has",
"0",
"or",
">",
"1",
"ARs",
"go",
"to",
"the",
"sample",
"s",
"view",
"URL",
"."
] | python | train | 38 |
LionelR/pyair | pyair/reg.py | https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/reg.py#L632-L678 | def excel_synthese(fct, df, excel_file):
"""
Enregistre dans un fichier Excel une synthèse des calculs réglementaires en
fournissant les valeurs calculées suivant les réglementations définies dans
chaque fonction de calcul et un tableau de nombre de dépassement.
Les résultats sont enregistrés
P... | [
"def",
"excel_synthese",
"(",
"fct",
",",
"df",
",",
"excel_file",
")",
":",
"def",
"sheet_name",
"(",
"name",
")",
":",
"# formatage du nom des feuilles (suppression des guillements, :, ...)",
"name",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFKD'",
",",
"name"... | Enregistre dans un fichier Excel une synthèse des calculs réglementaires en
fournissant les valeurs calculées suivant les réglementations définies dans
chaque fonction de calcul et un tableau de nombre de dépassement.
Les résultats sont enregistrés
Paramètres:
fct: fonction renvoyant les éléments c... | [
"Enregistre",
"dans",
"un",
"fichier",
"Excel",
"une",
"synthèse",
"des",
"calculs",
"réglementaires",
"en",
"fournissant",
"les",
"valeurs",
"calculées",
"suivant",
"les",
"réglementations",
"définies",
"dans",
"chaque",
"fonction",
"de",
"calcul",
"et",
"un",
"t... | python | valid | 31.06383 |
wtolson/gnsq | gnsq/nsqd.py | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L622-L644 | def stats(self, topic=None, channel=None, text=False):
"""Return internal instrumented statistics.
:param topic: (optional) filter to topic
:param channel: (optional) filter to channel
:param text: return the stats as a string (default: ``False``)
"""
if text:
... | [
"def",
"stats",
"(",
"self",
",",
"topic",
"=",
"None",
",",
"channel",
"=",
"None",
",",
"text",
"=",
"False",
")",
":",
"if",
"text",
":",
"fields",
"=",
"{",
"'format'",
":",
"'text'",
"}",
"else",
":",
"fields",
"=",
"{",
"'format'",
":",
"'j... | Return internal instrumented statistics.
:param topic: (optional) filter to topic
:param channel: (optional) filter to channel
:param text: return the stats as a string (default: ``False``) | [
"Return",
"internal",
"instrumented",
"statistics",
"."
] | python | train | 28.652174 |
praekeltfoundation/seaworthy | docs/apigen.py | https://github.com/praekeltfoundation/seaworthy/blob/6f10a19b45d4ea1dc3bd0553cc4d0438696c079c/docs/apigen.py#L62-L83 | def create_autosummary_file(modules, opts):
# type: (List[unicode], Any, unicode) -> None
"""Create the module's index."""
lines = [
'API Reference',
'=============',
'',
'.. autosummary::',
' :template: api_module.rst',
' :toctree: {}'.format(opts.destdir... | [
"def",
"create_autosummary_file",
"(",
"modules",
",",
"opts",
")",
":",
"# type: (List[unicode], Any, unicode) -> None",
"lines",
"=",
"[",
"'API Reference'",
",",
"'============='",
",",
"''",
",",
"'.. autosummary::'",
",",
"' :template: api_module.rst'",
",",
"' :... | Create the module's index. | [
"Create",
"the",
"module",
"s",
"index",
"."
] | python | train | 29.045455 |
saltstack/salt | salt/states/mount.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mount.py#L61-L728 | def mounted(name,
device,
fstype,
mkmnt=False,
opts='defaults',
dump=0,
pass_num=0,
config='/etc/fstab',
persist=True,
mount=True,
user=None,
match_on='auto',
device_name_regex... | [
"def",
"mounted",
"(",
"name",
",",
"device",
",",
"fstype",
",",
"mkmnt",
"=",
"False",
",",
"opts",
"=",
"'defaults'",
",",
"dump",
"=",
"0",
",",
"pass_num",
"=",
"0",
",",
"config",
"=",
"'/etc/fstab'",
",",
"persist",
"=",
"True",
",",
"mount",
... | Verify that a device is mounted
name
The path to the location where the device is to be mounted
device
The device name, typically the device node, such as ``/dev/sdb1``
or ``UUID=066e0200-2867-4ebe-b9e6-f30026ca2314`` or ``LABEL=DATA``
fstype
The filesystem type, this will... | [
"Verify",
"that",
"a",
"device",
"is",
"mounted"
] | python | train | 44.976048 |
aaugustin/websockets | src/websockets/protocol.py | https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L953-L969 | async def write_close_frame(self, data: bytes = b"") -> None:
"""
Write a close frame if and only if the connection state is OPEN.
This dedicated coroutine must be used for writing close frames to
ensure that at most one close frame is sent on a given connection.
"""
# ... | [
"async",
"def",
"write_close_frame",
"(",
"self",
",",
"data",
":",
"bytes",
"=",
"b\"\"",
")",
"->",
"None",
":",
"# Test and set the connection state before sending the close frame to",
"# avoid sending two frames in case of concurrent calls.",
"if",
"self",
".",
"state",
... | Write a close frame if and only if the connection state is OPEN.
This dedicated coroutine must be used for writing close frames to
ensure that at most one close frame is sent on a given connection. | [
"Write",
"a",
"close",
"frame",
"if",
"and",
"only",
"if",
"the",
"connection",
"state",
"is",
"OPEN",
"."
] | python | train | 46.058824 |
alvinwan/TexSoup | TexSoup/reader.py | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/reader.py#L109-L120 | def tokenize_punctuation_command(text):
"""Process command that augments or modifies punctuation.
This is important to the tokenization of a string, as opening or closing
punctuation is not supposed to match.
:param Buffer text: iterator over text, with current position
"""
if text.peek() == '... | [
"def",
"tokenize_punctuation_command",
"(",
"text",
")",
":",
"if",
"text",
".",
"peek",
"(",
")",
"==",
"'\\\\'",
":",
"for",
"point",
"in",
"PUNCTUATION_COMMANDS",
":",
"if",
"text",
".",
"peek",
"(",
"(",
"1",
",",
"len",
"(",
"point",
")",
"+",
"... | Process command that augments or modifies punctuation.
This is important to the tokenization of a string, as opening or closing
punctuation is not supposed to match.
:param Buffer text: iterator over text, with current position | [
"Process",
"command",
"that",
"augments",
"or",
"modifies",
"punctuation",
"."
] | python | train | 38.666667 |
manns/pyspread | pyspread/src/gui/_main_window.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_main_window.py#L1407-L1425 | def OnTextColorDialog(self, event):
"""Event handler for launching text color dialog"""
dlg = wx.ColourDialog(self.main_window)
# Ensure the full colour dialog is displayed,
# not the abbreviated version.
dlg.GetColourData().SetChooseFull(True)
if dlg.ShowModal() == wx... | [
"def",
"OnTextColorDialog",
"(",
"self",
",",
"event",
")",
":",
"dlg",
"=",
"wx",
".",
"ColourDialog",
"(",
"self",
".",
"main_window",
")",
"# Ensure the full colour dialog is displayed,",
"# not the abbreviated version.",
"dlg",
".",
"GetColourData",
"(",
")",
".... | Event handler for launching text color dialog | [
"Event",
"handler",
"for",
"launching",
"text",
"color",
"dialog"
] | python | train | 30.210526 |
vertexproject/synapse | synapse/datamodel.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/datamodel.py#L389-L411 | def addDataModels(self, mods):
'''
Adds a model definition (same format as input to Model.addDataModels and output of Model.getModelDef).
'''
# Load all the universal properties
for _, mdef in mods:
for univname, _, _ in mdef.get('univs', ()):
self.add... | [
"def",
"addDataModels",
"(",
"self",
",",
"mods",
")",
":",
"# Load all the universal properties",
"for",
"_",
",",
"mdef",
"in",
"mods",
":",
"for",
"univname",
",",
"_",
",",
"_",
"in",
"mdef",
".",
"get",
"(",
"'univs'",
",",
"(",
")",
")",
":",
"... | Adds a model definition (same format as input to Model.addDataModels and output of Model.getModelDef). | [
"Adds",
"a",
"model",
"definition",
"(",
"same",
"format",
"as",
"input",
"to",
"Model",
".",
"addDataModels",
"and",
"output",
"of",
"Model",
".",
"getModelDef",
")",
"."
] | python | train | 36 |
spacetelescope/stsci.tools | lib/stsci/tools/parseinput.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/parseinput.py#L185-L218 | def countinputs(inputlist):
"""
Determine the number of inputfiles provided by the user and the
number of those files that are association tables
Parameters
----------
inputlist : string
the user input
Returns
-------
numInputs: int
number of inputs provided by th... | [
"def",
"countinputs",
"(",
"inputlist",
")",
":",
"# Initialize return values",
"numInputs",
"=",
"0",
"numASNfiles",
"=",
"0",
"# User irafglob to count the number of inputfiles",
"files",
"=",
"irafglob",
"(",
"inputlist",
",",
"atfile",
"=",
"None",
")",
"# Use the... | Determine the number of inputfiles provided by the user and the
number of those files that are association tables
Parameters
----------
inputlist : string
the user input
Returns
-------
numInputs: int
number of inputs provided by the user
numASNfiles: int
numb... | [
"Determine",
"the",
"number",
"of",
"inputfiles",
"provided",
"by",
"the",
"user",
"and",
"the",
"number",
"of",
"those",
"files",
"that",
"are",
"association",
"tables"
] | python | train | 24.823529 |
kelproject/pykube | pykube/http.py | https://github.com/kelproject/pykube/blob/e8a46298a592ad9037587afb707ac75b3114eff9/pykube/http.py#L178-L185 | def version(self):
"""
Get Kubernetes API version
"""
response = self.get(version="", base="/version")
response.raise_for_status()
data = response.json()
return (data["major"], data["minor"]) | [
"def",
"version",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"get",
"(",
"version",
"=",
"\"\"",
",",
"base",
"=",
"\"/version\"",
")",
"response",
".",
"raise_for_status",
"(",
")",
"data",
"=",
"response",
".",
"json",
"(",
")",
"return",
... | Get Kubernetes API version | [
"Get",
"Kubernetes",
"API",
"version"
] | python | train | 30 |
saltstack/salt | salt/cloud/__init__.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L623-L657 | def map_providers(self, query='list_nodes', cached=False):
'''
Return a mapping of what named VMs are running on what VM providers
based on what providers are defined in the configuration and VMs
'''
if cached is True and query in self.__cached_provider_queries:
retur... | [
"def",
"map_providers",
"(",
"self",
",",
"query",
"=",
"'list_nodes'",
",",
"cached",
"=",
"False",
")",
":",
"if",
"cached",
"is",
"True",
"and",
"query",
"in",
"self",
".",
"__cached_provider_queries",
":",
"return",
"self",
".",
"__cached_provider_queries"... | Return a mapping of what named VMs are running on what VM providers
based on what providers are defined in the configuration and VMs | [
"Return",
"a",
"mapping",
"of",
"what",
"named",
"VMs",
"are",
"running",
"on",
"what",
"VM",
"providers",
"based",
"on",
"what",
"providers",
"are",
"defined",
"in",
"the",
"configuration",
"and",
"VMs"
] | python | train | 44.371429 |
mozilla/taar | taar/recommenders/hybrid_recommender.py | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/hybrid_recommender.py#L28-L32 | def get_randomized_guid_sample(self, item_count):
""" Fetch a subset of randomzied GUIDs from the whitelist """
dataset = self.get_whitelist()
random.shuffle(dataset)
return dataset[:item_count] | [
"def",
"get_randomized_guid_sample",
"(",
"self",
",",
"item_count",
")",
":",
"dataset",
"=",
"self",
".",
"get_whitelist",
"(",
")",
"random",
".",
"shuffle",
"(",
"dataset",
")",
"return",
"dataset",
"[",
":",
"item_count",
"]"
] | Fetch a subset of randomzied GUIDs from the whitelist | [
"Fetch",
"a",
"subset",
"of",
"randomzied",
"GUIDs",
"from",
"the",
"whitelist"
] | python | train | 44.4 |
gem/oq-engine | openquake/hazardlib/calc/hazard_curve.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/hazard_curve.py#L94-L176 | def classical(group, src_filter, gsims, param, monitor=Monitor()):
"""
Compute the hazard curves for a set of sources belonging to the same
tectonic region type for all the GSIMs associated to that TRT.
The arguments are the same as in :func:`calc_hazard_curves`, except
for ``gsims``, which is a lis... | [
"def",
"classical",
"(",
"group",
",",
"src_filter",
",",
"gsims",
",",
"param",
",",
"monitor",
"=",
"Monitor",
"(",
")",
")",
":",
"if",
"not",
"hasattr",
"(",
"src_filter",
",",
"'sitecol'",
")",
":",
"# a sitecol was passed",
"src_filter",
"=",
"Source... | Compute the hazard curves for a set of sources belonging to the same
tectonic region type for all the GSIMs associated to that TRT.
The arguments are the same as in :func:`calc_hazard_curves`, except
for ``gsims``, which is a list of GSIM instances.
:returns:
a dictionary {grp_id: pmap} with at... | [
"Compute",
"the",
"hazard",
"curves",
"for",
"a",
"set",
"of",
"sources",
"belonging",
"to",
"the",
"same",
"tectonic",
"region",
"type",
"for",
"all",
"the",
"GSIMs",
"associated",
"to",
"that",
"TRT",
".",
"The",
"arguments",
"are",
"the",
"same",
"as",
... | python | train | 44.578313 |
cmbruns/pyopenvr | src/openvr/__init__.py | https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/__init__.py#L2996-L3001 | def getEventTypeNameFromEnum(self, eType):
"""returns the name of an EVREvent enum value"""
fn = self.function_table.getEventTypeNameFromEnum
result = fn(eType)
return result | [
"def",
"getEventTypeNameFromEnum",
"(",
"self",
",",
"eType",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getEventTypeNameFromEnum",
"result",
"=",
"fn",
"(",
"eType",
")",
"return",
"result"
] | returns the name of an EVREvent enum value | [
"returns",
"the",
"name",
"of",
"an",
"EVREvent",
"enum",
"value"
] | python | train | 33.666667 |
rigetti/pyquil | pyquil/device.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/device.py#L354-L365 | def isa_from_graph(graph: nx.Graph, oneq_type='Xhalves', twoq_type='CZ') -> ISA:
"""
Generate an ISA object from a NetworkX graph.
:param graph: The graph
:param oneq_type: The type of 1-qubit gate. Currently 'Xhalves'
:param twoq_type: The type of 2-qubit gate. One of 'CZ' or 'CPHASE'.
"""
... | [
"def",
"isa_from_graph",
"(",
"graph",
":",
"nx",
".",
"Graph",
",",
"oneq_type",
"=",
"'Xhalves'",
",",
"twoq_type",
"=",
"'CZ'",
")",
"->",
"ISA",
":",
"all_qubits",
"=",
"list",
"(",
"range",
"(",
"max",
"(",
"graph",
".",
"nodes",
")",
"+",
"1",
... | Generate an ISA object from a NetworkX graph.
:param graph: The graph
:param oneq_type: The type of 1-qubit gate. Currently 'Xhalves'
:param twoq_type: The type of 2-qubit gate. One of 'CZ' or 'CPHASE'. | [
"Generate",
"an",
"ISA",
"object",
"from",
"a",
"NetworkX",
"graph",
"."
] | python | train | 46.666667 |
fermiPy/fermipy | fermipy/diffuse/source_factory.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/source_factory.py#L204-L217 | def make_roi(cls, sources=None):
"""Build and return a `fermipy.roi_model.ROIModel` object from
a dict with information about the sources
"""
if sources is None:
sources = {}
src_fact = cls()
src_fact.add_sources(sources)
ret_model = roi_model.ROIModel... | [
"def",
"make_roi",
"(",
"cls",
",",
"sources",
"=",
"None",
")",
":",
"if",
"sources",
"is",
"None",
":",
"sources",
"=",
"{",
"}",
"src_fact",
"=",
"cls",
"(",
")",
"src_fact",
".",
"add_sources",
"(",
"sources",
")",
"ret_model",
"=",
"roi_model",
... | Build and return a `fermipy.roi_model.ROIModel` object from
a dict with information about the sources | [
"Build",
"and",
"return",
"a",
"fermipy",
".",
"roi_model",
".",
"ROIModel",
"object",
"from",
"a",
"dict",
"with",
"information",
"about",
"the",
"sources"
] | python | train | 39.5 |
smarie/python-parsyfiles | parsyfiles/type_inspection_tools.py | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/type_inspection_tools.py#L90-L115 | def robust_isinstance(inst, typ) -> bool:
"""
Similar to isinstance, but if 'typ' is a parametrized generic Type, it is first transformed into its base generic
class so that the instance check works. It is also robust to Union and Any.
:param inst:
:param typ:
:return:
"""
if typ is Any... | [
"def",
"robust_isinstance",
"(",
"inst",
",",
"typ",
")",
"->",
"bool",
":",
"if",
"typ",
"is",
"Any",
":",
"return",
"True",
"if",
"is_typevar",
"(",
"typ",
")",
":",
"if",
"hasattr",
"(",
"typ",
",",
"'__constraints__'",
")",
"and",
"typ",
".",
"__... | Similar to isinstance, but if 'typ' is a parametrized generic Type, it is first transformed into its base generic
class so that the instance check works. It is also robust to Union and Any.
:param inst:
:param typ:
:return: | [
"Similar",
"to",
"isinstance",
"but",
"if",
"typ",
"is",
"a",
"parametrized",
"generic",
"Type",
"it",
"is",
"first",
"transformed",
"into",
"its",
"base",
"generic",
"class",
"so",
"that",
"the",
"instance",
"check",
"works",
".",
"It",
"is",
"also",
"rob... | python | train | 37.538462 |
collectiveacuity/labPack | labpack/storage/google/drive.py | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/storage/google/drive.py#L236-L271 | def _get_id(self, file_path):
''' a helper method for retrieving id of file or folder '''
title = '%s._get_id' % self.__class__.__name__
# construct request kwargs
list_kwargs = {
'spaces': self.drive_space,
'fields': 'files(id, parents)'
... | [
"def",
"_get_id",
"(",
"self",
",",
"file_path",
")",
":",
"title",
"=",
"'%s._get_id'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# construct request kwargs",
"list_kwargs",
"=",
"{",
"'spaces'",
":",
"self",
".",
"drive_space",
",",
"'fields'",
":",
... | a helper method for retrieving id of file or folder | [
"a",
"helper",
"method",
"for",
"retrieving",
"id",
"of",
"file",
"or",
"folder"
] | python | train | 33.388889 |
annoviko/pyclustering | pyclustering/container/cftree.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/container/cftree.py#L656-L665 | def insert_entry(self, entry):
"""!
@brief Insert new clustering feature to the leaf node.
@param[in] entry (cfentry): Clustering feature.
"""
self.feature += entry;
self.entries.append(entry); | [
"def",
"insert_entry",
"(",
"self",
",",
"entry",
")",
":",
"self",
".",
"feature",
"+=",
"entry",
"self",
".",
"entries",
".",
"append",
"(",
"entry",
")"
] | !
@brief Insert new clustering feature to the leaf node.
@param[in] entry (cfentry): Clustering feature. | [
"!"
] | python | valid | 29 |
pyQode/pyqode.core | pyqode/core/modes/pygments_sh.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/pygments_sh.py#L185-L205 | def set_mime_type(self, mime_type):
"""
Update the highlighter lexer based on a mime type.
:param mime_type: mime type of the new lexer to setup.
"""
try:
self.set_lexer_from_mime_type(mime_type)
except ClassNotFound:
_logger().exception('failed t... | [
"def",
"set_mime_type",
"(",
"self",
",",
"mime_type",
")",
":",
"try",
":",
"self",
".",
"set_lexer_from_mime_type",
"(",
"mime_type",
")",
"except",
"ClassNotFound",
":",
"_logger",
"(",
")",
".",
"exception",
"(",
"'failed to get lexer from mimetype'",
")",
"... | Update the highlighter lexer based on a mime type.
:param mime_type: mime type of the new lexer to setup. | [
"Update",
"the",
"highlighter",
"lexer",
"based",
"on",
"a",
"mime",
"type",
"."
] | python | train | 35.190476 |
clalancette/pycdlib | pycdlib/udf.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/udf.py#L3184-L3200 | def track_file_ident_desc(self, file_ident):
# type: (UDFFileIdentifierDescriptor) -> None
'''
A method to start tracking a UDF File Identifier descriptor in this
UDF File Entry. Both 'tracking' and 'addition' add the identifier to
the list of file identifiers, but tracking doee... | [
"def",
"track_file_ident_desc",
"(",
"self",
",",
"file_ident",
")",
":",
"# type: (UDFFileIdentifierDescriptor) -> None",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'UDF File Entry not initialized'",
")",
... | A method to start tracking a UDF File Identifier descriptor in this
UDF File Entry. Both 'tracking' and 'addition' add the identifier to
the list of file identifiers, but tracking doees not expand or
otherwise modify the UDF File Entry.
Parameters:
file_ident - The UDF File Id... | [
"A",
"method",
"to",
"start",
"tracking",
"a",
"UDF",
"File",
"Identifier",
"descriptor",
"in",
"this",
"UDF",
"File",
"Entry",
".",
"Both",
"tracking",
"and",
"addition",
"add",
"the",
"identifier",
"to",
"the",
"list",
"of",
"file",
"identifiers",
"but",
... | python | train | 39.647059 |
smira/py-numa | numa.py | https://github.com/smira/py-numa/blob/eb38979c61028eb9422a4ad1eda0387cd93ea390/numa.py#L354-L366 | def get_run_on_node_mask():
"""
Returns the mask of nodes that the current thread is allowed to run on.
@return: node mask
@rtype: C{set}
"""
bitmask = libnuma.numa_get_run_node_mask()
nodemask = nodemask_t()
libnuma.copy_bitmask_to_nodemask(bitmask, byref(nodemask))
libnuma.numa_bi... | [
"def",
"get_run_on_node_mask",
"(",
")",
":",
"bitmask",
"=",
"libnuma",
".",
"numa_get_run_node_mask",
"(",
")",
"nodemask",
"=",
"nodemask_t",
"(",
")",
"libnuma",
".",
"copy_bitmask_to_nodemask",
"(",
"bitmask",
",",
"byref",
"(",
"nodemask",
")",
")",
"lib... | Returns the mask of nodes that the current thread is allowed to run on.
@return: node mask
@rtype: C{set} | [
"Returns",
"the",
"mask",
"of",
"nodes",
"that",
"the",
"current",
"thread",
"is",
"allowed",
"to",
"run",
"on",
"."
] | python | train | 28.461538 |
EnigmaBridge/jbossply | jbossply/main.py | https://github.com/EnigmaBridge/jbossply/blob/44b30b15982cae781f0c356fab7263751b20b4d0/jbossply/main.py#L12-L23 | def main():
"""
Reads stdin jboss output, writes json on output
:return:
"""
buff = ''
for line in fileinput.input():
buff += line
parser = jbossparser.JbossParser()
result = parser.parse(buff)
print(json.dumps(result)) | [
"def",
"main",
"(",
")",
":",
"buff",
"=",
"''",
"for",
"line",
"in",
"fileinput",
".",
"input",
"(",
")",
":",
"buff",
"+=",
"line",
"parser",
"=",
"jbossparser",
".",
"JbossParser",
"(",
")",
"result",
"=",
"parser",
".",
"parse",
"(",
"buff",
")... | Reads stdin jboss output, writes json on output
:return: | [
"Reads",
"stdin",
"jboss",
"output",
"writes",
"json",
"on",
"output",
":",
"return",
":"
] | python | train | 21.083333 |
delfick/aws_syncr | aws_syncr/option_spec/aws_syncr_specs.py | https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/option_spec/aws_syncr_specs.py#L51-L63 | def aws_syncr_spec(self):
"""Spec for aws_syncr options"""
formatted_string = formatted(string_spec(), MergedOptionStringFormatter, expected_type=string_types)
return create_spec(AwsSyncr
, extra = defaulted(formatted_string, "")
, stage = defaulted(formatted_string, "")
... | [
"def",
"aws_syncr_spec",
"(",
"self",
")",
":",
"formatted_string",
"=",
"formatted",
"(",
"string_spec",
"(",
")",
",",
"MergedOptionStringFormatter",
",",
"expected_type",
"=",
"string_types",
")",
"return",
"create_spec",
"(",
"AwsSyncr",
",",
"extra",
"=",
"... | Spec for aws_syncr options | [
"Spec",
"for",
"aws_syncr",
"options"
] | python | train | 48.307692 |
tanghaibao/jcvi | jcvi/formats/blast.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/blast.py#L383-L408 | def gaps(args):
"""
%prog gaps A_vs_B.blast
Find distribution of gap sizes betwen adjacent HSPs.
"""
p = OptionParser(gaps.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
blastfile, = args
blast = BlastSlow(blastfile)
logging.de... | [
"def",
"gaps",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"gaps",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
"not",... | %prog gaps A_vs_B.blast
Find distribution of gap sizes betwen adjacent HSPs. | [
"%prog",
"gaps",
"A_vs_B",
".",
"blast"
] | python | train | 27.192308 |
happyleavesaoc/python-snapcast | snapcast/control/client.py | https://github.com/happyleavesaoc/python-snapcast/blob/9b3c483358677327c7fd6d0666bf474c19d87f19/snapcast/control/client.py#L94-L104 | def set_volume(self, percent, update_group=True):
"""Set client volume percent."""
if percent not in range(0, 101):
raise ValueError('Volume percent out of range')
new_volume = self._client['config']['volume']
new_volume['percent'] = percent
self._client['config']['vo... | [
"def",
"set_volume",
"(",
"self",
",",
"percent",
",",
"update_group",
"=",
"True",
")",
":",
"if",
"percent",
"not",
"in",
"range",
"(",
"0",
",",
"101",
")",
":",
"raise",
"ValueError",
"(",
"'Volume percent out of range'",
")",
"new_volume",
"=",
"self"... | Set client volume percent. | [
"Set",
"client",
"volume",
"percent",
"."
] | python | train | 52.545455 |
monarch-initiative/dipper | dipper/sources/UDP.py | https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/sources/UDP.py#L324-L439 | def _add_variant_gene_relationship(self, patient_var_map, gene_coordinate_map):
"""
Right now it is unclear the best approach on how to connect
variants to genes. In most cases has_affected_locus/GENO:0000418
is accurate; however, there are cases where a variant is in the intron
... | [
"def",
"_add_variant_gene_relationship",
"(",
"self",
",",
"patient_var_map",
",",
"gene_coordinate_map",
")",
":",
"# genotype = Genotype(self.graph)",
"dipper_util",
"=",
"DipperUtil",
"(",
")",
"model",
"=",
"Model",
"(",
"self",
".",
"graph",
")",
"# Note this cou... | Right now it is unclear the best approach on how to connect
variants to genes. In most cases has_affected_locus/GENO:0000418
is accurate; however, there are cases where a variant is in the intron
on one gene and is purported to causally affect another gene down or
upstream. In these ca... | [
"Right",
"now",
"it",
"is",
"unclear",
"the",
"best",
"approach",
"on",
"how",
"to",
"connect",
"variants",
"to",
"genes",
".",
"In",
"most",
"cases",
"has_affected_locus",
"/",
"GENO",
":",
"0000418",
"is",
"accurate",
";",
"however",
"there",
"are",
"cas... | python | train | 54.387931 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevd_reload.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_reload.py#L167-L179 | def xreload(mod):
"""Reload a module in place, updating classes, methods and functions.
mod: a module object
Returns a boolean indicating whether a change was done.
"""
r = Reload(mod)
r.apply()
found_change = r.found_change
r = None
pydevd_dont_trace.clear_trace_filter_cache()
... | [
"def",
"xreload",
"(",
"mod",
")",
":",
"r",
"=",
"Reload",
"(",
"mod",
")",
"r",
".",
"apply",
"(",
")",
"found_change",
"=",
"r",
".",
"found_change",
"r",
"=",
"None",
"pydevd_dont_trace",
".",
"clear_trace_filter_cache",
"(",
")",
"return",
"found_ch... | Reload a module in place, updating classes, methods and functions.
mod: a module object
Returns a boolean indicating whether a change was done. | [
"Reload",
"a",
"module",
"in",
"place",
"updating",
"classes",
"methods",
"and",
"functions",
"."
] | python | train | 25.230769 |
osrg/ryu | ryu/services/protocols/bgp/core_managers/peer_manager.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/services/protocols/bgp/core_managers/peer_manager.py#L77-L83 | def get_peers_in_established(self):
"""Returns list of peers in established state."""
est_peers = []
for peer in self._peers.values():
if peer.in_established:
est_peers.append(peer)
return est_peers | [
"def",
"get_peers_in_established",
"(",
"self",
")",
":",
"est_peers",
"=",
"[",
"]",
"for",
"peer",
"in",
"self",
".",
"_peers",
".",
"values",
"(",
")",
":",
"if",
"peer",
".",
"in_established",
":",
"est_peers",
".",
"append",
"(",
"peer",
")",
"ret... | Returns list of peers in established state. | [
"Returns",
"list",
"of",
"peers",
"in",
"established",
"state",
"."
] | python | train | 36 |
rvswift/EB | EB/builder/splitter/splitter_io.py | https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/splitter/splitter_io.py#L26-L70 | def print_extended_help():
"""
Prints an extended help message.
"""
# initiate TextWrapper class, which will handle all of the string formatting
w = textwrap.TextWrapper()
w.expand_tabs = False
w.width=110
w.initial_indent = ' '
w.subsequent_indent = ' '
print('')
print(te... | [
"def",
"print_extended_help",
"(",
")",
":",
"# initiate TextWrapper class, which will handle all of the string formatting",
"w",
"=",
"textwrap",
".",
"TextWrapper",
"(",
")",
"w",
".",
"expand_tabs",
"=",
"False",
"w",
".",
"width",
"=",
"110",
"w",
".",
"initial_... | Prints an extended help message. | [
"Prints",
"an",
"extended",
"help",
"message",
"."
] | python | train | 34.266667 |
codeinn/vcs | vcs/backends/git/changeset.py | https://github.com/codeinn/vcs/blob/e6cd94188e9c36d273411bf3adc0584ac6ab92a0/vcs/backends/git/changeset.py#L469-L474 | def affected_files(self):
"""
Get's a fast accessible file changes for given changeset
"""
added, modified, deleted = self._changes_cache
return list(added.union(modified).union(deleted)) | [
"def",
"affected_files",
"(",
"self",
")",
":",
"added",
",",
"modified",
",",
"deleted",
"=",
"self",
".",
"_changes_cache",
"return",
"list",
"(",
"added",
".",
"union",
"(",
"modified",
")",
".",
"union",
"(",
"deleted",
")",
")"
] | Get's a fast accessible file changes for given changeset | [
"Get",
"s",
"a",
"fast",
"accessible",
"file",
"changes",
"for",
"given",
"changeset"
] | python | train | 37 |
DataBiosphere/toil | src/toil/leader.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/leader.py#L815-L843 | def getSuccessors(jobGraph, alreadySeenSuccessors, jobStore):
"""
Gets successors of the given job by walking the job graph recursively.
Any successor in alreadySeenSuccessors is ignored and not traversed.
Returns the set of found successors. This set is added to alreadySeenSuccessors.
... | [
"def",
"getSuccessors",
"(",
"jobGraph",
",",
"alreadySeenSuccessors",
",",
"jobStore",
")",
":",
"successors",
"=",
"set",
"(",
")",
"def",
"successorRecursion",
"(",
"jobGraph",
")",
":",
"# For lists of successors",
"for",
"successorList",
"in",
"jobGraph",
"."... | Gets successors of the given job by walking the job graph recursively.
Any successor in alreadySeenSuccessors is ignored and not traversed.
Returns the set of found successors. This set is added to alreadySeenSuccessors. | [
"Gets",
"successors",
"of",
"the",
"given",
"job",
"by",
"walking",
"the",
"job",
"graph",
"recursively",
".",
"Any",
"successor",
"in",
"alreadySeenSuccessors",
"is",
"ignored",
"and",
"not",
"traversed",
".",
"Returns",
"the",
"set",
"of",
"found",
"successo... | python | train | 44.103448 |
rstoneback/pysat | pysat/_instrument.py | https://github.com/rstoneback/pysat/blob/4ae1afd80e15e4449397d39dce8c3e969c32c422/pysat/_instrument.py#L1409-L1823 | def to_netcdf4(self, fname=None, base_instrument=None, epoch_name='Epoch',
zlib=False, complevel=4, shuffle=True):
"""Stores loaded data into a netCDF4 file.
Parameters
----------
fname : string
full path to save instrument object to
base_i... | [
"def",
"to_netcdf4",
"(",
"self",
",",
"fname",
"=",
"None",
",",
"base_instrument",
"=",
"None",
",",
"epoch_name",
"=",
"'Epoch'",
",",
"zlib",
"=",
"False",
",",
"complevel",
"=",
"4",
",",
"shuffle",
"=",
"True",
")",
":",
"import",
"netCDF4",
"imp... | Stores loaded data into a netCDF4 file.
Parameters
----------
fname : string
full path to save instrument object to
base_instrument : pysat.Instrument
used as a comparison, only attributes that are present with
self and not on base_instrument ... | [
"Stores",
"loaded",
"data",
"into",
"a",
"netCDF4",
"file",
".",
"Parameters",
"----------",
"fname",
":",
"string",
"full",
"path",
"to",
"save",
"instrument",
"object",
"to",
"base_instrument",
":",
"pysat",
".",
"Instrument",
"used",
"as",
"a",
"comparison"... | python | train | 57.055422 |
modin-project/modin | modin/pandas/indexing.py | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/indexing.py#L127-L140 | def _compute_ndim(row_loc, col_loc):
"""Compute the ndim of result from locators
"""
row_scaler = is_scalar(row_loc)
col_scaler = is_scalar(col_loc)
if row_scaler and col_scaler:
ndim = 0
elif row_scaler ^ col_scaler:
ndim = 1
else:
ndim = 2
return ndim | [
"def",
"_compute_ndim",
"(",
"row_loc",
",",
"col_loc",
")",
":",
"row_scaler",
"=",
"is_scalar",
"(",
"row_loc",
")",
"col_scaler",
"=",
"is_scalar",
"(",
"col_loc",
")",
"if",
"row_scaler",
"and",
"col_scaler",
":",
"ndim",
"=",
"0",
"elif",
"row_scaler",
... | Compute the ndim of result from locators | [
"Compute",
"the",
"ndim",
"of",
"result",
"from",
"locators"
] | python | train | 21.285714 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/fw_mgr.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fw_mgr.py#L455-L471 | def _check_delete_fw(self, tenant_id, drvr_name):
"""Deletes the Firewall, if all conditioms are met.
This function after modifying the DB with delete operation status,
calls the routine to remove the fabric cfg from DB and unconfigure
the device.
"""
fw_dict = self.fwid... | [
"def",
"_check_delete_fw",
"(",
"self",
",",
"tenant_id",
",",
"drvr_name",
")",
":",
"fw_dict",
"=",
"self",
".",
"fwid_attr",
"[",
"tenant_id",
"]",
".",
"get_fw_dict",
"(",
")",
"ret",
"=",
"False",
"try",
":",
"with",
"self",
".",
"fwid_attr",
"[",
... | Deletes the Firewall, if all conditioms are met.
This function after modifying the DB with delete operation status,
calls the routine to remove the fabric cfg from DB and unconfigure
the device. | [
"Deletes",
"the",
"Firewall",
"if",
"all",
"conditioms",
"are",
"met",
"."
] | python | train | 43.941176 |
pyviz/param | param/parameterized.py | https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/parameterized.py#L152-L161 | def get_occupied_slots(instance):
"""
Return a list of slots for which values have been set.
(While a slot might be defined, if a value for that slot hasn't
been set, then it's an AttributeError to request the slot's
value.)
"""
return [slot for slot in get_all_slots(type(instance))
... | [
"def",
"get_occupied_slots",
"(",
"instance",
")",
":",
"return",
"[",
"slot",
"for",
"slot",
"in",
"get_all_slots",
"(",
"type",
"(",
"instance",
")",
")",
"if",
"hasattr",
"(",
"instance",
",",
"slot",
")",
"]"
] | Return a list of slots for which values have been set.
(While a slot might be defined, if a value for that slot hasn't
been set, then it's an AttributeError to request the slot's
value.) | [
"Return",
"a",
"list",
"of",
"slots",
"for",
"which",
"values",
"have",
"been",
"set",
"."
] | python | train | 34.2 |
F5Networks/f5-common-python | f5-sdk-dist/build_pkgs.py | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5-sdk-dist/build_pkgs.py#L143-L168 | def build_debian(config, os_versions, os_type='ubuntu'):
"""build_debian
Builds for a specific debian operating system with os version
specified. By default, it will use os_type='ubuntu'
"""
def build_pkg(config, os_type, os_version):
result = _build_package(config, os_type, os_version)
if... | [
"def",
"build_debian",
"(",
"config",
",",
"os_versions",
",",
"os_type",
"=",
"'ubuntu'",
")",
":",
"def",
"build_pkg",
"(",
"config",
",",
"os_type",
",",
"os_version",
")",
":",
"result",
"=",
"_build_package",
"(",
"config",
",",
"os_type",
",",
"os_ve... | build_debian
Builds for a specific debian operating system with os version
specified. By default, it will use os_type='ubuntu' | [
"build_debian"
] | python | train | 32.769231 |
docker/docker-py | docker/api/container.py | https://github.com/docker/docker-py/blob/613d6aad83acc9931ff2ecfd6a6c7bd8061dc125/docker/api/container.py#L973-L993 | def remove_container(self, container, v=False, link=False, force=False):
"""
Remove a container. Similar to the ``docker rm`` command.
Args:
container (str): The container to remove
v (bool): Remove the volumes associated with the container
link (bool): Remov... | [
"def",
"remove_container",
"(",
"self",
",",
"container",
",",
"v",
"=",
"False",
",",
"link",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'v'",
":",
"v",
",",
"'link'",
":",
"link",
",",
"'force'",
":",
"force",
"}",
... | Remove a container. Similar to the ``docker rm`` command.
Args:
container (str): The container to remove
v (bool): Remove the volumes associated with the container
link (bool): Remove the specified link and not the underlying
container
force (bool... | [
"Remove",
"a",
"container",
".",
"Similar",
"to",
"the",
"docker",
"rm",
"command",
"."
] | python | train | 37.714286 |
fr33jc/bang | bang/util.py | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/util.py#L149-L159 | def add_if_unique(self, name):
"""
Returns ``True`` on success.
Returns ``False`` if the name already exists in the namespace.
"""
with self.lock:
if name not in self.names:
self.names.append(name)
return True
return False | [
"def",
"add_if_unique",
"(",
"self",
",",
"name",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"name",
"not",
"in",
"self",
".",
"names",
":",
"self",
".",
"names",
".",
"append",
"(",
"name",
")",
"return",
"True",
"return",
"False"
] | Returns ``True`` on success.
Returns ``False`` if the name already exists in the namespace. | [
"Returns",
"True",
"on",
"success",
"."
] | python | train | 27.727273 |
SpriteLink/NIPAP | nipap-cli/nipap_cli/nipap_cli.py | https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap-cli/nipap_cli/nipap_cli.py#L688-L842 | def add_prefix(arg, opts, shell_opts):
""" Add prefix to NIPAP
"""
# sanity checks
if 'from-pool' not in opts and 'from-prefix' not in opts and 'prefix' not in opts:
print("ERROR: 'prefix', 'from-pool' or 'from-prefix' must be specified.", file=sys.stderr)
sys.exit(1)
if len([opt f... | [
"def",
"add_prefix",
"(",
"arg",
",",
"opts",
",",
"shell_opts",
")",
":",
"# sanity checks",
"if",
"'from-pool'",
"not",
"in",
"opts",
"and",
"'from-prefix'",
"not",
"in",
"opts",
"and",
"'prefix'",
"not",
"in",
"opts",
":",
"print",
"(",
"\"ERROR: 'prefix'... | Add prefix to NIPAP | [
"Add",
"prefix",
"to",
"NIPAP"
] | python | train | 37.03871 |
sods/paramz | paramz/optimization/optimization.py | https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/optimization/optimization.py#L105-L132 | def opt(self, x_init, f_fp=None, f=None, fp=None):
"""
Run the optimizer
"""
rcstrings = ['Converged', 'Maximum number of f evaluations reached', 'Error']
assert f_fp != None, "BFGS requires f_fp"
opt_dict = {}
if self.xtol is not None:
print("WARNI... | [
"def",
"opt",
"(",
"self",
",",
"x_init",
",",
"f_fp",
"=",
"None",
",",
"f",
"=",
"None",
",",
"fp",
"=",
"None",
")",
":",
"rcstrings",
"=",
"[",
"'Converged'",
",",
"'Maximum number of f evaluations reached'",
",",
"'Error'",
"]",
"assert",
"f_fp",
"!... | Run the optimizer | [
"Run",
"the",
"optimizer"
] | python | train | 42.821429 |
dmlc/xgboost | python-package/xgboost/sklearn.py | https://github.com/dmlc/xgboost/blob/253fdd8a42d5ec6b819788199584d27bf9ea6253/python-package/xgboost/sklearn.py#L302-L408 | def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None,
early_stopping_rounds=None, verbose=True, xgb_model=None,
sample_weight_eval_set=None, callbacks=None):
# pylint: disable=missing-docstring,invalid-name,attribute-defined-outside-init
"""
Fit the gra... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"sample_weight",
"=",
"None",
",",
"eval_set",
"=",
"None",
",",
"eval_metric",
"=",
"None",
",",
"early_stopping_rounds",
"=",
"None",
",",
"verbose",
"=",
"True",
",",
"xgb_model",
"=",
"None",
",",... | Fit the gradient boosting model
Parameters
----------
X : array_like
Feature matrix
y : array_like
Labels
sample_weight : array_like
instance weights
eval_set : list, optional
A list of (X, y) tuple pairs to use as a valida... | [
"Fit",
"the",
"gradient",
"boosting",
"model"
] | python | train | 45.775701 |
ansible/molecule | molecule/command/idempotence.py | https://github.com/ansible/molecule/blob/766dc35b0b0ce498cd5e3a62b40f828742d0d08c/molecule/command/idempotence.py#L92-L110 | def _is_idempotent(self, output):
"""
Parses the output of the provisioning for changed and returns a bool.
:param output: A string containing the output of the ansible run.
:return: bool
"""
# Remove blank lines to make regex matches easier
output = re.sub(r'\n... | [
"def",
"_is_idempotent",
"(",
"self",
",",
"output",
")",
":",
"# Remove blank lines to make regex matches easier",
"output",
"=",
"re",
".",
"sub",
"(",
"r'\\n\\s*\\n*'",
",",
"'\\n'",
",",
"output",
")",
"# Look for any non-zero changed lines",
"changed",
"=",
"re",... | Parses the output of the provisioning for changed and returns a bool.
:param output: A string containing the output of the ansible run.
:return: bool | [
"Parses",
"the",
"output",
"of",
"the",
"provisioning",
"for",
"changed",
"and",
"returns",
"a",
"bool",
"."
] | python | train | 27.842105 |
senaite/senaite.core | bika/lims/catalog/catalog_utilities.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/catalog/catalog_utilities.py#L53-L76 | def getCatalog(instance, field='UID'):
"""
Returns the catalog that stores objects of instance passed in type.
If an object is indexed by more than one catalog, the first match
will be returned.
:param instance: A single object
:type instance: ATContentType
:returns: The first catalog that ... | [
"def",
"getCatalog",
"(",
"instance",
",",
"field",
"=",
"'UID'",
")",
":",
"uid",
"=",
"instance",
".",
"UID",
"(",
")",
"if",
"'workflow_skiplist'",
"in",
"instance",
".",
"REQUEST",
"and",
"[",
"x",
"for",
"x",
"in",
"instance",
".",
"REQUEST",
"[",... | Returns the catalog that stores objects of instance passed in type.
If an object is indexed by more than one catalog, the first match
will be returned.
:param instance: A single object
:type instance: ATContentType
:returns: The first catalog that stores the type of object passed in | [
"Returns",
"the",
"catalog",
"that",
"stores",
"objects",
"of",
"instance",
"passed",
"in",
"type",
".",
"If",
"an",
"object",
"is",
"indexed",
"by",
"more",
"than",
"one",
"catalog",
"the",
"first",
"match",
"will",
"be",
"returned",
"."
] | python | train | 39.625 |
lago-project/lago | lago/log_utils.py | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/log_utils.py#L265-L278 | def get_tasks(self, thread_name):
"""
Args:
thread_name (str): name of the thread to get the tasks for
Returns:
OrderedDict of str, Task: list of task names and log records for
each for the given thread
"""
if thread_name not in self.tasks... | [
"def",
"get_tasks",
"(",
"self",
",",
"thread_name",
")",
":",
"if",
"thread_name",
"not",
"in",
"self",
".",
"tasks_by_thread",
":",
"with",
"self",
".",
"_tasks_lock",
":",
"self",
".",
"tasks_by_thread",
"[",
"thread_name",
"]",
"=",
"OrderedDict",
"(",
... | Args:
thread_name (str): name of the thread to get the tasks for
Returns:
OrderedDict of str, Task: list of task names and log records for
each for the given thread | [
"Args",
":",
"thread_name",
"(",
"str",
")",
":",
"name",
"of",
"the",
"thread",
"to",
"get",
"the",
"tasks",
"for"
] | python | train | 33.5 |
ansible/ansible-runner | ansible_runner/utils.py | https://github.com/ansible/ansible-runner/blob/8ce485480a5d0b602428d9d64a752e06fb46cdb8/ansible_runner/utils.py#L39-L49 | def isplaybook(obj):
'''
Inspects the object and returns if it is a playbook
Args:
obj (object): The object to be inspected by this function
Returns:
boolean: True if the object is a list and False if it is not
'''
return isinstance(obj, Iterable) and (not isinstance(obj, strin... | [
"def",
"isplaybook",
"(",
"obj",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"Iterable",
")",
"and",
"(",
"not",
"isinstance",
"(",
"obj",
",",
"string_types",
")",
"and",
"not",
"isinstance",
"(",
"obj",
",",
"Mapping",
")",
")"
] | Inspects the object and returns if it is a playbook
Args:
obj (object): The object to be inspected by this function
Returns:
boolean: True if the object is a list and False if it is not | [
"Inspects",
"the",
"object",
"and",
"returns",
"if",
"it",
"is",
"a",
"playbook"
] | python | train | 32 |
emilydolson/avida-spatial-tools | avidaspatial/utils.py | https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L124-L133 | def prepend_zeros_to_lists(ls):
"""
Takes a list of lists and appends 0s to the beggining of each sub_list
until they are all the same length. Used for sign-extending binary numbers.
"""
longest = max([len(l) for l in ls])
for i in range(len(ls)):
while len(ls[i]) < longest:
... | [
"def",
"prepend_zeros_to_lists",
"(",
"ls",
")",
":",
"longest",
"=",
"max",
"(",
"[",
"len",
"(",
"l",
")",
"for",
"l",
"in",
"ls",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"ls",
")",
")",
":",
"while",
"len",
"(",
"ls",
"[",
"i... | Takes a list of lists and appends 0s to the beggining of each sub_list
until they are all the same length. Used for sign-extending binary numbers. | [
"Takes",
"a",
"list",
"of",
"lists",
"and",
"appends",
"0s",
"to",
"the",
"beggining",
"of",
"each",
"sub_list",
"until",
"they",
"are",
"all",
"the",
"same",
"length",
".",
"Used",
"for",
"sign",
"-",
"extending",
"binary",
"numbers",
"."
] | python | train | 33.2 |
mrjoes/sockjs-tornado | sockjs/tornado/session.py | https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/session.py#L241-L252 | def on_delete(self, forced):
"""Session expiration callback
`forced`
If session item explicitly deleted, forced will be set to True. If
item expired, will be set to False.
"""
# Do not remove connection if it was not forced and there's running connection
... | [
"def",
"on_delete",
"(",
"self",
",",
"forced",
")",
":",
"# Do not remove connection if it was not forced and there's running connection",
"if",
"not",
"forced",
"and",
"self",
".",
"handler",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"is_closed",
":",
"self"... | Session expiration callback
`forced`
If session item explicitly deleted, forced will be set to True. If
item expired, will be set to False. | [
"Session",
"expiration",
"callback"
] | python | train | 36.75 |
aestrivex/bctpy | bct/algorithms/distance.py | https://github.com/aestrivex/bctpy/blob/4cb0e759eb4a038750b07e23bd29958c400684b8/bct/algorithms/distance.py#L910-L1004 | def search_information(adjacency, transform=None, has_memory=False):
"""
Calculates search information of `adjacency`
Computes the amount of information (measured in bits) that a random walker
needs to follow the shortest path between a given pair of nodes.
Parameters
----------
adjacency ... | [
"def",
"search_information",
"(",
"adjacency",
",",
"transform",
"=",
"None",
",",
"has_memory",
"=",
"False",
")",
":",
"N",
"=",
"len",
"(",
"adjacency",
")",
"if",
"np",
".",
"allclose",
"(",
"adjacency",
",",
"adjacency",
".",
"T",
")",
":",
"flag_... | Calculates search information of `adjacency`
Computes the amount of information (measured in bits) that a random walker
needs to follow the shortest path between a given pair of nodes.
Parameters
----------
adjacency : (N x N) array_like
Weighted/unweighted, direct/undirected connection we... | [
"Calculates",
"search",
"information",
"of",
"adjacency"
] | python | train | 42.084211 |
log2timeline/plaso | plaso/cli/helpers/elastic_output.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/helpers/elastic_output.py#L86-L137 | def ParseOptions(cls, options, output_module):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
output_module (OutputModule): output module to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
BadConfigOption... | [
"def",
"ParseOptions",
"(",
"cls",
",",
"options",
",",
"output_module",
")",
":",
"elastic_output_modules",
"=",
"(",
"elastic",
".",
"ElasticsearchOutputModule",
",",
"elastic",
".",
"ElasticsearchOutputModule",
")",
"if",
"not",
"isinstance",
"(",
"output_module"... | Parses and validates options.
Args:
options (argparse.Namespace): parser options.
output_module (OutputModule): output module to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
BadConfigOption: when a configuration parameter fails validation. | [
"Parses",
"and",
"validates",
"options",
"."
] | python | train | 41.423077 |
bitprophet/ssh | ssh/agent.py | https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/agent.py#L199-L219 | def connect(self):
"""
Method automatically called by the run() method of the AgentProxyThread
"""
if ('SSH_AUTH_SOCK' in os.environ) and (sys.platform != 'win32'):
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
retry_on_signal(lambd... | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"(",
"'SSH_AUTH_SOCK'",
"in",
"os",
".",
"environ",
")",
"and",
"(",
"sys",
".",
"platform",
"!=",
"'win32'",
")",
":",
"conn",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_UNIX",
",",
"socket",... | Method automatically called by the run() method of the AgentProxyThread | [
"Method",
"automatically",
"called",
"by",
"the",
"run",
"()",
"method",
"of",
"the",
"AgentProxyThread"
] | python | train | 36.190476 |
vaexio/vaex | packages/vaex-core/vaex/dataframe.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/dataframe.py#L4150-L4161 | def dropna(self, drop_nan=True, drop_masked=True, column_names=None):
"""Create a shallow copy of a DataFrame, with filtering set using select_non_missing.
:param drop_nan: drop rows when there is a NaN in any of the columns (will only affect float values)
:param drop_masked: drop rows when the... | [
"def",
"dropna",
"(",
"self",
",",
"drop_nan",
"=",
"True",
",",
"drop_masked",
"=",
"True",
",",
"column_names",
"=",
"None",
")",
":",
"copy",
"=",
"self",
".",
"copy",
"(",
")",
"copy",
".",
"select_non_missing",
"(",
"drop_nan",
"=",
"drop_nan",
",... | Create a shallow copy of a DataFrame, with filtering set using select_non_missing.
:param drop_nan: drop rows when there is a NaN in any of the columns (will only affect float values)
:param drop_masked: drop rows when there is a masked value in any of the columns
:param column_names: The colum... | [
"Create",
"a",
"shallow",
"copy",
"of",
"a",
"DataFrame",
"with",
"filtering",
"set",
"using",
"select_non_missing",
"."
] | python | test | 58.833333 |
Esri/ArcREST | src/arcrest/security/security.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/security/security.py#L209-L213 | def password(self, value):
"""gets/sets the current password"""
if isinstance(value, str):
self._password = value
self._handler = None | [
"def",
"password",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"self",
".",
"_password",
"=",
"value",
"self",
".",
"_handler",
"=",
"None"
] | gets/sets the current password | [
"gets",
"/",
"sets",
"the",
"current",
"password"
] | python | train | 34 |
log2timeline/dftimewolf | dftimewolf/lib/utils.py | https://github.com/log2timeline/dftimewolf/blob/45f898476a288d73c4256ae8e3836a2a4848c0d7/dftimewolf/lib/utils.py#L21-L60 | def import_args_from_dict(value, args, config):
"""Replaces some arguments by those specified by a key-value dictionary.
This function will be recursively called on a dictionary looking for any
value containing a "$" variable. If found, the value will be replaced
by the attribute in "args" of the same name.
... | [
"def",
"import_args_from_dict",
"(",
"value",
",",
"args",
",",
"config",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"for",
"match",
"in",
"TOKEN_REGEX",
".",
"finditer",
"(",
"str",
"(",
"value",
")",
")",
"... | Replaces some arguments by those specified by a key-value dictionary.
This function will be recursively called on a dictionary looking for any
value containing a "$" variable. If found, the value will be replaced
by the attribute in "args" of the same name.
It is used to load arguments from the CLI and any ex... | [
"Replaces",
"some",
"arguments",
"by",
"those",
"specified",
"by",
"a",
"key",
"-",
"value",
"dictionary",
"."
] | python | train | 40.85 |
Skype4Py/Skype4Py | Skype4Py/call.py | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/call.py#L175-L188 | def Join(self, Id):
"""Joins with another call to form a conference.
:Parameters:
Id : int
Call Id of the other call to join to the conference.
:return: Conference object.
:rtype: `Conference`
"""
#self._Alter('JOIN_CONFERENCE', Id)
reply =... | [
"def",
"Join",
"(",
"self",
",",
"Id",
")",
":",
"#self._Alter('JOIN_CONFERENCE', Id)",
"reply",
"=",
"self",
".",
"_Owner",
".",
"_DoCommand",
"(",
"'SET CALL %s JOIN_CONFERENCE %s'",
"%",
"(",
"self",
".",
"Id",
",",
"Id",
")",
",",
"'CALL %s CONF_ID'",
"%",... | Joins with another call to form a conference.
:Parameters:
Id : int
Call Id of the other call to join to the conference.
:return: Conference object.
:rtype: `Conference` | [
"Joins",
"with",
"another",
"call",
"to",
"form",
"a",
"conference",
"."
] | python | train | 34.214286 |
ChargePoint/pydnp3 | examples/outstation.py | https://github.com/ChargePoint/pydnp3/blob/5bcd8240d1fc0aa1579e71f2efcab63b4c61c547/examples/outstation.py#L201-L214 | def apply_update(self, value, index):
"""
Record an opendnp3 data value (Analog, Binary, etc.) in the outstation's database.
The data value gets sent to the Master as a side-effect.
:param value: An instance of Analog, Binary, or another opendnp3 data value.
:param inde... | [
"def",
"apply_update",
"(",
"self",
",",
"value",
",",
"index",
")",
":",
"_log",
".",
"debug",
"(",
"'Recording {} measurement, index={}, value={}'",
".",
"format",
"(",
"type",
"(",
"value",
")",
".",
"__name__",
",",
"index",
",",
"value",
".",
"value",
... | Record an opendnp3 data value (Analog, Binary, etc.) in the outstation's database.
The data value gets sent to the Master as a side-effect.
:param value: An instance of Analog, Binary, or another opendnp3 data value.
:param index: (integer) Index of the data definition in the opendnp3 data... | [
"Record",
"an",
"opendnp3",
"data",
"value",
"(",
"Analog",
"Binary",
"etc",
".",
")",
"in",
"the",
"outstation",
"s",
"database",
"."
] | python | valid | 48.285714 |
ChristopherRabotin/bungiesearch | bungiesearch/utils.py | https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/utils.py#L15-L64 | def update_index(model_items, model_name, action='index', bulk_size=100, num_docs=-1, start_date=None, end_date=None, refresh=True):
'''
Updates the index for the provided model_items.
:param model_items: a list of model_items (django Model instances, or proxy instances) which are to be indexed/updated or d... | [
"def",
"update_index",
"(",
"model_items",
",",
"model_name",
",",
"action",
"=",
"'index'",
",",
"bulk_size",
"=",
"100",
",",
"num_docs",
"=",
"-",
"1",
",",
"start_date",
"=",
"None",
",",
"end_date",
"=",
"None",
",",
"refresh",
"=",
"True",
")",
"... | Updates the index for the provided model_items.
:param model_items: a list of model_items (django Model instances, or proxy instances) which are to be indexed/updated or deleted.
If action is 'index', the model_items must be serializable objects. If action is 'delete', the model_items must be primary keys
c... | [
"Updates",
"the",
"index",
"for",
"the",
"provided",
"model_items",
".",
":",
"param",
"model_items",
":",
"a",
"list",
"of",
"model_items",
"(",
"django",
"Model",
"instances",
"or",
"proxy",
"instances",
")",
"which",
"are",
"to",
"be",
"indexed",
"/",
"... | python | train | 63.08 |
fastavro/fastavro | fastavro/_read_py.py | https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_read_py.py#L345-L366 | def read_union(fo, writer_schema, reader_schema=None):
"""A union is encoded by first writing a long value indicating the
zero-based position within the union of the schema of its value.
The value is then encoded per the indicated schema within the union.
"""
# schema resolution
index = read_lo... | [
"def",
"read_union",
"(",
"fo",
",",
"writer_schema",
",",
"reader_schema",
"=",
"None",
")",
":",
"# schema resolution",
"index",
"=",
"read_long",
"(",
"fo",
")",
"if",
"reader_schema",
":",
"# Handle case where the reader schema is just a single type (not union)",
"i... | A union is encoded by first writing a long value indicating the
zero-based position within the union of the schema of its value.
The value is then encoded per the indicated schema within the union. | [
"A",
"union",
"is",
"encoded",
"by",
"first",
"writing",
"a",
"long",
"value",
"indicating",
"the",
"zero",
"-",
"based",
"position",
"within",
"the",
"union",
"of",
"the",
"schema",
"of",
"its",
"value",
"."
] | python | train | 44.681818 |
codeforamerica/epa_python | epa/radinfo/radinfo.py | https://github.com/codeforamerica/epa_python/blob/62a53da62936bea8daa487a01a52b973e9062b2c/epa/radinfo/radinfo.py#L23-L29 | def facility(self, column=None, value=None, **kwargs):
"""
Check information related to Radiation facilities.
>>> RADInfo().facility('state_code', 'CA')
"""
return self._resolve_call('RAD_FACILITY', column, value, **kwargs) | [
"def",
"facility",
"(",
"self",
",",
"column",
"=",
"None",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_resolve_call",
"(",
"'RAD_FACILITY'",
",",
"column",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | Check information related to Radiation facilities.
>>> RADInfo().facility('state_code', 'CA') | [
"Check",
"information",
"related",
"to",
"Radiation",
"facilities",
"."
] | python | train | 36.857143 |
twilio/twilio-python | twilio/rest/api/v2010/account/call/recording.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/call/recording.py#L248-L262 | def get_instance(self, payload):
"""
Build an instance of RecordingInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.call.recording.RecordingInstance
:rtype: twilio.rest.api.v2010.account.call.recording.RecordingInstance
... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"RecordingInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
"call_sid",
"=",
"self",
".",
"_so... | Build an instance of RecordingInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.call.recording.RecordingInstance
:rtype: twilio.rest.api.v2010.account.call.recording.RecordingInstance | [
"Build",
"an",
"instance",
"of",
"RecordingInstance"
] | python | train | 33.733333 |
trolldbois/ctypeslib | ctypeslib/codegen/typehandler.py | https://github.com/trolldbois/ctypeslib/blob/2aeb1942a5a32a5cc798c287cd0d9e684a0181a8/ctypeslib/codegen/typehandler.py#L154-L187 | def _array_handler(self, _cursor_type):
"""
Handles all array types.
Resolves it's element type and makes a Array typedesc.
"""
# The element type has been previously declared
# we need to get the canonical typedef, in some cases
_type = _cursor_type.get_canonical... | [
"def",
"_array_handler",
"(",
"self",
",",
"_cursor_type",
")",
":",
"# The element type has been previously declared",
"# we need to get the canonical typedef, in some cases",
"_type",
"=",
"_cursor_type",
".",
"get_canonical",
"(",
")",
"size",
"=",
"_type",
".",
"get_arr... | Handles all array types.
Resolves it's element type and makes a Array typedesc. | [
"Handles",
"all",
"array",
"types",
".",
"Resolves",
"it",
"s",
"element",
"type",
"and",
"makes",
"a",
"Array",
"typedesc",
"."
] | python | train | 46.882353 |
MisterWil/abodepy | abodepy/__init__.py | https://github.com/MisterWil/abodepy/blob/6f84bb428fd1da98855f55083cd427bebbcc57ae/abodepy/__init__.py#L302-L313 | def get_automation(self, automation_id, refresh=False):
"""Get a single automation."""
if self._automations is None:
self.get_automations()
refresh = False
automation = self._automations.get(str(automation_id))
if automation and refresh:
automation.r... | [
"def",
"get_automation",
"(",
"self",
",",
"automation_id",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"self",
".",
"_automations",
"is",
"None",
":",
"self",
".",
"get_automations",
"(",
")",
"refresh",
"=",
"False",
"automation",
"=",
"self",
".",
"... | Get a single automation. | [
"Get",
"a",
"single",
"automation",
"."
] | python | train | 28.666667 |
reingart/pyafipws | utils.py | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/utils.py#L195-L210 | def inicializar_y_capturar_excepciones_simple(func):
"Decorador para inicializar y capturar errores (versión básica indep.)"
@functools.wraps(func)
def capturar_errores_wrapper(self, *args, **kwargs):
self.inicializar()
try:
return func(self, *args, **kwargs)
except:
... | [
"def",
"inicializar_y_capturar_excepciones_simple",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"capturar_errores_wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"inicializar",
"(",... | Decorador para inicializar y capturar errores (versión básica indep.) | [
"Decorador",
"para",
"inicializar",
"y",
"capturar",
"errores",
"(",
"versión",
"básica",
"indep",
".",
")"
] | python | train | 34.8125 |
PmagPy/PmagPy | programs/dmag_magic.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/dmag_magic.py#L16-L187 | def dmag_magic(in_file="measurements.txt", dir_path=".", input_dir_path="",
spec_file="specimens.txt", samp_file="samples.txt",
site_file="sites.txt", loc_file="locations.txt",
plot_by="loc", LT="AF", norm=True, XLP="",
save_plots=True, fmt="svg"):
"""
plots intensity decay ... | [
"def",
"dmag_magic",
"(",
"in_file",
"=",
"\"measurements.txt\"",
",",
"dir_path",
"=",
"\".\"",
",",
"input_dir_path",
"=",
"\"\"",
",",
"spec_file",
"=",
"\"specimens.txt\"",
",",
"samp_file",
"=",
"\"samples.txt\"",
",",
"site_file",
"=",
"\"sites.txt\"",
",",
... | plots intensity decay curves for demagnetization experiments
Parameters
----------
in_file : str, default "measurements.txt"
dir_path : str
output directory, default "."
input_dir_path : str
input file directory (if different from dir_path), default ""
spec_file : str
in... | [
"plots",
"intensity",
"decay",
"curves",
"for",
"demagnetization",
"experiments"
] | python | train | 40.023256 |
fastai/fastai | fastai/layers.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L221-L229 | def icnr(x, scale=2, init=nn.init.kaiming_normal_):
"ICNR init of `x`, with `scale` and `init` function."
ni,nf,h,w = x.shape
ni2 = int(ni/(scale**2))
k = init(torch.zeros([ni2,nf,h,w])).transpose(0, 1)
k = k.contiguous().view(ni2, nf, -1)
k = k.repeat(1, 1, scale**2)
k = k.contiguous().view... | [
"def",
"icnr",
"(",
"x",
",",
"scale",
"=",
"2",
",",
"init",
"=",
"nn",
".",
"init",
".",
"kaiming_normal_",
")",
":",
"ni",
",",
"nf",
",",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"ni2",
"=",
"int",
"(",
"ni",
"/",
"(",
"scale",
"**",
"2",... | ICNR init of `x`, with `scale` and `init` function. | [
"ICNR",
"init",
"of",
"x",
"with",
"scale",
"and",
"init",
"function",
"."
] | python | train | 40.111111 |
jobovy/galpy | galpy/orbit/Orbit.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/Orbit.py#L2643-L2689 | def vra(self,*args,**kwargs):
"""
NAME:
vra
PURPOSE:
return velocity in right ascension (km/s)
INPUT:
t - (optional) time at which to get vra (can be Quantity)
obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer
... | [
"def",
"vra",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"OrbitTop",
"import",
"_check_roSet",
",",
"_check_voSet",
"_check_roSet",
"(",
"self",
",",
"kwargs",
",",
"'vra'",
")",
"_check_voSet",
"(",
"self",
",",
"kw... | NAME:
vra
PURPOSE:
return velocity in right ascension (km/s)
INPUT:
t - (optional) time at which to get vra (can be Quantity)
obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer
in the Galactocentric frame
... | [
"NAME",
":"
] | python | train | 32.978723 |
dropbox/stone | stone/frontend/parser.py | https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/frontend/parser.py#L478-L480 | def p_tag_ref(self, p):
'tag_ref : ID'
p[0] = AstTagRef(self.path, p.lineno(1), p.lexpos(1), p[1]) | [
"def",
"p_tag_ref",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"AstTagRef",
"(",
"self",
".",
"path",
",",
"p",
".",
"lineno",
"(",
"1",
")",
",",
"p",
".",
"lexpos",
"(",
"1",
")",
",",
"p",
"[",
"1",
"]",
")"
] | tag_ref : ID | [
"tag_ref",
":",
"ID"
] | python | train | 37.333333 |
h2oai/h2o-3 | scripts/run.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/scripts/run.py#L71-L77 | def is_ipython_notebook(file_name):
"""
Return True if file_name matches a regexp for an ipython notebook. False otherwise.
:param file_name: file to test
"""
if (not re.match("^.*checkpoint\.ipynb$", file_name)) and re.match("^.*\.ipynb$", file_name): return True
return False | [
"def",
"is_ipython_notebook",
"(",
"file_name",
")",
":",
"if",
"(",
"not",
"re",
".",
"match",
"(",
"\"^.*checkpoint\\.ipynb$\"",
",",
"file_name",
")",
")",
"and",
"re",
".",
"match",
"(",
"\"^.*\\.ipynb$\"",
",",
"file_name",
")",
":",
"return",
"True",
... | Return True if file_name matches a regexp for an ipython notebook. False otherwise.
:param file_name: file to test | [
"Return",
"True",
"if",
"file_name",
"matches",
"a",
"regexp",
"for",
"an",
"ipython",
"notebook",
".",
"False",
"otherwise",
".",
":",
"param",
"file_name",
":",
"file",
"to",
"test"
] | python | test | 42.285714 |
rwl/pylon | pylon/io/excel.py | https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/pylon/io/excel.py#L38-L43 | def write(self, file_or_filename):
""" Writes case data to file in Excel format.
"""
self.book = Workbook()
self._write_data(None)
self.book.save(file_or_filename) | [
"def",
"write",
"(",
"self",
",",
"file_or_filename",
")",
":",
"self",
".",
"book",
"=",
"Workbook",
"(",
")",
"self",
".",
"_write_data",
"(",
"None",
")",
"self",
".",
"book",
".",
"save",
"(",
"file_or_filename",
")"
] | Writes case data to file in Excel format. | [
"Writes",
"case",
"data",
"to",
"file",
"in",
"Excel",
"format",
"."
] | python | train | 33 |
datadesk/django-bakery | bakery/management/commands/__init__.py | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/management/commands/__init__.py#L8-L38 | def get_s3_client():
"""
A DRY place to make sure AWS credentials in settings override
environment based credentials. Boto3 will fall back to:
http://boto3.readthedocs.io/en/latest/guide/configuration.html
"""
session_kwargs = {}
if hasattr(settings, 'AWS_ACCESS_KEY_ID'):
session_kw... | [
"def",
"get_s3_client",
"(",
")",
":",
"session_kwargs",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"settings",
",",
"'AWS_ACCESS_KEY_ID'",
")",
":",
"session_kwargs",
"[",
"'aws_access_key_id'",
"]",
"=",
"settings",
".",
"AWS_ACCESS_KEY_ID",
"if",
"hasattr",
"(",
... | A DRY place to make sure AWS credentials in settings override
environment based credentials. Boto3 will fall back to:
http://boto3.readthedocs.io/en/latest/guide/configuration.html | [
"A",
"DRY",
"place",
"to",
"make",
"sure",
"AWS",
"credentials",
"in",
"settings",
"override",
"environment",
"based",
"credentials",
".",
"Boto3",
"will",
"fall",
"back",
"to",
":",
"http",
":",
"//",
"boto3",
".",
"readthedocs",
".",
"io",
"/",
"en",
"... | python | train | 38.935484 |
shad7/tvdbapi_client | tvdbapi_client/api.py | https://github.com/shad7/tvdbapi_client/blob/edf1771184122f4db42af7fc087407a3e6a4e377/tvdbapi_client/api.py#L96-L100 | def token_expired(self):
"""Provide access to flag indicating if token has expired."""
if self._token_timer is None:
return True
return timeutil.is_newer_than(self._token_timer, timeutil.ONE_HOUR) | [
"def",
"token_expired",
"(",
"self",
")",
":",
"if",
"self",
".",
"_token_timer",
"is",
"None",
":",
"return",
"True",
"return",
"timeutil",
".",
"is_newer_than",
"(",
"self",
".",
"_token_timer",
",",
"timeutil",
".",
"ONE_HOUR",
")"
] | Provide access to flag indicating if token has expired. | [
"Provide",
"access",
"to",
"flag",
"indicating",
"if",
"token",
"has",
"expired",
"."
] | python | train | 45.6 |
limix/numpy-sugar | numpy_sugar/linalg/qs.py | https://github.com/limix/numpy-sugar/blob/4bdfa26913135c76ef3cd542a332f4e5861e948b/numpy_sugar/linalg/qs.py#L5-L36 | def economic_qs(K, epsilon=sqrt(finfo(float).eps)):
r"""Economic eigen decomposition for symmetric matrices.
A symmetric matrix ``K`` can be decomposed in
:math:`\mathrm Q_0 \mathrm S_0 \mathrm Q_0^\intercal + \mathrm Q_1\
\mathrm S_1 \mathrm Q_1^ \intercal`, where :math:`\mathrm S_1` is a zero
mat... | [
"def",
"economic_qs",
"(",
"K",
",",
"epsilon",
"=",
"sqrt",
"(",
"finfo",
"(",
"float",
")",
".",
"eps",
")",
")",
":",
"(",
"S",
",",
"Q",
")",
"=",
"eigh",
"(",
"K",
")",
"nok",
"=",
"abs",
"(",
"max",
"(",
"Q",
"[",
"0",
"]",
".",
"mi... | r"""Economic eigen decomposition for symmetric matrices.
A symmetric matrix ``K`` can be decomposed in
:math:`\mathrm Q_0 \mathrm S_0 \mathrm Q_0^\intercal + \mathrm Q_1\
\mathrm S_1 \mathrm Q_1^ \intercal`, where :math:`\mathrm S_1` is a zero
matrix with size determined by ``K``'s rank deficiency.
... | [
"r",
"Economic",
"eigen",
"decomposition",
"for",
"symmetric",
"matrices",
"."
] | python | train | 29.0625 |
gwastro/pycbc | pycbc/workflow/jobsetup.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/jobsetup.py#L179-L322 | def sngl_ifo_job_setup(workflow, ifo, out_files, curr_exe_job, science_segs,
datafind_outs, parents=None,
link_job_instance=None, allow_overlap=True,
compatibility_mode=True):
""" This function sets up a set of single ifo jobs. A basic overview of... | [
"def",
"sngl_ifo_job_setup",
"(",
"workflow",
",",
"ifo",
",",
"out_files",
",",
"curr_exe_job",
",",
"science_segs",
",",
"datafind_outs",
",",
"parents",
"=",
"None",
",",
"link_job_instance",
"=",
"None",
",",
"allow_overlap",
"=",
"True",
",",
"compatibility... | This function sets up a set of single ifo jobs. A basic overview of how this
works is as follows:
* (1) Identify the length of data that each job needs to read in, and what
part of that data the job is valid for.
* START LOOPING OVER SCIENCE SEGMENTS
* (2) Identify how many jobs are needed (if an... | [
"This",
"function",
"sets",
"up",
"a",
"set",
"of",
"single",
"ifo",
"jobs",
".",
"A",
"basic",
"overview",
"of",
"how",
"this",
"works",
"is",
"as",
"follows",
":"
] | python | train | 49.013889 |
bwohlberg/sporco | sporco/admm/cbpdn.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/cbpdn.py#L614-L620 | def obfn_reg(self):
"""Compute regularisation term and contribution to objective
function.
"""
rl1 = np.linalg.norm((self.wl1 * self.obfn_gvar()).ravel(), 1)
return (self.lmbda*rl1, rl1) | [
"def",
"obfn_reg",
"(",
"self",
")",
":",
"rl1",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"(",
"self",
".",
"wl1",
"*",
"self",
".",
"obfn_gvar",
"(",
")",
")",
".",
"ravel",
"(",
")",
",",
"1",
")",
"return",
"(",
"self",
".",
"lmbda",
"*... | Compute regularisation term and contribution to objective
function. | [
"Compute",
"regularisation",
"term",
"and",
"contribution",
"to",
"objective",
"function",
"."
] | python | train | 31.571429 |
ellmetha/django-machina | machina/apps/forum_conversation/views.py | https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/views.py#L314-L321 | def get_post(self):
""" Returns the considered post if applicable. """
pk = self.kwargs.get(self.post_pk_url_kwarg, None)
if not pk:
return
if not hasattr(self, '_forum_post'):
self._forum_post = get_object_or_404(Post, pk=pk)
return self._forum_post | [
"def",
"get_post",
"(",
"self",
")",
":",
"pk",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"self",
".",
"post_pk_url_kwarg",
",",
"None",
")",
"if",
"not",
"pk",
":",
"return",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_forum_post'",
")",
":",
... | Returns the considered post if applicable. | [
"Returns",
"the",
"considered",
"post",
"if",
"applicable",
"."
] | python | train | 38.375 |
rvswift/EB | EB/builder/splitter/splitter.py | https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/splitter/splitter.py#L190-L230 | def read_csv(csvfile, options):
"""
Read csv and return molList, a list of mol objects
"""
# open file or exit
name, ext = os.path.splitext(csvfile)
try:
if ext == '.gz':
f = gzip.open(csvfile, 'rb')
else:
f = open(csvfile, 'rU')
except IOError:
pri... | [
"def",
"read_csv",
"(",
"csvfile",
",",
"options",
")",
":",
"# open file or exit",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"csvfile",
")",
"try",
":",
"if",
"ext",
"==",
"'.gz'",
":",
"f",
"=",
"gzip",
".",
"open",
"(",
"... | Read csv and return molList, a list of mol objects | [
"Read",
"csv",
"and",
"return",
"molList",
"a",
"list",
"of",
"mol",
"objects"
] | python | train | 25.292683 |
echinopsii/net.echinopsii.ariane.community.cli.python3 | ariane_clip3/directory.py | https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/directory.py#L137-L157 | def location_2_json(self):
"""
transform ariane_clip3 location object to Ariane server JSON obj
:return: Ariane JSON obj
"""
LOGGER.debug("Location.location_2_json")
json_obj = {
'locationID': self.id,
'locationName': self.name,
'locati... | [
"def",
"location_2_json",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Location.location_2_json\"",
")",
"json_obj",
"=",
"{",
"'locationID'",
":",
"self",
".",
"id",
",",
"'locationName'",
":",
"self",
".",
"name",
",",
"'locationDescription'",
":",... | transform ariane_clip3 location object to Ariane server JSON obj
:return: Ariane JSON obj | [
"transform",
"ariane_clip3",
"location",
"object",
"to",
"Ariane",
"server",
"JSON",
"obj",
":",
"return",
":",
"Ariane",
"JSON",
"obj"
] | python | train | 38.095238 |
hazelcast/hazelcast-python-client | hazelcast/protocol/codec/ringbuffer_read_one_codec.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/protocol/codec/ringbuffer_read_one_codec.py#L10-L15 | def calculate_size(name, sequence):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += LONG_SIZE_IN_BYTES
return data_size | [
"def",
"calculate_size",
"(",
"name",
",",
"sequence",
")",
":",
"data_size",
"=",
"0",
"data_size",
"+=",
"calculate_size_str",
"(",
"name",
")",
"data_size",
"+=",
"LONG_SIZE_IN_BYTES",
"return",
"data_size"
] | Calculates the request payload size | [
"Calculates",
"the",
"request",
"payload",
"size"
] | python | train | 32.333333 |
nwilming/ocupy | ocupy/saccade_geometry.py | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/saccade_geometry.py#L51-L63 | def saccadic_momentum_effect(durations, forward_angle,
summary_stat=nanmean):
"""
Computes the mean fixation duration at forward angles.
"""
durations_per_da = np.nan * np.ones((len(e_angle) - 1,))
for i, (bo, b1) in enumerate(zip(e_angle[:-1], e_angle[1:])):
idx... | [
"def",
"saccadic_momentum_effect",
"(",
"durations",
",",
"forward_angle",
",",
"summary_stat",
"=",
"nanmean",
")",
":",
"durations_per_da",
"=",
"np",
".",
"nan",
"*",
"np",
".",
"ones",
"(",
"(",
"len",
"(",
"e_angle",
")",
"-",
"1",
",",
")",
")",
... | Computes the mean fixation duration at forward angles. | [
"Computes",
"the",
"mean",
"fixation",
"duration",
"at",
"forward",
"angles",
"."
] | python | train | 38.923077 |
openpermissions/koi | koi/base.py | https://github.com/openpermissions/koi/blob/d721f8e1dfa8f07ad265d9dec32e8aaf80a9f281/koi/base.py#L120-L152 | def get_json_body(self, required=None, validators=None):
"""Get JSON from the request body
:param required: optionally provide a list of keys that should be
in the JSON body (raises a 400 HTTPError if any are missing)
:param validator: optionally provide a dictionary of items that shoul... | [
"def",
"get_json_body",
"(",
"self",
",",
"required",
"=",
"None",
",",
"validators",
"=",
"None",
")",
":",
"content_type",
"=",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
",",
"'application/json'",
")",
"if",
"'application/j... | Get JSON from the request body
:param required: optionally provide a list of keys that should be
in the JSON body (raises a 400 HTTPError if any are missing)
:param validator: optionally provide a dictionary of items that should
be in the body with a method that validates the item.
... | [
"Get",
"JSON",
"from",
"the",
"request",
"body"
] | python | train | 38.151515 |
eqcorrscan/EQcorrscan | eqcorrscan/utils/plotting.py | https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/utils/plotting.py#L810-L959 | def detection_multiplot(stream, template, times, streamcolour='k',
templatecolour='r', size=(10.5, 7.5), **kwargs):
"""
Plot a stream of data with a template on top of it at detection times.
:type stream: obspy.core.stream.Stream
:param stream: Stream of data to be plotted as th... | [
"def",
"detection_multiplot",
"(",
"stream",
",",
"template",
",",
"times",
",",
"streamcolour",
"=",
"'k'",
",",
"templatecolour",
"=",
"'r'",
",",
"size",
"=",
"(",
"10.5",
",",
"7.5",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
"... | Plot a stream of data with a template on top of it at detection times.
:type stream: obspy.core.stream.Stream
:param stream: Stream of data to be plotted as the background.
:type template: obspy.core.stream.Stream
:param template: Template to be plotted on top of the base stream.
:type times: list
... | [
"Plot",
"a",
"stream",
"of",
"data",
"with",
"a",
"template",
"on",
"top",
"of",
"it",
"at",
"detection",
"times",
"."
] | python | train | 44.98 |
jbeluch/xbmcswift2 | xbmcswift2/xbmcmixin.py | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/xbmcmixin.py#L398-L418 | def add_items(self, items):
'''Adds ListItems to the XBMC interface. Each item in the
provided list should either be instances of xbmcswift2.ListItem,
or regular dictionaries that will be passed to
xbmcswift2.ListItem.from_dict. Returns the list of ListItems.
:param items: An it... | [
"def",
"add_items",
"(",
"self",
",",
"items",
")",
":",
"_items",
"=",
"[",
"self",
".",
"_listitemify",
"(",
"item",
")",
"for",
"item",
"in",
"items",
"]",
"tuples",
"=",
"[",
"item",
".",
"as_tuple",
"(",
")",
"for",
"item",
"in",
"_items",
"]"... | Adds ListItems to the XBMC interface. Each item in the
provided list should either be instances of xbmcswift2.ListItem,
or regular dictionaries that will be passed to
xbmcswift2.ListItem.from_dict. Returns the list of ListItems.
:param items: An iterable of items where each item is eith... | [
"Adds",
"ListItems",
"to",
"the",
"XBMC",
"interface",
".",
"Each",
"item",
"in",
"the",
"provided",
"list",
"should",
"either",
"be",
"instances",
"of",
"xbmcswift2",
".",
"ListItem",
"or",
"regular",
"dictionaries",
"that",
"will",
"be",
"passed",
"to",
"x... | python | train | 47.52381 |
Fantomas42/django-blog-zinnia | zinnia/views/mixins/templates.py | https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/views/mixins/templates.py#L81-L125 | def get_template_names(self):
"""
Return a list of template names to be used for the view.
"""
year = self.get_archive_part_value('year')
week = self.get_archive_part_value('week')
month = self.get_archive_part_value('month')
day = self.get_archive_part_value('day... | [
"def",
"get_template_names",
"(",
"self",
")",
":",
"year",
"=",
"self",
".",
"get_archive_part_value",
"(",
"'year'",
")",
"week",
"=",
"self",
".",
"get_archive_part_value",
"(",
"'week'",
")",
"month",
"=",
"self",
".",
"get_archive_part_value",
"(",
"'mont... | Return a list of template names to be used for the view. | [
"Return",
"a",
"list",
"of",
"template",
"names",
"to",
"be",
"used",
"for",
"the",
"view",
"."
] | python | train | 42.311111 |
lcharleux/argiope | argiope/mesh.py | https://github.com/lcharleux/argiope/blob/8170e431362dc760589f7d141090fd133dece259/argiope/mesh.py#L508-L528 | def node_set_to_surface(self, tag):
"""
Converts a node set to surface.
"""
# Create a dummy node with label 0
nodes = self.nodes.copy()
dummy = nodes.iloc[0].copy()
dummy["coords"] *= np.nan
dummy["sets"] = True
nodes.loc[0] = dummy
# Getting element surfaces
element_surface... | [
"def",
"node_set_to_surface",
"(",
"self",
",",
"tag",
")",
":",
"# Create a dummy node with label 0",
"nodes",
"=",
"self",
".",
"nodes",
".",
"copy",
"(",
")",
"dummy",
"=",
"nodes",
".",
"iloc",
"[",
"0",
"]",
".",
"copy",
"(",
")",
"dummy",
"[",
"\... | Converts a node set to surface. | [
"Converts",
"a",
"node",
"set",
"to",
"surface",
"."
] | python | test | 35.809524 |
shoebot/shoebot | lib/graph/__init__.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/graph/__init__.py#L241-L257 | def copy(self, empty=False):
""" Create a copy of the graph (by default with nodes and edges).
"""
g = graph(self.layout.n, self.distance, self.layout.type)
g.layout = self.layout.copy(g)
g.styles = self.styles.copy(g)
g.events = self.events.copy(g)
... | [
"def",
"copy",
"(",
"self",
",",
"empty",
"=",
"False",
")",
":",
"g",
"=",
"graph",
"(",
"self",
".",
"layout",
".",
"n",
",",
"self",
".",
"distance",
",",
"self",
".",
"layout",
".",
"type",
")",
"g",
".",
"layout",
"=",
"self",
".",
"layout... | Create a copy of the graph (by default with nodes and edges). | [
"Create",
"a",
"copy",
"of",
"the",
"graph",
"(",
"by",
"default",
"with",
"nodes",
"and",
"edges",
")",
"."
] | python | valid | 35.529412 |
SheffieldML/GPy | GPy/models/ss_gplvm.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/models/ss_gplvm.py#L249-L251 | def get_X_gradients(self, X):
"""Get the gradients of the posterior distribution of X in its specific form."""
return X.mean.gradient, X.variance.gradient, X.binary_prob.gradient | [
"def",
"get_X_gradients",
"(",
"self",
",",
"X",
")",
":",
"return",
"X",
".",
"mean",
".",
"gradient",
",",
"X",
".",
"variance",
".",
"gradient",
",",
"X",
".",
"binary_prob",
".",
"gradient"
] | Get the gradients of the posterior distribution of X in its specific form. | [
"Get",
"the",
"gradients",
"of",
"the",
"posterior",
"distribution",
"of",
"X",
"in",
"its",
"specific",
"form",
"."
] | python | train | 64 |
Gorialis/jishaku | jishaku/repl/inspections.py | https://github.com/Gorialis/jishaku/blob/fc7c479b9d510ede189a929c8aa6f7c8ef7f9a6e/jishaku/repl/inspections.py#L22-L45 | def add_inspection(name):
"""
Add a Jishaku object inspection
"""
# create the real decorator
def inspection_inner(func):
"""
Jishaku inspection decorator
"""
# pylint: disable=inconsistent-return-statements
# create an encapsulated version of the inspectio... | [
"def",
"add_inspection",
"(",
"name",
")",
":",
"# create the real decorator",
"def",
"inspection_inner",
"(",
"func",
")",
":",
"\"\"\"\n Jishaku inspection decorator\n \"\"\"",
"# pylint: disable=inconsistent-return-statements",
"# create an encapsulated version of the ... | Add a Jishaku object inspection | [
"Add",
"a",
"Jishaku",
"object",
"inspection"
] | python | train | 27.041667 |
annayqho/TheCannon | code/lamost/abundances/calc_gradient_spectra.py | https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/code/lamost/abundances/calc_gradient_spectra.py#L62-L94 | def gen_cannon_grad_spec(choose, coeffs, pivots):
""" Generate Cannon gradient spectra
Parameters
----------
labels: default values for [teff, logg, feh, cfe, nfe, afe, ak]
choose: val of cfe or nfe, whatever you're varying
low: lowest val of cfe or nfe, whatever you're varying
high: highes... | [
"def",
"gen_cannon_grad_spec",
"(",
"choose",
",",
"coeffs",
",",
"pivots",
")",
":",
"base_labels",
"=",
"[",
"4800",
",",
"2.5",
",",
"0.03",
",",
"0.10",
",",
"-",
"0.17",
",",
"-",
"0.17",
",",
"0",
",",
"-",
"0.16",
",",
"-",
"0.13",
",",
"-... | Generate Cannon gradient spectra
Parameters
----------
labels: default values for [teff, logg, feh, cfe, nfe, afe, ak]
choose: val of cfe or nfe, whatever you're varying
low: lowest val of cfe or nfe, whatever you're varying
high: highest val of cfe or nfe, whatever you're varying | [
"Generate",
"Cannon",
"gradient",
"spectra"
] | python | train | 39.787879 |
lambdamusic/Ontospy | ontospy/core/utils.py | https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/utils.py#L651-L674 | def inferURILocalSymbol(aUri):
"""
From a URI returns a tuple (namespace, uri-last-bit)
Eg
from <'http://www.w3.org/2008/05/skos#something'>
==> ('something', 'http://www.w3.org/2008/05/skos')
from <'http://www.w3.org/2003/01/geo/wgs84_pos'> we extract
==> ('wgs84_pos', 'http://www.... | [
"def",
"inferURILocalSymbol",
"(",
"aUri",
")",
":",
"# stringa = aUri.__str__()",
"stringa",
"=",
"aUri",
"try",
":",
"ns",
"=",
"stringa",
".",
"split",
"(",
"\"#\"",
")",
"[",
"0",
"]",
"name",
"=",
"stringa",
".",
"split",
"(",
"\"#\"",
")",
"[",
"... | From a URI returns a tuple (namespace, uri-last-bit)
Eg
from <'http://www.w3.org/2008/05/skos#something'>
==> ('something', 'http://www.w3.org/2008/05/skos')
from <'http://www.w3.org/2003/01/geo/wgs84_pos'> we extract
==> ('wgs84_pos', 'http://www.w3.org/2003/01/geo/') | [
"From",
"a",
"URI",
"returns",
"a",
"tuple",
"(",
"namespace",
"uri",
"-",
"last",
"-",
"bit",
")"
] | python | train | 27.833333 |
darvid/biome | src/biome/__init__.py | https://github.com/darvid/biome/blob/e1f1945165df9def31af42e5e13b623e1de97f01/src/biome/__init__.py#L130-L150 | def get_dict(self, name, default=None):
"""Retrieves an environment variable value as a dictionary.
Args:
name (str): The case-insensitive, unprefixed variable name.
default: If provided, a default value will be returned
instead of throwing ``EnvironmentError``.
... | [
"def",
"get_dict",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"if",
"name",
"not",
"in",
"self",
":",
"if",
"default",
"is",
"not",
"None",
":",
"return",
"default",
"raise",
"EnvironmentError",
".",
"not_found",
"(",
"self",
".",... | Retrieves an environment variable value as a dictionary.
Args:
name (str): The case-insensitive, unprefixed variable name.
default: If provided, a default value will be returned
instead of throwing ``EnvironmentError``.
Returns:
dict: The environment... | [
"Retrieves",
"an",
"environment",
"variable",
"value",
"as",
"a",
"dictionary",
"."
] | python | train | 35.047619 |
koehlma/pygrooveshark | src/grooveshark/classes/album.py | https://github.com/koehlma/pygrooveshark/blob/17673758ac12f54dc26ac879c30ea44f13b81057/src/grooveshark/classes/album.py#L95-L101 | def export(self):
"""
Returns a dictionary with all album information.
Use the :meth:`from_export` method to recreate the
:class:`Album` object.
"""
return {'id' : self.id, 'name' : self.name, 'artist' : self._artist_name, 'artist_id' : self._artist_id, 'cover' : self._co... | [
"def",
"export",
"(",
"self",
")",
":",
"return",
"{",
"'id'",
":",
"self",
".",
"id",
",",
"'name'",
":",
"self",
".",
"name",
",",
"'artist'",
":",
"self",
".",
"_artist_name",
",",
"'artist_id'",
":",
"self",
".",
"_artist_id",
",",
"'cover'",
":"... | Returns a dictionary with all album information.
Use the :meth:`from_export` method to recreate the
:class:`Album` object. | [
"Returns",
"a",
"dictionary",
"with",
"all",
"album",
"information",
".",
"Use",
"the",
":",
"meth",
":",
"from_export",
"method",
"to",
"recreate",
"the",
":",
"class",
":",
"Album",
"object",
"."
] | python | train | 46 |
GPflow/GPflow | gpflow/training/scipy_optimizer.py | https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/training/scipy_optimizer.py#L27-L52 | def make_optimize_tensor(self, model, session=None, var_list=None, **kwargs):
"""
Make SciPy optimization tensor.
The `make_optimize_tensor` method builds optimization tensor and initializes
all necessary variables created by optimizer.
:param model: GPflow model.
... | [
"def",
"make_optimize_tensor",
"(",
"self",
",",
"model",
",",
"session",
"=",
"None",
",",
"var_list",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"session",
"=",
"model",
".",
"enquire_session",
"(",
"session",
")",
"with",
"session",
".",
"as_defa... | Make SciPy optimization tensor.
The `make_optimize_tensor` method builds optimization tensor and initializes
all necessary variables created by optimizer.
:param model: GPflow model.
:param session: Tensorflow session.
:param var_list: List of variables for training.... | [
"Make",
"SciPy",
"optimization",
"tensor",
".",
"The",
"make_optimize_tensor",
"method",
"builds",
"optimization",
"tensor",
"and",
"initializes",
"all",
"necessary",
"variables",
"created",
"by",
"optimizer",
"."
] | python | train | 48.230769 |
jaywink/federation | federation/utils/diaspora.py | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/utils/diaspora.py#L235-L238 | def get_private_endpoint(id: str, guid: str) -> str:
"""Get remote endpoint for delivering private payloads."""
_username, domain = id.split("@")
return "https://%s/receive/users/%s" % (domain, guid) | [
"def",
"get_private_endpoint",
"(",
"id",
":",
"str",
",",
"guid",
":",
"str",
")",
"->",
"str",
":",
"_username",
",",
"domain",
"=",
"id",
".",
"split",
"(",
"\"@\"",
")",
"return",
"\"https://%s/receive/users/%s\"",
"%",
"(",
"domain",
",",
"guid",
")... | Get remote endpoint for delivering private payloads. | [
"Get",
"remote",
"endpoint",
"for",
"delivering",
"private",
"payloads",
"."
] | python | train | 52 |
redcanari/canari3 | src/canari/entrypoints.py | https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/entrypoints.py#L193-L196 | def load_plume_package(package, plume_dir, accept_defaults):
"""Loads a canari package into Plume."""
from canari.commands.load_plume_package import load_plume_package
load_plume_package(package, plume_dir, accept_defaults) | [
"def",
"load_plume_package",
"(",
"package",
",",
"plume_dir",
",",
"accept_defaults",
")",
":",
"from",
"canari",
".",
"commands",
".",
"load_plume_package",
"import",
"load_plume_package",
"load_plume_package",
"(",
"package",
",",
"plume_dir",
",",
"accept_defaults... | Loads a canari package into Plume. | [
"Loads",
"a",
"canari",
"package",
"into",
"Plume",
"."
] | python | train | 58 |
spulec/freezegun | freezegun/api.py | https://github.com/spulec/freezegun/blob/9347d133f33f675c87bb0569d70d9d95abef737f/freezegun/api.py#L397-L413 | def _parse_time_to_freeze(time_to_freeze_str):
"""Parses all the possible inputs for freeze_time
:returns: a naive ``datetime.datetime`` object
"""
if time_to_freeze_str is None:
time_to_freeze_str = datetime.datetime.utcnow()
if isinstance(time_to_freeze_str, datetime.datetime):
ti... | [
"def",
"_parse_time_to_freeze",
"(",
"time_to_freeze_str",
")",
":",
"if",
"time_to_freeze_str",
"is",
"None",
":",
"time_to_freeze_str",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"isinstance",
"(",
"time_to_freeze_str",
",",
"datetime",
"."... | Parses all the possible inputs for freeze_time
:returns: a naive ``datetime.datetime`` object | [
"Parses",
"all",
"the",
"possible",
"inputs",
"for",
"freeze_time",
":",
"returns",
":",
"a",
"naive",
"datetime",
".",
"datetime",
"object"
] | python | train | 43.352941 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.