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 |
|---|---|---|---|---|---|---|---|---|---|
arne-cl/discoursegraphs | src/discoursegraphs/discoursegraph.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/discoursegraph.py#L1204-L1254 | def select_edges_by_attribute(docgraph, attribute=None, value=None, data=False):
"""
get all edges with the given edge type and layer.
Parameters
----------
docgraph : DiscourseDocumentGraph
document graph from which the nodes will be extracted
attribute : str or None
Name of th... | [
"def",
"select_edges_by_attribute",
"(",
"docgraph",
",",
"attribute",
"=",
"None",
",",
"value",
"=",
"None",
",",
"data",
"=",
"False",
")",
":",
"if",
"attribute",
":",
"attrib_key_eval",
"=",
"\"'{}' in edge_attribs\"",
".",
"format",
"(",
"attribute",
")"... | get all edges with the given edge type and layer.
Parameters
----------
docgraph : DiscourseDocumentGraph
document graph from which the nodes will be extracted
attribute : str or None
Name of the node attribute that all nodes must posess.
If None, returns all nodes.
value : ... | [
"get",
"all",
"edges",
"with",
"the",
"given",
"edge",
"type",
"and",
"layer",
"."
] | python | train | 40.490196 |
Autodesk/aomi | aomi/model/context.py | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/context.py#L161-L165 | def freeze(self, dest_dir):
"""Freezes every resource within a context"""
for resource in self.resources():
if resource.present:
resource.freeze(dest_dir) | [
"def",
"freeze",
"(",
"self",
",",
"dest_dir",
")",
":",
"for",
"resource",
"in",
"self",
".",
"resources",
"(",
")",
":",
"if",
"resource",
".",
"present",
":",
"resource",
".",
"freeze",
"(",
"dest_dir",
")"
] | Freezes every resource within a context | [
"Freezes",
"every",
"resource",
"within",
"a",
"context"
] | python | train | 38.8 |
Qiskit/qiskit-terra | qiskit/transpiler/passes/mapping/check_map.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/passes/mapping/check_map.py#L34-L56 | def run(self, dag):
"""
If `dag` is mapped to `coupling_map`, the property
`is_swap_mapped` is set to True (or to False otherwise).
Args:
dag (DAGCircuit): DAG to map.
"""
if self.layout is None:
if self.property_set["layout"]:
sel... | [
"def",
"run",
"(",
"self",
",",
"dag",
")",
":",
"if",
"self",
".",
"layout",
"is",
"None",
":",
"if",
"self",
".",
"property_set",
"[",
"\"layout\"",
"]",
":",
"self",
".",
"layout",
"=",
"self",
".",
"property_set",
"[",
"\"layout\"",
"]",
"else",
... | If `dag` is mapped to `coupling_map`, the property
`is_swap_mapped` is set to True (or to False otherwise).
Args:
dag (DAGCircuit): DAG to map. | [
"If",
"dag",
"is",
"mapped",
"to",
"coupling_map",
"the",
"property",
"is_swap_mapped",
"is",
"set",
"to",
"True",
"(",
"or",
"to",
"False",
"otherwise",
")",
"."
] | python | test | 34.391304 |
SeattleTestbed/seash | pyreadline/console/console.py | https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/console/console.py#L421-L430 | def text(self, x, y, text, attr=None):
u'''Write text at the given position.'''
if attr is None:
attr = self.attr
pos = self.fixcoord(x, y)
n = DWORD(0)
self.WriteConsoleOutputCharacterW(self.hout, text,
len(text), p... | [
"def",
"text",
"(",
"self",
",",
"x",
",",
"y",
",",
"text",
",",
"attr",
"=",
"None",
")",
":",
"if",
"attr",
"is",
"None",
":",
"attr",
"=",
"self",
".",
"attr",
"pos",
"=",
"self",
".",
"fixcoord",
"(",
"x",
",",
"y",
")",
"n",
"=",
"DWO... | u'''Write text at the given position. | [
"u",
"Write",
"text",
"at",
"the",
"given",
"position",
"."
] | python | train | 40 |
defunkt/pystache | pystache/loader.py | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/loader.py#L112-L122 | def read(self, path, encoding=None):
"""
Read the template at the given path, and return it as a unicode string.
"""
b = common.read(path)
if encoding is None:
encoding = self.file_encoding
return self.unicode(b, encoding) | [
"def",
"read",
"(",
"self",
",",
"path",
",",
"encoding",
"=",
"None",
")",
":",
"b",
"=",
"common",
".",
"read",
"(",
"path",
")",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"self",
".",
"file_encoding",
"return",
"self",
".",
"unicode",
... | Read the template at the given path, and return it as a unicode string. | [
"Read",
"the",
"template",
"at",
"the",
"given",
"path",
"and",
"return",
"it",
"as",
"a",
"unicode",
"string",
"."
] | python | train | 25 |
chrisspen/burlap | burlap/apache.py | https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/apache.py#L519-L555 | def configure_modsecurity(self):
"""
Installs the mod-security Apache module.
https://www.modsecurity.org
"""
r = self.local_renderer
if r.env.modsecurity_enabled and not self.last_manifest.modsecurity_enabled:
self.install_packages()
# Write mo... | [
"def",
"configure_modsecurity",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"local_renderer",
"if",
"r",
".",
"env",
".",
"modsecurity_enabled",
"and",
"not",
"self",
".",
"last_manifest",
".",
"modsecurity_enabled",
":",
"self",
".",
"install_packages",
"("... | Installs the mod-security Apache module.
https://www.modsecurity.org | [
"Installs",
"the",
"mod",
"-",
"security",
"Apache",
"module",
"."
] | python | valid | 52.891892 |
joeyespo/grip | grip/renderers.py | https://github.com/joeyespo/grip/blob/ce933ccc4ca8e0d3718f271c59bd530a4518bf63/grip/renderers.py#L95-L110 | def render(self, text, auth=None):
"""
Renders the specified markdown content and embedded styles.
"""
if markdown is None:
import markdown
if UrlizeExtension is None:
from .mdx_urlize import UrlizeExtension
return markdown.markdown(text, extension... | [
"def",
"render",
"(",
"self",
",",
"text",
",",
"auth",
"=",
"None",
")",
":",
"if",
"markdown",
"is",
"None",
":",
"import",
"markdown",
"if",
"UrlizeExtension",
"is",
"None",
":",
"from",
".",
"mdx_urlize",
"import",
"UrlizeExtension",
"return",
"markdow... | Renders the specified markdown content and embedded styles. | [
"Renders",
"the",
"specified",
"markdown",
"content",
"and",
"embedded",
"styles",
"."
] | python | train | 30.6875 |
manns/pyspread | pyspread/src/gui/_grid.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_grid.py#L1152-L1184 | def OnMouseWheel(self, event):
"""Event handler for mouse wheel actions
Invokes zoom when mouse when Ctrl is also pressed
"""
if event.ControlDown():
if event.WheelRotation > 0:
post_command_event(self.grid, self.grid.ZoomInMsg)
else:
... | [
"def",
"OnMouseWheel",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"ControlDown",
"(",
")",
":",
"if",
"event",
".",
"WheelRotation",
">",
"0",
":",
"post_command_event",
"(",
"self",
".",
"grid",
",",
"self",
".",
"grid",
".",
"ZoomInMsg"... | Event handler for mouse wheel actions
Invokes zoom when mouse when Ctrl is also pressed | [
"Event",
"handler",
"for",
"mouse",
"wheel",
"actions"
] | python | train | 34.424242 |
nerdvegas/rez | src/rez/utils/memcached.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/memcached.py#L229-L245 | def pool_memcached_connections(func):
"""Function decorator to pool memcached connections.
Use this to wrap functions that might make multiple calls to memcached. This
will cause a single memcached client to be shared for all connections.
"""
if isgeneratorfunction(func):
def wrapper(*nargs... | [
"def",
"pool_memcached_connections",
"(",
"func",
")",
":",
"if",
"isgeneratorfunction",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"nargs",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"memcached_client",
"(",
")",
":",
"for",
"result",
"in",
"fun... | Function decorator to pool memcached connections.
Use this to wrap functions that might make multiple calls to memcached. This
will cause a single memcached client to be shared for all connections. | [
"Function",
"decorator",
"to",
"pool",
"memcached",
"connections",
"."
] | python | train | 36.117647 |
slundberg/shap | shap/benchmark/methods.py | https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/methods.py#L91-L94 | def lime_tabular_regression_1000(model, data):
""" LIME Tabular 1000
"""
return lambda X: other.LimeTabularExplainer(model.predict, data, mode="regression").attributions(X, nsamples=1000) | [
"def",
"lime_tabular_regression_1000",
"(",
"model",
",",
"data",
")",
":",
"return",
"lambda",
"X",
":",
"other",
".",
"LimeTabularExplainer",
"(",
"model",
".",
"predict",
",",
"data",
",",
"mode",
"=",
"\"regression\"",
")",
".",
"attributions",
"(",
"X",... | LIME Tabular 1000 | [
"LIME",
"Tabular",
"1000"
] | python | train | 49 |
RudolfCardinal/pythonlib | cardinal_pythonlib/interval.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L290-L294 | def contiguous(self, other: "Interval") -> bool:
"""
Does this interval overlap or touch the other?
"""
return not(self.end < other.start or self.start > other.end) | [
"def",
"contiguous",
"(",
"self",
",",
"other",
":",
"\"Interval\"",
")",
"->",
"bool",
":",
"return",
"not",
"(",
"self",
".",
"end",
"<",
"other",
".",
"start",
"or",
"self",
".",
"start",
">",
"other",
".",
"end",
")"
] | Does this interval overlap or touch the other? | [
"Does",
"this",
"interval",
"overlap",
"or",
"touch",
"the",
"other?"
] | python | train | 38.4 |
SmokinCaterpillar/pypet | pypet/trajectory.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/trajectory.py#L3710-L3788 | def f_load_items(self, iterator, *args, **kwargs):
"""Loads parameters and results specified in `iterator`.
You can directly list the Parameter objects or just their names.
If names are given the `~pypet.naturalnaming.NNGroupNode.f_get` method is applied to find the
parameters or resul... | [
"def",
"f_load_items",
"(",
"self",
",",
"iterator",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"_stored",
":",
"raise",
"TypeError",
"(",
"'Cannot load stuff from disk for a trajectory that has never been stored.'",
")",
"fetch... | Loads parameters and results specified in `iterator`.
You can directly list the Parameter objects or just their names.
If names are given the `~pypet.naturalnaming.NNGroupNode.f_get` method is applied to find the
parameters or results in the trajectory. Accordingly, the parameters and results
... | [
"Loads",
"parameters",
"and",
"results",
"specified",
"in",
"iterator",
"."
] | python | test | 48.303797 |
Tinche/cattrs | src/cattr/converters.py | https://github.com/Tinche/cattrs/blob/481bc9bdb69b2190d699b54f331c8c5c075506d5/src/cattr/converters.py#L294-L317 | def structure_attrs_fromdict(self, obj, cl):
# type: (Mapping[str, Any], Type[T]) -> T
"""Instantiate an attrs class from a mapping (dict)."""
# For public use.
conv_obj = {} # Start with a fresh dict, to ignore extra keys.
dispatch = self._structure_func.dispatch
for a ... | [
"def",
"structure_attrs_fromdict",
"(",
"self",
",",
"obj",
",",
"cl",
")",
":",
"# type: (Mapping[str, Any], Type[T]) -> T",
"# For public use.",
"conv_obj",
"=",
"{",
"}",
"# Start with a fresh dict, to ignore extra keys.",
"dispatch",
"=",
"self",
".",
"_structure_func",... | Instantiate an attrs class from a mapping (dict). | [
"Instantiate",
"an",
"attrs",
"class",
"from",
"a",
"mapping",
"(",
"dict",
")",
"."
] | python | train | 31.375 |
vmlaker/coils | coils/SocketTalk.py | https://github.com/vmlaker/coils/blob/a3a613b3d661dec010e5879c86e62cbff2519dd0/coils/SocketTalk.py#L38-L50 | def client(addr):
"""Return a SocketTalk client."""
success = False
while not success:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.connect(addr)
... | [
"def",
"client",
"(",
"addr",
")",
":",
"success",
"=",
"False",
"while",
"not",
"success",
":",
"try",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"sock",
".",
"setsockopt",
"(",
... | Return a SocketTalk client. | [
"Return",
"a",
"SocketTalk",
"client",
"."
] | python | train | 34.615385 |
pjuren/pyokit | src/pyokit/io/genomeAlignment.py | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/io/genomeAlignment.py#L167-L201 | def build_genome_alignment_from_directory(d_name, ref_spec, extensions=None,
index_exts=None,
fail_no_index=False):
"""
build a genome aligment by loading all files in a directory.
Fiel without indexes are loaded immediately; tho... | [
"def",
"build_genome_alignment_from_directory",
"(",
"d_name",
",",
"ref_spec",
",",
"extensions",
"=",
"None",
",",
"index_exts",
"=",
"None",
",",
"fail_no_index",
"=",
"False",
")",
":",
"if",
"index_exts",
"is",
"None",
"and",
"fail_no_index",
":",
"raise",
... | build a genome aligment by loading all files in a directory.
Fiel without indexes are loaded immediately; those with indexes are
loaded on-demand. Not recursive (i.e. subdirectories are not parsed).
:param d_name: directory to load from.
:param ref_spec: which species in the alignemnt files is the... | [
"build",
"a",
"genome",
"aligment",
"by",
"loading",
"all",
"files",
"in",
"a",
"directory",
"."
] | python | train | 48.142857 |
openatx/facebook-wda | wda/__init__.py | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L239-L305 | def session(self, bundle_id=None, arguments=None, environment=None):
"""
Args:
- bundle_id (str): the app bundle id
- arguments (list): ['-u', 'https://www.google.com/ncr']
- enviroment (dict): {"KEY": "VAL"}
WDA Return json like
{
"value... | [
"def",
"session",
"(",
"self",
",",
"bundle_id",
"=",
"None",
",",
"arguments",
"=",
"None",
",",
"environment",
"=",
"None",
")",
":",
"if",
"bundle_id",
"is",
"None",
":",
"sid",
"=",
"self",
".",
"status",
"(",
")",
"[",
"'sessionId'",
"]",
"if",
... | Args:
- bundle_id (str): the app bundle id
- arguments (list): ['-u', 'https://www.google.com/ncr']
- enviroment (dict): {"KEY": "VAL"}
WDA Return json like
{
"value": {
"sessionId": "69E6FDBA-8D59-4349-B7DE-A9CA41A97814",
... | [
"Args",
":",
"-",
"bundle_id",
"(",
"str",
")",
":",
"the",
"app",
"bundle",
"id",
"-",
"arguments",
"(",
"list",
")",
":",
"[",
"-",
"u",
"https",
":",
"//",
"www",
".",
"google",
".",
"com",
"/",
"ncr",
"]",
"-",
"enviroment",
"(",
"dict",
")... | python | train | 33.80597 |
tsroten/hanzidentifier | hanzidentifier.py | https://github.com/tsroten/hanzidentifier/blob/40b565222363f5582fd06dc14833d2b86f09fa35/hanzidentifier.py#L88-L102 | def is_simplified(s):
"""Check if a string's Chinese characters are Simplified.
This is equivalent to:
>>> identify('foo') in (SIMPLIFIED, BOTH)
"""
chinese = _get_hanzi(s)
if not chinese:
return False
elif chinese.issubset(_SHARED_CHARACTERS):
return True
elif chin... | [
"def",
"is_simplified",
"(",
"s",
")",
":",
"chinese",
"=",
"_get_hanzi",
"(",
"s",
")",
"if",
"not",
"chinese",
":",
"return",
"False",
"elif",
"chinese",
".",
"issubset",
"(",
"_SHARED_CHARACTERS",
")",
":",
"return",
"True",
"elif",
"chinese",
".",
"i... | Check if a string's Chinese characters are Simplified.
This is equivalent to:
>>> identify('foo') in (SIMPLIFIED, BOTH) | [
"Check",
"if",
"a",
"string",
"s",
"Chinese",
"characters",
"are",
"Simplified",
"."
] | python | train | 25.333333 |
spotify/snakebite | snakebite/channel.py | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/channel.py#L293-L301 | def create_connection_context(self):
'''Creates and seriazlies a IpcConnectionContextProto (not delimited)'''
context = IpcConnectionContextProto()
context.userInfo.effectiveUser = self.effective_user
context.protocol = "org.apache.hadoop.hdfs.protocol.ClientProtocol"
s_context ... | [
"def",
"create_connection_context",
"(",
"self",
")",
":",
"context",
"=",
"IpcConnectionContextProto",
"(",
")",
"context",
".",
"userInfo",
".",
"effectiveUser",
"=",
"self",
".",
"effective_user",
"context",
".",
"protocol",
"=",
"\"org.apache.hadoop.hdfs.protocol.... | Creates and seriazlies a IpcConnectionContextProto (not delimited) | [
"Creates",
"and",
"seriazlies",
"a",
"IpcConnectionContextProto",
"(",
"not",
"delimited",
")"
] | python | train | 49.888889 |
ericsomdahl/python-bittrex | bittrex/bittrex.py | https://github.com/ericsomdahl/python-bittrex/blob/2dbc08e3221e07a9e618eaa025d98ed197d28e31/bittrex/bittrex.py#L123-L171 | def _api_query(self, protection=None, path_dict=None, options=None):
"""
Queries Bittrex
:param request_url: fully-formed URL to request
:type options: dict
:return: JSON response from Bittrex
:rtype : dict
"""
if not options:
options = {}
... | [
"def",
"_api_query",
"(",
"self",
",",
"protection",
"=",
"None",
",",
"path_dict",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"if",
"not",
"options",
":",
"options",
"=",
"{",
"}",
"if",
"self",
".",
"api_version",
"not",
"in",
"path_dict",
... | Queries Bittrex
:param request_url: fully-formed URL to request
:type options: dict
:return: JSON response from Bittrex
:rtype : dict | [
"Queries",
"Bittrex"
] | python | train | 31.755102 |
cbclab/MOT | mot/optimize/__init__.py | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/optimize/__init__.py#L742-L822 | def _get_penalty_function(nmr_parameters, constraints_func=None):
"""Get a function to compute the penalty term for the boundary conditions.
This is meant to be used in the evaluation function of the optimization routines.
Args:
nmr_parameters (int): the number of parameters in the model
c... | [
"def",
"_get_penalty_function",
"(",
"nmr_parameters",
",",
"constraints_func",
"=",
"None",
")",
":",
"dependencies",
"=",
"[",
"]",
"data_requirements",
"=",
"{",
"'scratch'",
":",
"LocalMemory",
"(",
"'double'",
",",
"1",
")",
"}",
"constraints_code",
"=",
... | Get a function to compute the penalty term for the boundary conditions.
This is meant to be used in the evaluation function of the optimization routines.
Args:
nmr_parameters (int): the number of parameters in the model
constraints_func (mot.optimize.base.ConstraintFunction): function to compu... | [
"Get",
"a",
"function",
"to",
"compute",
"the",
"penalty",
"term",
"for",
"the",
"boundary",
"conditions",
"."
] | python | train | 39.382716 |
COALAIP/pycoalaip | coalaip/models.py | https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/models.py#L255-L262 | def manifestation_model_factory(*, validator=validators.is_manifestation_model,
ld_type='CreativeWork', **kwargs):
"""Generate a Manifestation model.
Expects ``data``, ``validator``, ``model_cls``, ``ld_type``, and
``ld_context`` as keyword arguments.
"""
return _mod... | [
"def",
"manifestation_model_factory",
"(",
"*",
",",
"validator",
"=",
"validators",
".",
"is_manifestation_model",
",",
"ld_type",
"=",
"'CreativeWork'",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_model_factory",
"(",
"validator",
"=",
"validator",
",",
"ld... | Generate a Manifestation model.
Expects ``data``, ``validator``, ``model_cls``, ``ld_type``, and
``ld_context`` as keyword arguments. | [
"Generate",
"a",
"Manifestation",
"model",
"."
] | python | train | 46.375 |
lionheart/django-pyodbc | django_pyodbc/operations.py | https://github.com/lionheart/django-pyodbc/blob/46adda7b0bfabfa2640f72592c6f6f407f78b363/django_pyodbc/operations.py#L124-L146 | def _get_sql_server_ver(self):
"""
Returns the version of the SQL Server in use:
"""
if self._ss_ver is not None:
return self._ss_ver
cur = self.connection.cursor()
ver_code = None
if not self.is_db2 and not self.is_openedge:
cur.execute("S... | [
"def",
"_get_sql_server_ver",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ss_ver",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_ss_ver",
"cur",
"=",
"self",
".",
"connection",
".",
"cursor",
"(",
")",
"ver_code",
"=",
"None",
"if",
"not",
"self",... | Returns the version of the SQL Server in use: | [
"Returns",
"the",
"version",
"of",
"the",
"SQL",
"Server",
"in",
"use",
":"
] | python | train | 32.173913 |
cloudtools/stacker | stacker/providers/aws/default.py | https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/providers/aws/default.py#L951-L983 | def noninteractive_changeset_update(self, fqn, template, old_parameters,
parameters, stack_policy, tags,
**kwargs):
"""Update a Cloudformation stack using a change set.
This is required for stacks with a defined Transform (... | [
"def",
"noninteractive_changeset_update",
"(",
"self",
",",
"fqn",
",",
"template",
",",
"old_parameters",
",",
"parameters",
",",
"stack_policy",
",",
"tags",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"\"Using noninterative changeset provide... | Update a Cloudformation stack using a change set.
This is required for stacks with a defined Transform (i.e. SAM), as the
default update_stack API cannot be used with them.
Args:
fqn (str): The fully qualified name of the Cloudformation stack.
template (:class:`stacker.... | [
"Update",
"a",
"Cloudformation",
"stack",
"using",
"a",
"change",
"set",
"."
] | python | train | 49.121212 |
ScienceLogic/amiuploader | amiimporter/AWSUtilities.py | https://github.com/ScienceLogic/amiuploader/blob/c36c247b2226107b38571cbc6119118b1fe07182/amiimporter/AWSUtilities.py#L12-L24 | def parse_image_json(text):
"""
parses response output of AWS describe commands and returns the first (and only) item in array
:param text: describe output
:return: image json
"""
image_details = json.loads(text)
if image_details.get('Images') is not None:
try:
image_deta... | [
"def",
"parse_image_json",
"(",
"text",
")",
":",
"image_details",
"=",
"json",
".",
"loads",
"(",
"text",
")",
"if",
"image_details",
".",
"get",
"(",
"'Images'",
")",
"is",
"not",
"None",
":",
"try",
":",
"image_details",
"=",
"image_details",
".",
"ge... | parses response output of AWS describe commands and returns the first (and only) item in array
:param text: describe output
:return: image json | [
"parses",
"response",
"output",
"of",
"AWS",
"describe",
"commands",
"and",
"returns",
"the",
"first",
"(",
"and",
"only",
")",
"item",
"in",
"array",
":",
"param",
"text",
":",
"describe",
"output",
":",
"return",
":",
"image",
"json"
] | python | train | 33 |
KrzyHonk/bpmn-python | bpmn_python/diagram_layout_metrics.py | https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/diagram_layout_metrics.py#L130-L149 | def orientation(p1, p2, p3):
"""
Finds orientation of three points p1, p2, p3.
The function returns following values
0 --> p1, p2 and p3 are collinear
1 --> Clockwise
2 --> Counterclockwise
:param p1: tuple representing two dimensional point
:param p2: tuple representing two dimensional ... | [
"def",
"orientation",
"(",
"p1",
",",
"p2",
",",
"p3",
")",
":",
"val",
"=",
"(",
"p2",
"[",
"consts",
".",
"Consts",
".",
"y",
"]",
"-",
"p1",
"[",
"consts",
".",
"Consts",
".",
"y",
"]",
")",
"*",
"(",
"p3",
"[",
"consts",
".",
"Consts",
... | Finds orientation of three points p1, p2, p3.
The function returns following values
0 --> p1, p2 and p3 are collinear
1 --> Clockwise
2 --> Counterclockwise
:param p1: tuple representing two dimensional point
:param p2: tuple representing two dimensional point
:param p3: tuple representing t... | [
"Finds",
"orientation",
"of",
"three",
"points",
"p1",
"p2",
"p3",
".",
"The",
"function",
"returns",
"following",
"values",
"0",
"--",
">",
"p1",
"p2",
"and",
"p3",
"are",
"collinear",
"1",
"--",
">",
"Clockwise",
"2",
"--",
">",
"Counterclockwise",
":"... | python | train | 34.75 |
knagra/farnsworth | workshift/views.py | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L894-L1020 | def assign_shifts_view(request, semester):
"""
View all members' preferences. This view also includes forms to create an
entire semester's worth of weekly workshifts.
"""
page_name = "Assign Shifts"
auto_assign_shifts_form = None
random_assign_instances_form = None
clear_assign_form = N... | [
"def",
"assign_shifts_view",
"(",
"request",
",",
"semester",
")",
":",
"page_name",
"=",
"\"Assign Shifts\"",
"auto_assign_shifts_form",
"=",
"None",
"random_assign_instances_form",
"=",
"None",
"clear_assign_form",
"=",
"None",
"if",
"WorkshiftPool",
".",
"objects",
... | View all members' preferences. This view also includes forms to create an
entire semester's worth of weekly workshifts. | [
"View",
"all",
"members",
"preferences",
".",
"This",
"view",
"also",
"includes",
"forms",
"to",
"create",
"an",
"entire",
"semester",
"s",
"worth",
"of",
"weekly",
"workshifts",
"."
] | python | train | 35.787402 |
gwpy/gwpy | gwpy/segments/flag.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/flag.py#L1330-L1399 | def from_veto_definer_file(cls, fp, start=None, end=None, ifo=None,
format='ligolw'):
"""Read a `DataQualityDict` from a LIGO_LW XML VetoDefinerTable.
Parameters
----------
fp : `str`
path of veto definer file to read
start : `~gwpy.tim... | [
"def",
"from_veto_definer_file",
"(",
"cls",
",",
"fp",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"ifo",
"=",
"None",
",",
"format",
"=",
"'ligolw'",
")",
":",
"if",
"format",
"!=",
"'ligolw'",
":",
"raise",
"NotImplementedError",
"(",
"... | Read a `DataQualityDict` from a LIGO_LW XML VetoDefinerTable.
Parameters
----------
fp : `str`
path of veto definer file to read
start : `~gwpy.time.LIGOTimeGPS`, `int`, optional
GPS start time at which to restrict returned flags
end : `~gwpy.time.LIGOTim... | [
"Read",
"a",
"DataQualityDict",
"from",
"a",
"LIGO_LW",
"XML",
"VetoDefinerTable",
"."
] | python | train | 36.571429 |
honeynet/beeswarm | beeswarm/drones/honeypot/capabilities/shared/shell.py | https://github.com/honeynet/beeswarm/blob/db51ea0bc29f631c3e3b5312b479ac9d5e31079a/beeswarm/drones/honeypot/capabilities/shared/shell.py#L244-L273 | def handle(self):
"The actual service to which the user has connected."
if not self.authentication_ok():
return
if self.DOECHO:
self.writeline(self.WELCOME)
self.session_start()
while self.RUNSHELL:
read_line = self.readline(prompt=self.PROMPT)... | [
"def",
"handle",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"authentication_ok",
"(",
")",
":",
"return",
"if",
"self",
".",
"DOECHO",
":",
"self",
".",
"writeline",
"(",
"self",
".",
"WELCOME",
")",
"self",
".",
"session_start",
"(",
")",
"whi... | The actual service to which the user has connected. | [
"The",
"actual",
"service",
"to",
"which",
"the",
"user",
"has",
"connected",
"."
] | python | train | 43.5 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsRepAgentModel.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsRepAgentModel.py#L94-L185 | def solveConsRepAgentMarkov(solution_next,MrkvArray,DiscFac,CRRA,IncomeDstn,CapShare,DeprFac,PermGroFac,aXtraGrid):
'''
Solve one period of the simple representative agent consumption-saving model.
This version supports a discrete Markov process.
Parameters
----------
solution_next : ConsumerSo... | [
"def",
"solveConsRepAgentMarkov",
"(",
"solution_next",
",",
"MrkvArray",
",",
"DiscFac",
",",
"CRRA",
",",
"IncomeDstn",
",",
"CapShare",
",",
"DeprFac",
",",
"PermGroFac",
",",
"aXtraGrid",
")",
":",
"# Define basic objects",
"StateCount",
"=",
"MrkvArray",
".",... | Solve one period of the simple representative agent consumption-saving model.
This version supports a discrete Markov process.
Parameters
----------
solution_next : ConsumerSolution
Solution to the next period's problem (i.e. previous iteration).
MrkvArray : np.array
Markov transiti... | [
"Solve",
"one",
"period",
"of",
"the",
"simple",
"representative",
"agent",
"consumption",
"-",
"saving",
"model",
".",
"This",
"version",
"supports",
"a",
"discrete",
"Markov",
"process",
"."
] | python | train | 45.413043 |
cidles/pressagio | src/pressagio/dbconnector.py | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/dbconnector.py#L225-L239 | def insert_ngram(self, ngram, count):
"""
Inserts a given n-gram with count into the database.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings.
count : int
The count for the given n-gram.
"""
query = ... | [
"def",
"insert_ngram",
"(",
"self",
",",
"ngram",
",",
"count",
")",
":",
"query",
"=",
"\"INSERT INTO _{0}_gram {1};\"",
".",
"format",
"(",
"len",
"(",
"ngram",
")",
",",
"self",
".",
"_build_values_clause",
"(",
"ngram",
",",
"count",
")",
")",
"self",
... | Inserts a given n-gram with count into the database.
Parameters
----------
ngram : iterable of str
A list, set or tuple of strings.
count : int
The count for the given n-gram. | [
"Inserts",
"a",
"given",
"n",
"-",
"gram",
"with",
"count",
"into",
"the",
"database",
"."
] | python | train | 29.2 |
sentinel-hub/eo-learn | core/eolearn/core/utilities.py | https://github.com/sentinel-hub/eo-learn/blob/b8c390b9f553c561612fe9eb64e720611633a035/core/eolearn/core/utilities.py#L204-L212 | def _parse_names_set(feature_names):
"""Helping function of `_parse_feature_names` that parses a set of feature names."""
feature_collection = OrderedDict()
for feature_name in feature_names:
if isinstance(feature_name, str):
feature_collection[feature_name] = ..... | [
"def",
"_parse_names_set",
"(",
"feature_names",
")",
":",
"feature_collection",
"=",
"OrderedDict",
"(",
")",
"for",
"feature_name",
"in",
"feature_names",
":",
"if",
"isinstance",
"(",
"feature_name",
",",
"str",
")",
":",
"feature_collection",
"[",
"feature_nam... | Helping function of `_parse_feature_names` that parses a set of feature names. | [
"Helping",
"function",
"of",
"_parse_feature_names",
"that",
"parses",
"a",
"set",
"of",
"feature",
"names",
"."
] | python | train | 51.222222 |
Fuyukai/ConfigMaster | configmaster/ConfigKey.py | https://github.com/Fuyukai/ConfigMaster/blob/8018aa415da55c84edaa8a49664f674758a14edd/configmaster/ConfigKey.py#L79-L129 | def load_from_dict(self, data: dict, overwrite: bool=True):
"""
Loads key/values from dicts or list into the ConfigKey.
:param data: The data object to load.
This can be a dict, or a list of key/value tuples.
:param overwrite: Should the ConfigKey overwrite data a... | [
"def",
"load_from_dict",
"(",
"self",
",",
"data",
":",
"dict",
",",
"overwrite",
":",
"bool",
"=",
"True",
")",
":",
"if",
"data",
"is",
"None",
"or",
"data",
"==",
"{",
"}",
":",
"return",
"False",
"# Loop over items",
"if",
"isinstance",
"(",
"data"... | Loads key/values from dicts or list into the ConfigKey.
:param data: The data object to load.
This can be a dict, or a list of key/value tuples.
:param overwrite: Should the ConfigKey overwrite data already in it? | [
"Loads",
"key",
"/",
"values",
"from",
"dicts",
"or",
"list",
"into",
"the",
"ConfigKey",
".",
":",
"param",
"data",
":",
"The",
"data",
"object",
"to",
"load",
".",
"This",
"can",
"be",
"a",
"dict",
"or",
"a",
"list",
"of",
"key",
"/",
"value",
"t... | python | train | 46.176471 |
gem/oq-engine | openquake/hazardlib/site.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L313-L324 | def split_in_tiles(self, hint):
"""
Split a SiteCollection into a set of tiles (SiteCollection instances).
:param hint: hint for how many tiles to generate
"""
tiles = []
for seq in split_in_blocks(range(len(self)), hint or 1):
sc = SiteCollection.__new__(Sit... | [
"def",
"split_in_tiles",
"(",
"self",
",",
"hint",
")",
":",
"tiles",
"=",
"[",
"]",
"for",
"seq",
"in",
"split_in_blocks",
"(",
"range",
"(",
"len",
"(",
"self",
")",
")",
",",
"hint",
"or",
"1",
")",
":",
"sc",
"=",
"SiteCollection",
".",
"__new_... | Split a SiteCollection into a set of tiles (SiteCollection instances).
:param hint: hint for how many tiles to generate | [
"Split",
"a",
"SiteCollection",
"into",
"a",
"set",
"of",
"tiles",
"(",
"SiteCollection",
"instances",
")",
"."
] | python | train | 35.666667 |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L403-L406 | def ban_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/bans#create-ban"
api_path = "/api/v2/bans"
return self.call(api_path, method="POST", data=data, **kwargs) | [
"def",
"ban_create",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/bans\"",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"POST\"",
",",
"data",
"=",
"data",
",",
"*",
"*",
"kwargs",
... | https://developer.zendesk.com/rest_api/docs/chat/bans#create-ban | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"chat",
"/",
"bans#create",
"-",
"ban"
] | python | train | 53.5 |
CTPUG/wafer | wafer/schedule/admin.py | https://github.com/CTPUG/wafer/blob/a20af3c399267f76373dc342f4d542a9bc457c35/wafer/schedule/admin.py#L55-L69 | def find_non_contiguous(all_items):
"""Find any items that have slots that aren't contiguous"""
non_contiguous = []
for item in all_items:
if item.slots.count() < 2:
# No point in checking
continue
last_slot = None
for slot in item.slots.all().order_by('end_ti... | [
"def",
"find_non_contiguous",
"(",
"all_items",
")",
":",
"non_contiguous",
"=",
"[",
"]",
"for",
"item",
"in",
"all_items",
":",
"if",
"item",
".",
"slots",
".",
"count",
"(",
")",
"<",
"2",
":",
"# No point in checking",
"continue",
"last_slot",
"=",
"No... | Find any items that have slots that aren't contiguous | [
"Find",
"any",
"items",
"that",
"have",
"slots",
"that",
"aren",
"t",
"contiguous"
] | python | train | 35.333333 |
luckydonald/pytgbot | code_generation/output/teleflask_messages.py | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L2658-L2670 | def send(self, sender: PytgbotApiBot):
"""
Send the message via pytgbot.
:param sender: The bot instance to send with.
:type sender: pytgbot.bot.Bot
:rtype: PytgbotApiMessage
"""
return sender.send_location(
# receiver, self.media, disable_notificat... | [
"def",
"send",
"(",
"self",
",",
"sender",
":",
"PytgbotApiBot",
")",
":",
"return",
"sender",
".",
"send_location",
"(",
"# receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id",
"latitude",
"=",
"self",
".",
"latitude",
",",
... | Send the message via pytgbot.
:param sender: The bot instance to send with.
:type sender: pytgbot.bot.Bot
:rtype: PytgbotApiMessage | [
"Send",
"the",
"message",
"via",
"pytgbot",
"."
] | python | train | 46.615385 |
estnltk/estnltk | estnltk/prettyprinter/rules.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/prettyprinter/rules.py#L51-L67 | def create_rules(aes, value):
"""Create a Rules instance for a single aesthetic value.
Parameter
---------
aes: str
The name of the aesthetic
value: str or list
The value associated with any aesthetic
"""
if isinstance(value, six.string_types):
return Rules(aes)
... | [
"def",
"create_rules",
"(",
"aes",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"return",
"Rules",
"(",
"aes",
")",
"else",
":",
"rules",
"=",
"Rules",
"(",
")",
"for",
"idx",
",",
"(",
"patte... | Create a Rules instance for a single aesthetic value.
Parameter
---------
aes: str
The name of the aesthetic
value: str or list
The value associated with any aesthetic | [
"Create",
"a",
"Rules",
"instance",
"for",
"a",
"single",
"aesthetic",
"value",
"."
] | python | train | 28.058824 |
DarkEnergySurvey/ugali | ugali/scratch/simulation/survey_selection_function.py | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L87-L113 | def angsep(lon1, lat1, lon2, lat2):
"""
Angular separation (deg) between two sky coordinates.
Borrowed from astropy (www.astropy.org)
Notes
-----
The angular separation is calculated using the Vincenty formula [1],
which is slighly more complex and computationally expensive than
some alt... | [
"def",
"angsep",
"(",
"lon1",
",",
"lat1",
",",
"lon2",
",",
"lat2",
")",
":",
"lon1",
",",
"lat1",
"=",
"np",
".",
"radians",
"(",
"[",
"lon1",
",",
"lat1",
"]",
")",
"lon2",
",",
"lat2",
"=",
"np",
".",
"radians",
"(",
"[",
"lon2",
",",
"la... | Angular separation (deg) between two sky coordinates.
Borrowed from astropy (www.astropy.org)
Notes
-----
The angular separation is calculated using the Vincenty formula [1],
which is slighly more complex and computationally expensive than
some alternatives, but is stable at at all distances, in... | [
"Angular",
"separation",
"(",
"deg",
")",
"between",
"two",
"sky",
"coordinates",
".",
"Borrowed",
"from",
"astropy",
"(",
"www",
".",
"astropy",
".",
"org",
")",
"Notes",
"-----",
"The",
"angular",
"separation",
"is",
"calculated",
"using",
"the",
"Vincenty... | python | train | 33.111111 |
zhmcclient/python-zhmcclient | zhmcclient_mock/_hmc.py | https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L2429-L2450 | def remove(self, oid):
"""
Remove a faked Virtual Function resource.
This method also updates the 'virtual-function-uris' property in the
parent Partition resource, by removing the URI for the faked Virtual
Function resource.
Parameters:
oid (string):
... | [
"def",
"remove",
"(",
"self",
",",
"oid",
")",
":",
"virtual_function",
"=",
"self",
".",
"lookup_by_oid",
"(",
"oid",
")",
"partition",
"=",
"self",
".",
"parent",
"devno",
"=",
"virtual_function",
".",
"properties",
".",
"get",
"(",
"'device-number'",
",... | Remove a faked Virtual Function resource.
This method also updates the 'virtual-function-uris' property in the
parent Partition resource, by removing the URI for the faked Virtual
Function resource.
Parameters:
oid (string):
The object ID of the faked Virtual Fun... | [
"Remove",
"a",
"faked",
"Virtual",
"Function",
"resource",
"."
] | python | train | 37.590909 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py#L168-L179 | def draw(self, img, pixmapper, bounds):
'''draw a polygon on the image'''
if self.hidden:
return
self._pix_points = []
for i in range(len(self.points)-1):
if len(self.points[i]) > 2:
colour = self.points[i][2]
else:
colo... | [
"def",
"draw",
"(",
"self",
",",
"img",
",",
"pixmapper",
",",
"bounds",
")",
":",
"if",
"self",
".",
"hidden",
":",
"return",
"self",
".",
"_pix_points",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"points",
")",
"-",... | draw a polygon on the image | [
"draw",
"a",
"polygon",
"on",
"the",
"image"
] | python | train | 37.75 |
paramiko/paramiko | paramiko/pkey.py | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/pkey.py#L491-L515 | def from_string(cls, string):
"""
Create a public blob from a ``-cert.pub``-style string.
"""
fields = string.split(None, 2)
if len(fields) < 2:
msg = "Not enough fields for public blob: {}"
raise ValueError(msg.format(fields))
key_type = fields[0]... | [
"def",
"from_string",
"(",
"cls",
",",
"string",
")",
":",
"fields",
"=",
"string",
".",
"split",
"(",
"None",
",",
"2",
")",
"if",
"len",
"(",
"fields",
")",
"<",
"2",
":",
"msg",
"=",
"\"Not enough fields for public blob: {}\"",
"raise",
"ValueError",
... | Create a public blob from a ``-cert.pub``-style string. | [
"Create",
"a",
"public",
"blob",
"from",
"a",
"-",
"cert",
".",
"pub",
"-",
"style",
"string",
"."
] | python | train | 37 |
prompt-toolkit/pyvim | pyvim/window_arrangement.py | https://github.com/prompt-toolkit/pyvim/blob/5928b53b9d700863c1a06d2181a034a955f94594/pyvim/window_arrangement.py#L166-L191 | def close_active_window(self):
"""
Close active window.
"""
active_split = self._get_active_split()
# First remove the active window from its split.
index = active_split.index(self.active_window)
del active_split[index]
# Move focus.
if len(activ... | [
"def",
"close_active_window",
"(",
"self",
")",
":",
"active_split",
"=",
"self",
".",
"_get_active_split",
"(",
")",
"# First remove the active window from its split.",
"index",
"=",
"active_split",
".",
"index",
"(",
"self",
".",
"active_window",
")",
"del",
"acti... | Close active window. | [
"Close",
"active",
"window",
"."
] | python | train | 38.846154 |
GNS3/gns3-server | gns3server/controller/gns3vm/__init__.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L56-L97 | def engine_list(self):
"""
:returns: Return list of engines supported by GNS3 for the GNS3VM
"""
download_url = "https://github.com/GNS3/gns3-gui/releases/download/v{version}/GNS3.VM.VMware.Workstation.{version}.zip".format(version=__version__)
vmware_informations = {
... | [
"def",
"engine_list",
"(",
"self",
")",
":",
"download_url",
"=",
"\"https://github.com/GNS3/gns3-gui/releases/download/v{version}/GNS3.VM.VMware.Workstation.{version}.zip\"",
".",
"format",
"(",
"version",
"=",
"__version__",
")",
"vmware_informations",
"=",
"{",
"\"engine_id\... | :returns: Return list of engines supported by GNS3 for the GNS3VM | [
":",
"returns",
":",
"Return",
"list",
"of",
"engines",
"supported",
"by",
"GNS3",
"for",
"the",
"GNS3VM"
] | python | train | 42.452381 |
shoebot/shoebot | lib/web/simplejson/encoder.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/simplejson/encoder.py#L369-L383 | def iterencode(self, o):
"""
Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
"""
if self.check_circular:
... | [
"def",
"iterencode",
"(",
"self",
",",
"o",
")",
":",
"if",
"self",
".",
"check_circular",
":",
"markers",
"=",
"{",
"}",
"else",
":",
"markers",
"=",
"None",
"return",
"self",
".",
"_iterencode",
"(",
"o",
",",
"markers",
")"
] | Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk) | [
"Encode",
"the",
"given",
"object",
"and",
"yield",
"each",
"string",
"representation",
"as",
"available",
".",
"For",
"example",
"::",
"for",
"chunk",
"in",
"JSONEncoder",
"()",
".",
"iterencode",
"(",
"bigobject",
")",
":",
"mysocket",
".",
"write",
"(",
... | python | valid | 27.4 |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L653-L678 | def add_entry(self, path_object):
"""Adds a child FakeFile to this directory.
Args:
path_object: FakeFile instance to add as a child of this directory.
Raises:
OSError: if the directory has no write permission (Posix only)
OSError: if the file or directory t... | [
"def",
"add_entry",
"(",
"self",
",",
"path_object",
")",
":",
"if",
"(",
"not",
"is_root",
"(",
")",
"and",
"not",
"self",
".",
"st_mode",
"&",
"PERM_WRITE",
"and",
"not",
"self",
".",
"filesystem",
".",
"is_windows_fs",
")",
":",
"exception",
"=",
"I... | Adds a child FakeFile to this directory.
Args:
path_object: FakeFile instance to add as a child of this directory.
Raises:
OSError: if the directory has no write permission (Posix only)
OSError: if the file or directory to be added already exists | [
"Adds",
"a",
"child",
"FakeFile",
"to",
"this",
"directory",
"."
] | python | train | 39.884615 |
edx/edx-val | edxval/models.py | https://github.com/edx/edx-val/blob/30df48061e77641edb5272895b7c7f7f25eb7aa7/edxval/models.py#L141-L149 | def by_youtube_id(cls, youtube_id):
"""
Look up video by youtube id
"""
qset = cls.objects.filter(
encoded_videos__profile__profile_name='youtube',
encoded_videos__url=youtube_id
).prefetch_related('encoded_videos', 'courses')
return qset | [
"def",
"by_youtube_id",
"(",
"cls",
",",
"youtube_id",
")",
":",
"qset",
"=",
"cls",
".",
"objects",
".",
"filter",
"(",
"encoded_videos__profile__profile_name",
"=",
"'youtube'",
",",
"encoded_videos__url",
"=",
"youtube_id",
")",
".",
"prefetch_related",
"(",
... | Look up video by youtube id | [
"Look",
"up",
"video",
"by",
"youtube",
"id"
] | python | train | 33.555556 |
rigetti/grove | grove/measurements/estimation.py | https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/measurements/estimation.py#L37-L55 | def get_rotation_program(pauli_term: PauliTerm) -> Program:
"""
Generate a rotation program so that the pauli term is diagonal.
:param pauli_term: The Pauli term used to generate diagonalizing one-qubit rotations.
:return: The rotation program.
"""
meas_basis_change = Program()
for index, g... | [
"def",
"get_rotation_program",
"(",
"pauli_term",
":",
"PauliTerm",
")",
"->",
"Program",
":",
"meas_basis_change",
"=",
"Program",
"(",
")",
"for",
"index",
",",
"gate",
"in",
"pauli_term",
":",
"if",
"gate",
"==",
"'X'",
":",
"meas_basis_change",
".",
"ins... | Generate a rotation program so that the pauli term is diagonal.
:param pauli_term: The Pauli term used to generate diagonalizing one-qubit rotations.
:return: The rotation program. | [
"Generate",
"a",
"rotation",
"program",
"so",
"that",
"the",
"pauli",
"term",
"is",
"diagonal",
"."
] | python | train | 31.736842 |
tensorflow/probability | tensorflow_probability/python/vi/csiszar_divergence.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/vi/csiszar_divergence.py#L664-L709 | def dual_csiszar_function(logu, csiszar_function, name=None):
"""Calculates the dual Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Csiszar-dual is defined as:
```none
f^*(u) = u f(1 / u)
```
where `f` is some other Csiszar-funct... | [
"def",
"dual_csiszar_function",
"(",
"logu",
",",
"csiszar_function",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"\"dual_csiszar_function\"",
",",
"[",
"logu",
"]",
")",
":",
"return",
... | Calculates the dual Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Csiszar-dual is defined as:
```none
f^*(u) = u f(1 / u)
```
where `f` is some other Csiszar-function.
For example, the dual of `kl_reverse` is `kl_forward`, i.e.... | [
"Calculates",
"the",
"dual",
"Csiszar",
"-",
"function",
"in",
"log",
"-",
"space",
"."
] | python | test | 25.23913 |
pantsbuild/pants | src/python/pants/util/dirutil.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L361-L379 | def safe_concurrent_creation(target_path):
"""A contextmanager that yields a temporary path and renames it to a final target path when the
contextmanager exits.
Useful when concurrent processes may attempt to create a file, and it doesn't matter who wins.
:param target_path: The final target path to rename th... | [
"def",
"safe_concurrent_creation",
"(",
"target_path",
")",
":",
"safe_mkdir_for",
"(",
"target_path",
")",
"tmp_path",
"=",
"'{}.tmp.{}'",
".",
"format",
"(",
"target_path",
",",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
")",
"try",
":",
"yield",
"tmp_pat... | A contextmanager that yields a temporary path and renames it to a final target path when the
contextmanager exits.
Useful when concurrent processes may attempt to create a file, and it doesn't matter who wins.
:param target_path: The final target path to rename the temporary path to.
:yields: A temporary path... | [
"A",
"contextmanager",
"that",
"yields",
"a",
"temporary",
"path",
"and",
"renames",
"it",
"to",
"a",
"final",
"target",
"path",
"when",
"the",
"contextmanager",
"exits",
"."
] | python | train | 35.631579 |
orbingol/NURBS-Python | geomdl/_utilities.py | https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_utilities.py#L57-L67 | def export(fn):
""" Export decorator
Please refer to the following SO article for details: https://stackoverflow.com/a/35710527
"""
mod = sys.modules[fn.__module__]
if hasattr(mod, '__all__'):
mod.__all__.append(fn.__name__)
else:
mod.__all__ = [fn.__name__]
return fn | [
"def",
"export",
"(",
"fn",
")",
":",
"mod",
"=",
"sys",
".",
"modules",
"[",
"fn",
".",
"__module__",
"]",
"if",
"hasattr",
"(",
"mod",
",",
"'__all__'",
")",
":",
"mod",
".",
"__all__",
".",
"append",
"(",
"fn",
".",
"__name__",
")",
"else",
":... | Export decorator
Please refer to the following SO article for details: https://stackoverflow.com/a/35710527 | [
"Export",
"decorator"
] | python | train | 27.545455 |
sibirrer/lenstronomy | lenstronomy/LensModel/Profiles/coreBurkert.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/LensModel/Profiles/coreBurkert.py#L39-L62 | def derivatives(self, x, y, Rs, theta_Rs, r_core, center_x=0, center_y=0):
"""
deflection angles
:param x: x coordinate
:param y: y coordinate
:param Rs: scale radius
:param rho0: central core density
:param r_core: core radius
:param center_x:
:pa... | [
"def",
"derivatives",
"(",
"self",
",",
"x",
",",
"y",
",",
"Rs",
",",
"theta_Rs",
",",
"r_core",
",",
"center_x",
"=",
"0",
",",
"center_y",
"=",
"0",
")",
":",
"rho0",
"=",
"self",
".",
"_alpha2rho0",
"(",
"theta_Rs",
"=",
"theta_Rs",
",",
"Rs",
... | deflection angles
:param x: x coordinate
:param y: y coordinate
:param Rs: scale radius
:param rho0: central core density
:param r_core: core radius
:param center_x:
:param center_y:
:return: | [
"deflection",
"angles",
":",
"param",
"x",
":",
"x",
"coordinate",
":",
"param",
"y",
":",
"y",
"coordinate",
":",
"param",
"Rs",
":",
"scale",
"radius",
":",
"param",
"rho0",
":",
"central",
"core",
"density",
":",
"param",
"r_core",
":",
"core",
"rad... | python | train | 27 |
nfcpy/nfcpy | src/nfc/clf/__init__.py | https://github.com/nfcpy/nfcpy/blob/6649146d1afdd5e82b2b6b1ea00aa58d50785117/src/nfc/clf/__init__.py#L660-L871 | def sense(self, *targets, **options):
"""Discover a contactless card or listening device.
.. note:: The :meth:`sense` method is intended for experts
with a good understanding of the commands and
responses exchanged during target activation (the
noti... | [
"def",
"sense",
"(",
"self",
",",
"*",
"targets",
",",
"*",
"*",
"options",
")",
":",
"def",
"sense_tta",
"(",
"target",
")",
":",
"if",
"target",
".",
"sel_req",
"and",
"len",
"(",
"target",
".",
"sel_req",
")",
"not",
"in",
"(",
"4",
",",
"7",
... | Discover a contactless card or listening device.
.. note:: The :meth:`sense` method is intended for experts
with a good understanding of the commands and
responses exchanged during target activation (the
notion used for commands and responses follows the
... | [
"Discover",
"a",
"contactless",
"card",
"or",
"listening",
"device",
"."
] | python | train | 47.188679 |
decryptus/sonicprobe | sonicprobe/helpers.py | https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/helpers.py#L357-L423 | def linesubst(line, variables):
"""
In a string, substitute '{{varname}}' occurrences with the value of
variables['varname'], '\\' being an escaping char...
If at first you don't understand this function, draw its finite state
machine and everything will become crystal clear :)
"""
# trivial... | [
"def",
"linesubst",
"(",
"line",
",",
"variables",
")",
":",
"# trivial no substitution early detection:",
"if",
"'{{'",
"not",
"in",
"line",
"and",
"'\\\\'",
"not",
"in",
"line",
":",
"return",
"line",
"st",
"=",
"NORM",
"out",
"=",
"\"\"",
"curvar",
"=",
... | In a string, substitute '{{varname}}' occurrences with the value of
variables['varname'], '\\' being an escaping char...
If at first you don't understand this function, draw its finite state
machine and everything will become crystal clear :) | [
"In",
"a",
"string",
"substitute",
"{{",
"varname",
"}}",
"occurrences",
"with",
"the",
"value",
"of",
"variables",
"[",
"varname",
"]",
"\\\\",
"being",
"an",
"escaping",
"char",
"...",
"If",
"at",
"first",
"you",
"don",
"t",
"understand",
"this",
"functi... | python | train | 29.820896 |
todbot/blink1-python | blink1/blink1.py | https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L303-L314 | def blink1(switch_off=True, gamma=None, white_point=None):
"""Context manager which automatically shuts down the Blink(1)
after use.
:param switch_off: turn blink(1) off when existing context
:param gamma: set gamma curve (as tuple)
:param white_point: set white point (as tuple)
"""
b1 = Bli... | [
"def",
"blink1",
"(",
"switch_off",
"=",
"True",
",",
"gamma",
"=",
"None",
",",
"white_point",
"=",
"None",
")",
":",
"b1",
"=",
"Blink1",
"(",
"gamma",
"=",
"gamma",
",",
"white_point",
"=",
"white_point",
")",
"yield",
"b1",
"if",
"switch_off",
":",... | Context manager which automatically shuts down the Blink(1)
after use.
:param switch_off: turn blink(1) off when existing context
:param gamma: set gamma curve (as tuple)
:param white_point: set white point (as tuple) | [
"Context",
"manager",
"which",
"automatically",
"shuts",
"down",
"the",
"Blink",
"(",
"1",
")",
"after",
"use",
".",
":",
"param",
"switch_off",
":",
"turn",
"blink",
"(",
"1",
")",
"off",
"when",
"existing",
"context",
":",
"param",
"gamma",
":",
"set",... | python | train | 34.5 |
StackStorm/pybind | pybind/slxos/v17s_1_02/mpls_state/rsvp/sessions/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/mpls_state/rsvp/sessions/__init__.py#L227-L255 | def _set_session_role(self, v, load=False):
"""
Setter method for session_role, mapped from YANG variable /mpls_state/rsvp/sessions/session_role (session-role)
If this variable is read-only (config: false) in the
source YANG file, then _set_session_role is considered as a private
method. Backends lo... | [
"def",
"_set_session_role",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"parent",
"=",
"getattr",
"(",
"self",
",",
"\"_parent\"",
",",
"None",
")",
"if",
"parent",
"is",
"not",
"None",
"and",
"load",
"is",
"False",
":",
"raise",
"Att... | Setter method for session_role, mapped from YANG variable /mpls_state/rsvp/sessions/session_role (session-role)
If this variable is read-only (config: false) in the
source YANG file, then _set_session_role is considered as a private
method. Backends looking to populate this variable should
do so via cal... | [
"Setter",
"method",
"for",
"session_role",
"mapped",
"from",
"YANG",
"variable",
"/",
"mpls_state",
"/",
"rsvp",
"/",
"sessions",
"/",
"session_role",
"(",
"session",
"-",
"role",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":"... | python | train | 83.37931 |
taskcluster/taskcluster-client.py | taskcluster/aio/queue.py | https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/aio/queue.py#L59-L70 | async def status(self, *args, **kwargs):
"""
Get task status
Get task status structure from `taskId`
This method gives output: ``v1/task-status-response.json#``
This method is ``stable``
"""
return await self._makeApiCall(self.funcinfo["status"], *args, **kwar... | [
"async",
"def",
"status",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"status\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Get task status
Get task status structure from `taskId`
This method gives output: ``v1/task-status-response.json#``
This method is ``stable`` | [
"Get",
"task",
"status"
] | python | train | 26 |
intake/intake | intake/source/cache.py | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/cache.py#L540-L557 | def make_caches(driver, specs, catdir=None, cache_dir=None, storage_options={}):
"""
Creates Cache objects from the cache_specs provided in the catalog yaml file
Parameters
----------
driver: str
Name of the plugin that can load catalog entry
specs: list
Specification for cachi... | [
"def",
"make_caches",
"(",
"driver",
",",
"specs",
",",
"catdir",
"=",
"None",
",",
"cache_dir",
"=",
"None",
",",
"storage_options",
"=",
"{",
"}",
")",
":",
"if",
"specs",
"is",
"None",
":",
"return",
"[",
"]",
"return",
"[",
"registry",
".",
"get"... | Creates Cache objects from the cache_specs provided in the catalog yaml file
Parameters
----------
driver: str
Name of the plugin that can load catalog entry
specs: list
Specification for caching the data source. | [
"Creates",
"Cache",
"objects",
"from",
"the",
"cache_specs",
"provided",
"in",
"the",
"catalog",
"yaml",
"file"
] | python | train | 30.388889 |
quantumlib/Cirq | cirq/ops/named_qubit.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/named_qubit.py#L40-L56 | def range(*args, prefix: str):
"""Returns a range of NamedQubits.
The range returned starts with the prefix, and followed by a qubit for
each number in the range, e.g.:
NamedQubit.range(3, prefix="a") -> ["a1", "a2", "a3]
NamedQubit.range(2, 4, prefix="a") -> ["a2", "a3]
... | [
"def",
"range",
"(",
"*",
"args",
",",
"prefix",
":",
"str",
")",
":",
"return",
"[",
"NamedQubit",
"(",
"prefix",
"+",
"str",
"(",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"*",
"args",
")",
"]"
] | Returns a range of NamedQubits.
The range returned starts with the prefix, and followed by a qubit for
each number in the range, e.g.:
NamedQubit.range(3, prefix="a") -> ["a1", "a2", "a3]
NamedQubit.range(2, 4, prefix="a") -> ["a2", "a3]
Args:
*args: Args to be pas... | [
"Returns",
"a",
"range",
"of",
"NamedQubits",
"."
] | python | train | 33.882353 |
wal-e/wal-e | wal_e/piper.py | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/piper.py#L125-L140 | def pipe_wait(popens):
"""
Given an array of Popen objects returned by the
pipe method, wait for all processes to terminate
and return the array with their return values.
Taken from http://www.enricozini.org/2009/debian/python-pipes/
"""
# Avoid mutating the passed copy
popens = copy.c... | [
"def",
"pipe_wait",
"(",
"popens",
")",
":",
"# Avoid mutating the passed copy",
"popens",
"=",
"copy",
".",
"copy",
"(",
"popens",
")",
"results",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"popens",
")",
"while",
"popens",
":",
"last",
"=",
"popens",
".",
... | Given an array of Popen objects returned by the
pipe method, wait for all processes to terminate
and return the array with their return values.
Taken from http://www.enricozini.org/2009/debian/python-pipes/ | [
"Given",
"an",
"array",
"of",
"Popen",
"objects",
"returned",
"by",
"the",
"pipe",
"method",
"wait",
"for",
"all",
"processes",
"to",
"terminate",
"and",
"return",
"the",
"array",
"with",
"their",
"return",
"values",
"."
] | python | train | 28.625 |
libyal/dtfabric | dtfabric/reader.py | https://github.com/libyal/dtfabric/blob/0d2b5719fa257f6e5c661a406737ebcf8c8db266/dtfabric/reader.py#L219-L279 | def _ReadDataTypeDefinitionWithMembers(
self, definitions_registry, definition_values,
data_type_definition_class, definition_name, supports_conditions=False):
"""Reads a data type definition with members.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
... | [
"def",
"_ReadDataTypeDefinitionWithMembers",
"(",
"self",
",",
"definitions_registry",
",",
"definition_values",
",",
"data_type_definition_class",
",",
"definition_name",
",",
"supports_conditions",
"=",
"False",
")",
":",
"members",
"=",
"definition_values",
".",
"get",... | Reads a data type definition with members.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definition values.
data_type_definition_class (str): data type definition class.
definition_name (str): name ... | [
"Reads",
"a",
"data",
"type",
"definition",
"with",
"members",
"."
] | python | train | 42.377049 |
saltstack/salt | salt/modules/drac.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drac.py#L252-L312 | def create_user(username, password, permissions, users=None):
'''
Create user accounts
CLI Example:
.. code-block:: bash
salt dell drac.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell drac.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* logi... | [
"def",
"create_user",
"(",
"username",
",",
"password",
",",
"permissions",
",",
"users",
"=",
"None",
")",
":",
"_uids",
"=",
"set",
"(",
")",
"if",
"users",
"is",
"None",
":",
"users",
"=",
"list_users",
"(",
")",
"if",
"username",
"in",
"users",
"... | Create user accounts
CLI Example:
.. code-block:: bash
salt dell drac.create_user [USERNAME] [PASSWORD] [PRIVILEGES]
salt dell drac.create_user diana secret login,test_alerts,clear_logs
DRAC Privileges
* login : Login to iDRAC
* drac : Con... | [
"Create",
"user",
"accounts"
] | python | train | 30.918033 |
ambitioninc/newrelic-api | newrelic_api/dashboards.py | https://github.com/ambitioninc/newrelic-api/blob/07b4430aa6ae61e4704e2928a6e7a24c76f0f424/newrelic_api/dashboards.py#L8-L66 | def list(self, filter_title=None, filter_ids=None, page=None):
"""
:type filter_title: str
:param filter_title: Filter by dashboard title
:type filter_ids: list of ints
:param filter_ids: Filter by dashboard ids
:type page: int
:param page: Pagination index
... | [
"def",
"list",
"(",
"self",
",",
"filter_title",
"=",
"None",
",",
"filter_ids",
"=",
"None",
",",
"page",
"=",
"None",
")",
":",
"filters",
"=",
"[",
"'filter[title]={0}'",
".",
"format",
"(",
"filter_title",
")",
"if",
"filter_title",
"else",
"None",
"... | :type filter_title: str
:param filter_title: Filter by dashboard title
:type filter_ids: list of ints
:param filter_ids: Filter by dashboard ids
:type page: int
:param page: Pagination index
:rtype: dict
:return: The JSON response of the API, with an additional... | [
":",
"type",
"filter_title",
":",
"str",
":",
"param",
"filter_title",
":",
"Filter",
"by",
"dashboard",
"title"
] | python | train | 35.474576 |
adafruit/Adafruit_Python_BluefruitLE | Adafruit_BluefruitLE/corebluetooth/device.py | https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/device.py#L101-L109 | def _characteristics_discovered(self, service):
"""Called when GATT characteristics have been discovered."""
# Characteristics for the specified service were discovered. Update
# set of discovered services and signal when all have been discovered.
self._discovered_services.add(service)
... | [
"def",
"_characteristics_discovered",
"(",
"self",
",",
"service",
")",
":",
"# Characteristics for the specified service were discovered. Update",
"# set of discovered services and signal when all have been discovered.",
"self",
".",
"_discovered_services",
".",
"add",
"(",
"servic... | Called when GATT characteristics have been discovered. | [
"Called",
"when",
"GATT",
"characteristics",
"have",
"been",
"discovered",
"."
] | python | valid | 60.777778 |
python-xlib/python-xlib | Xlib/rdb.py | https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/rdb.py#L320-L330 | def update(self, db):
"""update(db)
Update this database with all resources entries in the resource
database DB.
"""
self.lock.acquire()
update_db(self.db, db.db)
self.lock.release() | [
"def",
"update",
"(",
"self",
",",
"db",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"update_db",
"(",
"self",
".",
"db",
",",
"db",
".",
"db",
")",
"self",
".",
"lock",
".",
"release",
"(",
")"
] | update(db)
Update this database with all resources entries in the resource
database DB. | [
"update",
"(",
"db",
")"
] | python | train | 21 |
nameko/nameko | nameko/exceptions.py | https://github.com/nameko/nameko/blob/88d7e5211de4fcc1c34cd7f84d7c77f0619c5f5d/nameko/exceptions.py#L85-L94 | def serialize(exc):
""" Serialize `self.exc` into a data dictionary representing it.
"""
return {
'exc_type': type(exc).__name__,
'exc_path': get_module_path(type(exc)),
'exc_args': list(map(safe_for_serialization, exc.args)),
'value': safe_for_serialization(exc),
} | [
"def",
"serialize",
"(",
"exc",
")",
":",
"return",
"{",
"'exc_type'",
":",
"type",
"(",
"exc",
")",
".",
"__name__",
",",
"'exc_path'",
":",
"get_module_path",
"(",
"type",
"(",
"exc",
")",
")",
",",
"'exc_args'",
":",
"list",
"(",
"map",
"(",
"safe... | Serialize `self.exc` into a data dictionary representing it. | [
"Serialize",
"self",
".",
"exc",
"into",
"a",
"data",
"dictionary",
"representing",
"it",
"."
] | python | train | 30.6 |
tensorforce/tensorforce | tensorforce/models/memory_model.py | https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/memory_model.py#L339-L358 | def tf_loss_per_instance(self, states, internals, actions, terminal, reward,
next_states, next_internals, update, reference=None):
"""
Creates the TensorFlow operations for calculating the loss per batch instance.
Args:
states: Dict of state tensors.
... | [
"def",
"tf_loss_per_instance",
"(",
"self",
",",
"states",
",",
"internals",
",",
"actions",
",",
"terminal",
",",
"reward",
",",
"next_states",
",",
"next_internals",
",",
"update",
",",
"reference",
"=",
"None",
")",
":",
"raise",
"NotImplementedError"
] | Creates the TensorFlow operations for calculating the loss per batch instance.
Args:
states: Dict of state tensors.
internals: Dict of prior internal state tensors.
actions: Dict of action tensors.
terminal: Terminal boolean tensor.
reward: Reward ten... | [
"Creates",
"the",
"TensorFlow",
"operations",
"for",
"calculating",
"the",
"loss",
"per",
"batch",
"instance",
"."
] | python | valid | 44.45 |
AgeOfLearning/coeus-unity-python-framework | coeus_unity/commands.py | https://github.com/AgeOfLearning/coeus-unity-python-framework/blob/cf8ca6800ace1425d917ea2628dbd05ed959fdd7/coeus_unity/commands.py#L226-L247 | def assign_component_value(cli, transform_path, component_type, name, value):
"""
Requests status on whether a scene is loaded or not.
:param cli:
:param transform_path: The path of the transform where the component resides
:param component_type: The C# type name of the component GetComponent(type)
... | [
"def",
"assign_component_value",
"(",
"cli",
",",
"transform_path",
",",
"component_type",
",",
"name",
",",
"value",
")",
":",
"message_payload",
"=",
"{",
"\"transform_path\"",
":",
"transform_path",
",",
"\"component_type\"",
":",
"component_type",
",",
"\"name\"... | Requests status on whether a scene is loaded or not.
:param cli:
:param transform_path: The path of the transform where the component resides
:param component_type: The C# type name of the component GetComponent(type)
:param name: The field or property name.
:param value: The value to assign (String... | [
"Requests",
"status",
"on",
"whether",
"a",
"scene",
"is",
"loaded",
"or",
"not",
".",
":",
"param",
"cli",
":",
":",
"param",
"transform_path",
":",
"The",
"path",
"of",
"the",
"transform",
"where",
"the",
"component",
"resides",
":",
"param",
"component_... | python | train | 34.590909 |
saltstack/salt | salt/spm/pkgdb/sqlite3.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/pkgdb/sqlite3.py#L217-L228 | def unregister_file(path, pkg=None, conn=None): # pylint: disable=W0612
'''
Unregister a file from the package database
'''
close = False
if conn is None:
close = True
conn = init()
conn.execute('DELETE FROM files WHERE path=?', (path, ))
if close:
conn.close() | [
"def",
"unregister_file",
"(",
"path",
",",
"pkg",
"=",
"None",
",",
"conn",
"=",
"None",
")",
":",
"# pylint: disable=W0612",
"close",
"=",
"False",
"if",
"conn",
"is",
"None",
":",
"close",
"=",
"True",
"conn",
"=",
"init",
"(",
")",
"conn",
".",
"... | Unregister a file from the package database | [
"Unregister",
"a",
"file",
"from",
"the",
"package",
"database"
] | python | train | 25.333333 |
MLAB-project/pymlab | src/pymlab/sensors/__init__.py | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/__init__.py#L170-L177 | def initialize(self):
"""See :meth:`pymlab.sensors.Device.initialize` for more information.
Calls `initialize()` on all devices connected to the bus.
"""
Device.initialize(self)
for child in iter(self.children.values()):
child.initialize() | [
"def",
"initialize",
"(",
"self",
")",
":",
"Device",
".",
"initialize",
"(",
"self",
")",
"for",
"child",
"in",
"iter",
"(",
"self",
".",
"children",
".",
"values",
"(",
")",
")",
":",
"child",
".",
"initialize",
"(",
")"
] | See :meth:`pymlab.sensors.Device.initialize` for more information.
Calls `initialize()` on all devices connected to the bus. | [
"See",
":",
"meth",
":",
"pymlab",
".",
"sensors",
".",
"Device",
".",
"initialize",
"for",
"more",
"information",
"."
] | python | train | 35.625 |
frc1418/tbapy | tbapy/main.py | https://github.com/frc1418/tbapy/blob/3866d5a9971fe3dfaf1a1d83638bd6be6070f0c4/tbapy/main.py#L218-L225 | def team_profiles(self, team):
"""
Get team's social media profiles linked on their TBA page.
:param team: Team to get data on.
:return: List of Profile objects.
"""
return [Profile(raw) for raw in self._get('team/%s/social_media' % self.team_key(team))] | [
"def",
"team_profiles",
"(",
"self",
",",
"team",
")",
":",
"return",
"[",
"Profile",
"(",
"raw",
")",
"for",
"raw",
"in",
"self",
".",
"_get",
"(",
"'team/%s/social_media'",
"%",
"self",
".",
"team_key",
"(",
"team",
")",
")",
"]"
] | Get team's social media profiles linked on their TBA page.
:param team: Team to get data on.
:return: List of Profile objects. | [
"Get",
"team",
"s",
"social",
"media",
"profiles",
"linked",
"on",
"their",
"TBA",
"page",
"."
] | python | train | 37 |
dslackw/colored | colored/colored.py | https://github.com/dslackw/colored/blob/064172b36bd5e456c60581c7fbf77060ca7829ba/colored/colored.py#L389-L392 | def stylize(text, styles, reset=True):
"""conveniently styles your text as and resets ANSI codes at its end."""
terminator = attr("reset") if reset else ""
return "{}{}{}".format("".join(styles), text, terminator) | [
"def",
"stylize",
"(",
"text",
",",
"styles",
",",
"reset",
"=",
"True",
")",
":",
"terminator",
"=",
"attr",
"(",
"\"reset\"",
")",
"if",
"reset",
"else",
"\"\"",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"\"\"",
".",
"join",
"(",
"styles",
")",
"... | conveniently styles your text as and resets ANSI codes at its end. | [
"conveniently",
"styles",
"your",
"text",
"as",
"and",
"resets",
"ANSI",
"codes",
"at",
"its",
"end",
"."
] | python | train | 55.5 |
saltstack/salt | salt/modules/nagios_rpc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nagios_rpc.py#L52-L110 | def _status_query(query, hostname, enumerate=None, service=None):
'''
Send query along to Nagios.
'''
config = _config()
data = None
params = {
'hostname': hostname,
'query': query,
}
ret = {
'result': False
}
if enumerate:
params['formatoptions... | [
"def",
"_status_query",
"(",
"query",
",",
"hostname",
",",
"enumerate",
"=",
"None",
",",
"service",
"=",
"None",
")",
":",
"config",
"=",
"_config",
"(",
")",
"data",
"=",
"None",
"params",
"=",
"{",
"'hostname'",
":",
"hostname",
",",
"'query'",
":"... | Send query along to Nagios. | [
"Send",
"query",
"along",
"to",
"Nagios",
"."
] | python | train | 27.457627 |
vertical-knowledge/ripozo-sqlalchemy | ripozo_sqlalchemy/easy_resource.py | https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/easy_resource.py#L48-L66 | def _get_relationships(model):
"""
Gets the necessary relationships for the resource
by inspecting the sqlalchemy model for relationships.
:param DeclarativeMeta model: The SQLAlchemy ORM model.
:return: A tuple of Relationship/ListRelationship instances
corresponding to the relationships o... | [
"def",
"_get_relationships",
"(",
"model",
")",
":",
"relationships",
"=",
"[",
"]",
"for",
"name",
",",
"relationship",
"in",
"inspect",
"(",
"model",
")",
".",
"relationships",
".",
"items",
"(",
")",
":",
"class_",
"=",
"relationship",
".",
"mapper",
... | Gets the necessary relationships for the resource
by inspecting the sqlalchemy model for relationships.
:param DeclarativeMeta model: The SQLAlchemy ORM model.
:return: A tuple of Relationship/ListRelationship instances
corresponding to the relationships on the Model.
:rtype: tuple | [
"Gets",
"the",
"necessary",
"relationships",
"for",
"the",
"resource",
"by",
"inspecting",
"the",
"sqlalchemy",
"model",
"for",
"relationships",
"."
] | python | train | 37.789474 |
juju/python-libjuju | juju/user.py | https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/user.py#L70-L74 | async def revoke(self):
"""Removes all access rights for this user from the controller.
"""
await self.controller.revoke(self.username)
self._user_info.access = '' | [
"async",
"def",
"revoke",
"(",
"self",
")",
":",
"await",
"self",
".",
"controller",
".",
"revoke",
"(",
"self",
".",
"username",
")",
"self",
".",
"_user_info",
".",
"access",
"=",
"''"
] | Removes all access rights for this user from the controller. | [
"Removes",
"all",
"access",
"rights",
"for",
"this",
"user",
"from",
"the",
"controller",
"."
] | python | train | 38.2 |
nugget/python-insteonplm | insteonplm/address.py | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/address.py#L169-L174 | def x10_housecode(self):
"""Emit the X10 house code."""
housecode = None
if self.is_x10:
housecode = insteonplm.utils.byte_to_housecode(self.addr[1])
return housecode | [
"def",
"x10_housecode",
"(",
"self",
")",
":",
"housecode",
"=",
"None",
"if",
"self",
".",
"is_x10",
":",
"housecode",
"=",
"insteonplm",
".",
"utils",
".",
"byte_to_housecode",
"(",
"self",
".",
"addr",
"[",
"1",
"]",
")",
"return",
"housecode"
] | Emit the X10 house code. | [
"Emit",
"the",
"X10",
"house",
"code",
"."
] | python | train | 34.166667 |
Tanganelli/CoAPthon3 | coapthon/layers/resourcelayer.py | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/resourcelayer.py#L119-L208 | def add_resource(self, transaction, parent_resource, lp):
"""
Render a POST on a new resource.
:param transaction: the transaction
:param parent_resource: the parent of the resource
:param lp: the location_path attribute of the resource
:return: the response
"""
... | [
"def",
"add_resource",
"(",
"self",
",",
"transaction",
",",
"parent_resource",
",",
"lp",
")",
":",
"method",
"=",
"getattr",
"(",
"parent_resource",
",",
"\"render_POST\"",
",",
"None",
")",
"try",
":",
"resource",
"=",
"method",
"(",
"request",
"=",
"tr... | Render a POST on a new resource.
:param transaction: the transaction
:param parent_resource: the parent of the resource
:param lp: the location_path attribute of the resource
:return: the response | [
"Render",
"a",
"POST",
"on",
"a",
"new",
"resource",
"."
] | python | train | 45.033333 |
happyleavesaoc/aoc-mgz | mgz/util.py | https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/util.py#L94-L104 | def _parse(self, stream, context, path):
"""Parse stream to find a given byte string."""
start = stream.tell()
read_bytes = ""
if self.max_length:
read_bytes = stream.read(self.max_length)
else:
read_bytes = stream.read()
skip = read_bytes.find(sel... | [
"def",
"_parse",
"(",
"self",
",",
"stream",
",",
"context",
",",
"path",
")",
":",
"start",
"=",
"stream",
".",
"tell",
"(",
")",
"read_bytes",
"=",
"\"\"",
"if",
"self",
".",
"max_length",
":",
"read_bytes",
"=",
"stream",
".",
"read",
"(",
"self",... | Parse stream to find a given byte string. | [
"Parse",
"stream",
"to",
"find",
"a",
"given",
"byte",
"string",
"."
] | python | train | 35.272727 |
paulovn/sparql-kernel | sparqlkernel/utils.py | https://github.com/paulovn/sparql-kernel/blob/1d2d155ff5da72070cb2a98fae33ea8113fac782/sparqlkernel/utils.py#L28-L47 | def escape( x, lb=False ):
"""
Ensure a string does not contain HTML-reserved characters (including
double quotes)
Optionally also insert a linebreak if the string is too long
"""
# Insert a linebreak? Roughly around the middle of the string,
if lb:
l = len(x)
if l >= 10:
... | [
"def",
"escape",
"(",
"x",
",",
"lb",
"=",
"False",
")",
":",
"# Insert a linebreak? Roughly around the middle of the string,",
"if",
"lb",
":",
"l",
"=",
"len",
"(",
"x",
")",
"if",
"l",
">=",
"10",
":",
"l",
">>=",
"1",
"# middle of the string",
"s1",
"=... | Ensure a string does not contain HTML-reserved characters (including
double quotes)
Optionally also insert a linebreak if the string is too long | [
"Ensure",
"a",
"string",
"does",
"not",
"contain",
"HTML",
"-",
"reserved",
"characters",
"(",
"including",
"double",
"quotes",
")",
"Optionally",
"also",
"insert",
"a",
"linebreak",
"if",
"the",
"string",
"is",
"too",
"long"
] | python | train | 40.85 |
Kaggle/kaggle-api | kaggle/api/kaggle_api_extended.py | https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L584-L592 | def competition_list_files(self, competition):
""" list files for competition
Parameters
==========
competition: the name of the competition
"""
competition_list_files_result = self.process_response(
self.competitions_data_list_files_with_http_inf... | [
"def",
"competition_list_files",
"(",
"self",
",",
"competition",
")",
":",
"competition_list_files_result",
"=",
"self",
".",
"process_response",
"(",
"self",
".",
"competitions_data_list_files_with_http_info",
"(",
"id",
"=",
"competition",
")",
")",
"return",
"[",
... | list files for competition
Parameters
==========
competition: the name of the competition | [
"list",
"files",
"for",
"competition",
"Parameters",
"==========",
"competition",
":",
"the",
"name",
"of",
"the",
"competition"
] | python | train | 43.777778 |
pennersr/django-allauth | allauth/socialaccount/app_settings.py | https://github.com/pennersr/django-allauth/blob/f70cb3d622f992f15fe9b57098e0b328445b664e/allauth/socialaccount/app_settings.py#L40-L45 | def EMAIL_REQUIRED(self):
"""
The user is required to hand over an e-mail address when signing up
"""
from allauth.account import app_settings as account_settings
return self._setting("EMAIL_REQUIRED", account_settings.EMAIL_REQUIRED) | [
"def",
"EMAIL_REQUIRED",
"(",
"self",
")",
":",
"from",
"allauth",
".",
"account",
"import",
"app_settings",
"as",
"account_settings",
"return",
"self",
".",
"_setting",
"(",
"\"EMAIL_REQUIRED\"",
",",
"account_settings",
".",
"EMAIL_REQUIRED",
")"
] | The user is required to hand over an e-mail address when signing up | [
"The",
"user",
"is",
"required",
"to",
"hand",
"over",
"an",
"e",
"-",
"mail",
"address",
"when",
"signing",
"up"
] | python | train | 44.833333 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L4638-L4643 | def is_metaseries(self):
"""Page contains MDS MetaSeries metadata in ImageDescription tag."""
if self.index > 1 or self.software != 'MetaSeries':
return False
d = self.description
return d.startswith('<MetaData>') and d.endswith('</MetaData>') | [
"def",
"is_metaseries",
"(",
"self",
")",
":",
"if",
"self",
".",
"index",
">",
"1",
"or",
"self",
".",
"software",
"!=",
"'MetaSeries'",
":",
"return",
"False",
"d",
"=",
"self",
".",
"description",
"return",
"d",
".",
"startswith",
"(",
"'<MetaData>'",... | Page contains MDS MetaSeries metadata in ImageDescription tag. | [
"Page",
"contains",
"MDS",
"MetaSeries",
"metadata",
"in",
"ImageDescription",
"tag",
"."
] | python | train | 47 |
wndhydrnt/python-oauth2 | oauth2/grant.py | https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/grant.py#L41-L53 | def encode_scopes(scopes, use_quote=False):
"""
Creates a string out of a list of scopes.
:param scopes: A list of scopes
:param use_quote: Boolean flag indicating whether the string should be quoted
:return: Scopes as a string
"""
scopes_as_string = Scope.separator.join(scopes)
if use... | [
"def",
"encode_scopes",
"(",
"scopes",
",",
"use_quote",
"=",
"False",
")",
":",
"scopes_as_string",
"=",
"Scope",
".",
"separator",
".",
"join",
"(",
"scopes",
")",
"if",
"use_quote",
":",
"return",
"quote",
"(",
"scopes_as_string",
")",
"return",
"scopes_a... | Creates a string out of a list of scopes.
:param scopes: A list of scopes
:param use_quote: Boolean flag indicating whether the string should be quoted
:return: Scopes as a string | [
"Creates",
"a",
"string",
"out",
"of",
"a",
"list",
"of",
"scopes",
"."
] | python | train | 29.384615 |
saltstack/salt | salt/modules/data.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/data.py#L41-L58 | def load():
'''
Return all of the data in the minion datastore
CLI Example:
.. code-block:: bash
salt '*' data.load
'''
serial = salt.payload.Serial(__opts__)
try:
datastore_path = os.path.join(__opts__['cachedir'], 'datastore')
with salt.utils.files.fopen(datasto... | [
"def",
"load",
"(",
")",
":",
"serial",
"=",
"salt",
".",
"payload",
".",
"Serial",
"(",
"__opts__",
")",
"try",
":",
"datastore_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'datastore'",
")",
"with",
"sa... | Return all of the data in the minion datastore
CLI Example:
.. code-block:: bash
salt '*' data.load | [
"Return",
"all",
"of",
"the",
"data",
"in",
"the",
"minion",
"datastore"
] | python | train | 23.833333 |
watson-developer-cloud/python-sdk | ibm_watson/assistant_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/assistant_v1.py#L7061-L7078 | def _from_dict(cls, _dict):
"""Initialize a ValueCollection object from a json dictionary."""
args = {}
if 'values' in _dict:
args['values'] = [
Value._from_dict(x) for x in (_dict.get('values'))
]
else:
raise ValueError(
... | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'values'",
"in",
"_dict",
":",
"args",
"[",
"'values'",
"]",
"=",
"[",
"Value",
".",
"_from_dict",
"(",
"x",
")",
"for",
"x",
"in",
"(",
"_dict",
".",
"get",
... | Initialize a ValueCollection object from a json dictionary. | [
"Initialize",
"a",
"ValueCollection",
"object",
"from",
"a",
"json",
"dictionary",
"."
] | python | train | 37.277778 |
lmjohns3/downhill | examples/mnist-sparse-factorization.py | https://github.com/lmjohns3/downhill/blob/42111ab03b5e6fa47b7bf7c7cb5caa402f10ce6d/examples/mnist-sparse-factorization.py#L11-L22 | def load_mnist():
'''Load the MNIST digits dataset.'''
mnist = skdata.mnist.dataset.MNIST()
mnist.meta # trigger download if needed.
def arr(n, dtype):
arr = mnist.arrays[n]
return arr.reshape((len(arr), -1)).astype(dtype)
train_images = arr('train_images', np.float32) / 128 - 1
... | [
"def",
"load_mnist",
"(",
")",
":",
"mnist",
"=",
"skdata",
".",
"mnist",
".",
"dataset",
".",
"MNIST",
"(",
")",
"mnist",
".",
"meta",
"# trigger download if needed.",
"def",
"arr",
"(",
"n",
",",
"dtype",
")",
":",
"arr",
"=",
"mnist",
".",
"arrays",... | Load the MNIST digits dataset. | [
"Load",
"the",
"MNIST",
"digits",
"dataset",
"."
] | python | train | 39.75 |
molmod/molmod | molmod/transformations.py | https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/transformations.py#L349-L361 | def about_axis(cls, center, angle, axis, invert=False):
"""Create transformation that represents a rotation about an axis
Arguments:
| ``center`` -- Point on the axis
| ``angle`` -- Rotation angle
| ``axis`` -- Rotation axis
| ``invert`` -- Whe... | [
"def",
"about_axis",
"(",
"cls",
",",
"center",
",",
"angle",
",",
"axis",
",",
"invert",
"=",
"False",
")",
":",
"return",
"Translation",
"(",
"center",
")",
"*",
"Rotation",
".",
"from_properties",
"(",
"angle",
",",
"axis",
",",
"invert",
")",
"*",
... | Create transformation that represents a rotation about an axis
Arguments:
| ``center`` -- Point on the axis
| ``angle`` -- Rotation angle
| ``axis`` -- Rotation axis
| ``invert`` -- When True, an inversion rotation is constructed
... | [
"Create",
"transformation",
"that",
"represents",
"a",
"rotation",
"about",
"an",
"axis"
] | python | train | 42.307692 |
jumpscale7/python-consistent-toml | contoml/file/file.py | https://github.com/jumpscale7/python-consistent-toml/blob/a0149c65313ccb8170aa99a0cc498e76231292b9/contoml/file/file.py#L169-L179 | def array(self, name):
"""
Returns the array of tables with the given name.
"""
if name in self._navigable:
if isinstance(self._navigable[name], (list, tuple)):
return self[name]
else:
raise NoArrayFoundError
else:
... | [
"def",
"array",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"_navigable",
":",
"if",
"isinstance",
"(",
"self",
".",
"_navigable",
"[",
"name",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"self",
"[",
"n... | Returns the array of tables with the given name. | [
"Returns",
"the",
"array",
"of",
"tables",
"with",
"the",
"given",
"name",
"."
] | python | train | 32.727273 |
mwouts/jupytext | jupytext/cell_metadata.py | https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/cell_metadata.py#L314-L330 | def try_eval_metadata(metadata, name):
"""Evaluate given metadata to a python object, if possible"""
value = metadata[name]
if not isinstance(value, (str, unicode)):
return
if (value.startswith('"') and value.endswith('"')) or (value.startswith("'") and value.endswith("'")):
if name in [... | [
"def",
"try_eval_metadata",
"(",
"metadata",
",",
"name",
")",
":",
"value",
"=",
"metadata",
"[",
"name",
"]",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"return",
"if",
"(",
"value",
".",
"startswith",
... | Evaluate given metadata to a python object, if possible | [
"Evaluate",
"given",
"metadata",
"to",
"a",
"python",
"object",
"if",
"possible"
] | python | train | 41.294118 |
jwkvam/bowtie | bowtie/_app.py | https://github.com/jwkvam/bowtie/blob/c494850671ac805bf186fbf2bdb07d2a34ae876d/bowtie/_app.py#L246-L250 | def min_percent(self, value: float) -> 'Size':
"""Set the minimum percentage of free space to use."""
raise_not_number(value)
self.minimum = '{}%'.format(value)
return self | [
"def",
"min_percent",
"(",
"self",
",",
"value",
":",
"float",
")",
"->",
"'Size'",
":",
"raise_not_number",
"(",
"value",
")",
"self",
".",
"minimum",
"=",
"'{}%'",
".",
"format",
"(",
"value",
")",
"return",
"self"
] | Set the minimum percentage of free space to use. | [
"Set",
"the",
"minimum",
"percentage",
"of",
"free",
"space",
"to",
"use",
"."
] | python | train | 40 |
inveniosoftware/invenio-oaiserver | invenio_oaiserver/ext.py | https://github.com/inveniosoftware/invenio-oaiserver/blob/eae765e32bd816ddc5612d4b281caf205518b512/invenio_oaiserver/ext.py#L33-L37 | def sets(self):
"""Get list of sets."""
if self.cache:
return self.cache.get(
self.app.config['OAISERVER_CACHE_KEY']) | [
"def",
"sets",
"(",
"self",
")",
":",
"if",
"self",
".",
"cache",
":",
"return",
"self",
".",
"cache",
".",
"get",
"(",
"self",
".",
"app",
".",
"config",
"[",
"'OAISERVER_CACHE_KEY'",
"]",
")"
] | Get list of sets. | [
"Get",
"list",
"of",
"sets",
"."
] | python | train | 31.4 |
zalando/patroni | patroni/postgresql.py | https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/postgresql.py#L663-L668 | def can_create_replica_without_replication_connection(self):
""" go through the replication methods to see if there are ones
that does not require a working replication connection.
"""
replica_methods = self._create_replica_methods
return any(self.replica_method_can_work_with... | [
"def",
"can_create_replica_without_replication_connection",
"(",
"self",
")",
":",
"replica_methods",
"=",
"self",
".",
"_create_replica_methods",
"return",
"any",
"(",
"self",
".",
"replica_method_can_work_without_replication_connection",
"(",
"method",
")",
"for",
"method... | go through the replication methods to see if there are ones
that does not require a working replication connection. | [
"go",
"through",
"the",
"replication",
"methods",
"to",
"see",
"if",
"there",
"are",
"ones",
"that",
"does",
"not",
"require",
"a",
"working",
"replication",
"connection",
"."
] | python | train | 63.333333 |
Yubico/python-pyhsm | pyhsm/util.py | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/util.py#L114-L122 | def validate_cmd_response_int(name, got, expected):
"""
Check that some value returned in the response to a command matches what
we put in the request (the command).
"""
if got != expected:
raise(pyhsm.exception.YHSM_Error("Bad %s in response (got %i, expected %i)" \
... | [
"def",
"validate_cmd_response_int",
"(",
"name",
",",
"got",
",",
"expected",
")",
":",
"if",
"got",
"!=",
"expected",
":",
"raise",
"(",
"pyhsm",
".",
"exception",
".",
"YHSM_Error",
"(",
"\"Bad %s in response (got %i, expected %i)\"",
"%",
"(",
"name",
",",
... | Check that some value returned in the response to a command matches what
we put in the request (the command). | [
"Check",
"that",
"some",
"value",
"returned",
"in",
"the",
"response",
"to",
"a",
"command",
"matches",
"what",
"we",
"put",
"in",
"the",
"request",
"(",
"the",
"command",
")",
"."
] | python | train | 41.444444 |
amaas-fintech/amaas-core-sdk-python | amaascore/market_data/quote.py | https://github.com/amaas-fintech/amaas-core-sdk-python/blob/347b71f8e776b2dde582b015e31b4802d91e8040/amaascore/market_data/quote.py#L26-L36 | def quote_datetime(self, value):
"""
Force the quote_datetime to always be a datetime
:param value:
:return:
"""
if value:
if isinstance(value, type_check):
self._quote_datetime = parse(value)
elif isinstance(value, datetime.datetim... | [
"def",
"quote_datetime",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
":",
"if",
"isinstance",
"(",
"value",
",",
"type_check",
")",
":",
"self",
".",
"_quote_datetime",
"=",
"parse",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"... | Force the quote_datetime to always be a datetime
:param value:
:return: | [
"Force",
"the",
"quote_datetime",
"to",
"always",
"be",
"a",
"datetime",
":",
"param",
"value",
":",
":",
"return",
":"
] | python | train | 32.545455 |
kderynski/blade-netconf-python-client | build/lib/bnclient/bnclient.py | https://github.com/kderynski/blade-netconf-python-client/blob/87396921a1c75f1093adf4bb7b13428ee368b2b7/build/lib/bnclient/bnclient.py#L109-L141 | def sendrpc(self, argv=[]):
self._aArgv += argv
_operation = ''
try:
self._cParams.parser(self._aArgv, self._dOptions)
# set rpc operation handler
while self._cParams.get('operation') not in rpc.operations.keys():
self._cParams.set('op... | [
"def",
"sendrpc",
"(",
"self",
",",
"argv",
"=",
"[",
"]",
")",
":",
"self",
".",
"_aArgv",
"+=",
"argv",
"_operation",
"=",
"''",
"try",
":",
"self",
".",
"_cParams",
".",
"parser",
"(",
"self",
".",
"_aArgv",
",",
"self",
".",
"_dOptions",
")",
... | end of function exchgmsg | [
"end",
"of",
"function",
"exchgmsg"
] | python | train | 41.848485 |
praekeltfoundation/molo | molo/core/models.py | https://github.com/praekeltfoundation/molo/blob/57702fda4fab261d67591415f7d46bc98fa38525/molo/core/models.py#L477-L561 | def create_page(self, content, class_, record_keeper=None, logger=None):
'''
Robust as possible
Attempts to create the page
If any of the functions used to attach content to the page
fail, keep going, keep a record of those errors in a context dict
return the page and th... | [
"def",
"create_page",
"(",
"self",
",",
"content",
",",
"class_",
",",
"record_keeper",
"=",
"None",
",",
"logger",
"=",
"None",
")",
":",
"fields",
",",
"nested_fields",
"=",
"separate_fields",
"(",
"content",
")",
"foreign_id",
"=",
"content",
".",
"pop"... | Robust as possible
Attempts to create the page
If any of the functions used to attach content to the page
fail, keep going, keep a record of those errors in a context dict
return the page and the context dict in a tuple | [
"Robust",
"as",
"possible"
] | python | train | 36.847059 |
tmr232/Sark | sark/structure.py | https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/structure.py#L143-L173 | def get_common_register(start, end):
"""Get the register most commonly used in accessing structs.
Access to is considered for every opcode that accesses memory
in an offset from a register::
mov eax, [ebx + 5]
For every access, the struct-referencing registers, in this case
`ebx`, are cou... | [
"def",
"get_common_register",
"(",
"start",
",",
"end",
")",
":",
"registers",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"line",
"in",
"lines",
"(",
"start",
",",
"end",
")",
":",
"insn",
"=",
"line",
".",
"insn",
"for",
"operand",
"in",
"insn",
".... | Get the register most commonly used in accessing structs.
Access to is considered for every opcode that accesses memory
in an offset from a register::
mov eax, [ebx + 5]
For every access, the struct-referencing registers, in this case
`ebx`, are counted. The most used one is returned.
Ar... | [
"Get",
"the",
"register",
"most",
"commonly",
"used",
"in",
"accessing",
"structs",
"."
] | python | train | 27 |
linkedin/naarad | lib/luminol/src/luminol/algorithms/correlator_algorithms/cross_correlator.py | https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/lib/luminol/src/luminol/algorithms/correlator_algorithms/cross_correlator.py#L94-L108 | def _find_first_bigger(self, timestamps, target, lower_bound, upper_bound):
"""
Find the first element in timestamps whose value is bigger than target.
param list values: list of timestamps(epoch number).
param target: target value.
param lower_bound: lower bound for binary search.
param upper_b... | [
"def",
"_find_first_bigger",
"(",
"self",
",",
"timestamps",
",",
"target",
",",
"lower_bound",
",",
"upper_bound",
")",
":",
"while",
"lower_bound",
"<",
"upper_bound",
":",
"pos",
"=",
"lower_bound",
"+",
"(",
"upper_bound",
"-",
"lower_bound",
")",
"/",
"... | Find the first element in timestamps whose value is bigger than target.
param list values: list of timestamps(epoch number).
param target: target value.
param lower_bound: lower bound for binary search.
param upper_bound: upper bound for binary search. | [
"Find",
"the",
"first",
"element",
"in",
"timestamps",
"whose",
"value",
"is",
"bigger",
"than",
"target",
".",
"param",
"list",
"values",
":",
"list",
"of",
"timestamps",
"(",
"epoch",
"number",
")",
".",
"param",
"target",
":",
"target",
"value",
".",
... | python | valid | 37.533333 |
lgpage/nbtutor | nbtutor/ipython/utils.py | https://github.com/lgpage/nbtutor/blob/07798a044cf6e1fd4eaac2afddeef3e13348dbcd/nbtutor/ipython/utils.py#L107-L125 | def format(obj, options):
"""Return a string representation of the Python object
Args:
obj: The Python object
options: Format options
"""
formatters = {
float_types: lambda x: '{:.{}g}'.format(x, options.digits),
}
for _types, fmtr in formatters.items():
if isins... | [
"def",
"format",
"(",
"obj",
",",
"options",
")",
":",
"formatters",
"=",
"{",
"float_types",
":",
"lambda",
"x",
":",
"'{:.{}g}'",
".",
"format",
"(",
"x",
",",
"options",
".",
"digits",
")",
",",
"}",
"for",
"_types",
",",
"fmtr",
"in",
"formatters... | Return a string representation of the Python object
Args:
obj: The Python object
options: Format options | [
"Return",
"a",
"string",
"representation",
"of",
"the",
"Python",
"object"
] | python | valid | 27.421053 |
chaoss/grimoirelab-sirmordred | sirmordred/eclipse_projects_lib.py | https://github.com/chaoss/grimoirelab-sirmordred/blob/d6ac94d28d707fae23170064d078f1edf937d13e/sirmordred/eclipse_projects_lib.py#L134-L149 | def compose_github(projects, data):
""" Compose projects.json for github
:param projects: projects.json
:param data: eclipse JSON
:return: projects.json with github
"""
for p in [project for project in data if len(data[project]['github_repos']) > 0]:
if 'github' not in projects[p]:
... | [
"def",
"compose_github",
"(",
"projects",
",",
"data",
")",
":",
"for",
"p",
"in",
"[",
"project",
"for",
"project",
"in",
"data",
"if",
"len",
"(",
"data",
"[",
"project",
"]",
"[",
"'github_repos'",
"]",
")",
">",
"0",
"]",
":",
"if",
"'github'",
... | Compose projects.json for github
:param projects: projects.json
:param data: eclipse JSON
:return: projects.json with github | [
"Compose",
"projects",
".",
"json",
"for",
"github"
] | python | valid | 32.5625 |
matthieugouel/gibica | gibica/lexer.py | https://github.com/matthieugouel/gibica/blob/65f937f7a6255078cc22eb7691a2897466032909/gibica/lexer.py#L79-L202 | def next_token(self):
"""Lexical analyser of the raw input."""
while self.char is not None:
if self.char.isspace():
# The current character is a whitespace
self.whitespace()
continue
elif self.char == '#':
# The cu... | [
"def",
"next_token",
"(",
"self",
")",
":",
"while",
"self",
".",
"char",
"is",
"not",
"None",
":",
"if",
"self",
".",
"char",
".",
"isspace",
"(",
")",
":",
"# The current character is a whitespace",
"self",
".",
"whitespace",
"(",
")",
"continue",
"elif"... | Lexical analyser of the raw input. | [
"Lexical",
"analyser",
"of",
"the",
"raw",
"input",
"."
] | python | train | 32.080645 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.