repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
basho/riak-python-client | riak/mapreduce.py | https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/mapreduce.py#L121-L144 | def add_bucket(self, bucket, bucket_type=None):
"""
Adds all keys in a bucket to the inputs.
:param bucket: the bucket
:type bucket: string
:param bucket_type: Optional name of a bucket type
:type bucket_type: string, None
:rtype: :class:`RiakMapReduce`
"... | [
"def",
"add_bucket",
"(",
"self",
",",
"bucket",
",",
"bucket_type",
"=",
"None",
")",
":",
"if",
"not",
"riak",
".",
"disable_list_exceptions",
":",
"raise",
"riak",
".",
"ListError",
"(",
")",
"self",
".",
"_input_mode",
"=",
"'bucket'",
"if",
"isinstanc... | Adds all keys in a bucket to the inputs.
:param bucket: the bucket
:type bucket: string
:param bucket_type: Optional name of a bucket type
:type bucket_type: string, None
:rtype: :class:`RiakMapReduce` | [
"Adds",
"all",
"keys",
"in",
"a",
"bucket",
"to",
"the",
"inputs",
"."
] | python | train |
arne-cl/discoursegraphs | src/discoursegraphs/readwrite/exportxml.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/exportxml.py#L423-L457 | def add_node_element(self, node):
"""Add a (syntax category) <node> to the document graph.
Parameters
----------
node : etree.Element
etree representation of a <node> element
A <node> describes an element of a syntax tree.
The root <node> element does... | [
"def",
"add_node_element",
"(",
"self",
",",
"node",
")",
":",
"node_id",
"=",
"self",
".",
"get_element_id",
"(",
"node",
")",
"if",
"'parent'",
"in",
"node",
".",
"attrib",
":",
"parent_id",
"=",
"self",
".",
"get_parent_id",
"(",
"node",
")",
"else",
... | Add a (syntax category) <node> to the document graph.
Parameters
----------
node : etree.Element
etree representation of a <node> element
A <node> describes an element of a syntax tree.
The root <node> element does not have a parent attribute,
whi... | [
"Add",
"a",
"(",
"syntax",
"category",
")",
"<node",
">",
"to",
"the",
"document",
"graph",
"."
] | python | train |
stevearc/dql | dql/engine.py | https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/engine.py#L344-L357 | def _parse_throttle(self, tablename, throttle):
""" Parse a 'throttle' statement and return a RateLimit """
amount = []
desc = self.describe(tablename)
throughputs = [desc.read_throughput, desc.write_throughput]
for value, throughput in zip(throttle[1:], throughputs):
... | [
"def",
"_parse_throttle",
"(",
"self",
",",
"tablename",
",",
"throttle",
")",
":",
"amount",
"=",
"[",
"]",
"desc",
"=",
"self",
".",
"describe",
"(",
"tablename",
")",
"throughputs",
"=",
"[",
"desc",
".",
"read_throughput",
",",
"desc",
".",
"write_th... | Parse a 'throttle' statement and return a RateLimit | [
"Parse",
"a",
"throttle",
"statement",
"and",
"return",
"a",
"RateLimit"
] | python | train |
boriel/zxbasic | arch/zx48k/backend/__16bit.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L279-L333 | def _divu16(ins):
''' Divides 2 16bit unsigned integers. The result is pushed onto the stack.
Optimizations:
* If 2nd op is 1 then
do nothing
* If 2nd op is 2 then
Shift Right Logical
'''
op1, op2 = tuple(ins.quad[2:])
if is_int(op1) and int(op1) == 0: # 0 / A = 0
... | [
"def",
"_divu16",
"(",
"ins",
")",
":",
"op1",
",",
"op2",
"=",
"tuple",
"(",
"ins",
".",
"quad",
"[",
"2",
":",
"]",
")",
"if",
"is_int",
"(",
"op1",
")",
"and",
"int",
"(",
"op1",
")",
"==",
"0",
":",
"# 0 / A = 0",
"if",
"op2",
"[",
"0",
... | Divides 2 16bit unsigned integers. The result is pushed onto the stack.
Optimizations:
* If 2nd op is 1 then
do nothing
* If 2nd op is 2 then
Shift Right Logical | [
"Divides",
"2",
"16bit",
"unsigned",
"integers",
".",
"The",
"result",
"is",
"pushed",
"onto",
"the",
"stack",
"."
] | python | train |
RedFantom/ttkwidgets | ttkwidgets/table.py | https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/table.py#L472-L481 | def _config_drag_cols(self, drag_cols):
"""Configure a new drag_cols state"""
self._drag_cols = drag_cols
# remove/display drag icon
if self._drag_cols:
self._im_drag.paste(self._im_draggable)
else:
self._im_drag.paste(self._im_not_draggable)
self.... | [
"def",
"_config_drag_cols",
"(",
"self",
",",
"drag_cols",
")",
":",
"self",
".",
"_drag_cols",
"=",
"drag_cols",
"# remove/display drag icon",
"if",
"self",
".",
"_drag_cols",
":",
"self",
".",
"_im_drag",
".",
"paste",
"(",
"self",
".",
"_im_draggable",
")",... | Configure a new drag_cols state | [
"Configure",
"a",
"new",
"drag_cols",
"state"
] | python | train |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1322-L1335 | def add_file_opt(self,opt,filename,file_is_output_file=False):
"""
Add a variable (macro) option for this node. If the option
specified does not exist in the CondorJob, it is added so the submit
file will be correct when written. The value of the option is also
added to the list of input files for t... | [
"def",
"add_file_opt",
"(",
"self",
",",
"opt",
",",
"filename",
",",
"file_is_output_file",
"=",
"False",
")",
":",
"self",
".",
"add_var_opt",
"(",
"opt",
",",
"filename",
")",
"if",
"file_is_output_file",
":",
"self",
".",
"add_output_file",
"(",
"filenam... | Add a variable (macro) option for this node. If the option
specified does not exist in the CondorJob, it is added so the submit
file will be correct when written. The value of the option is also
added to the list of input files for the DAX.
@param opt: option name.
@param value: value of the option ... | [
"Add",
"a",
"variable",
"(",
"macro",
")",
"option",
"for",
"this",
"node",
".",
"If",
"the",
"option",
"specified",
"does",
"not",
"exist",
"in",
"the",
"CondorJob",
"it",
"is",
"added",
"so",
"the",
"submit",
"file",
"will",
"be",
"correct",
"when",
... | python | train |
ZELLMECHANIK-DRESDEN/dclab | dclab/parse_funcs.py | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/parse_funcs.py#L8-L22 | def fbool(value):
"""boolean"""
if isinstance(value, str_types):
value = value.lower()
if value == "false":
value = False
elif value == "true":
value = True
elif value:
value = bool(float(value))
else:
raise ValueError("empt... | [
"def",
"fbool",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str_types",
")",
":",
"value",
"=",
"value",
".",
"lower",
"(",
")",
"if",
"value",
"==",
"\"false\"",
":",
"value",
"=",
"False",
"elif",
"value",
"==",
"\"true\"",
":",... | boolean | [
"boolean"
] | python | train |
fredRos/pypmc | pypmc/tools/_doc.py | https://github.com/fredRos/pypmc/blob/9138b67c976f0d58edd080353d16769a47794d09/pypmc/tools/_doc.py#L5-L39 | def _inherit_docstring(from_class):
'''Private wrapper function to inherit docstrings from Base class
Usage example:
class mood(object):
'describes typical reactions of a person in a specific mood'
def how_are_you(self):
'returns a typical answer to How are you? being i... | [
"def",
"_inherit_docstring",
"(",
"from_class",
")",
":",
"def",
"wrapper",
"(",
"method",
")",
":",
"funcname",
"=",
"method",
".",
"__name__",
"parent_doc",
"=",
"from_class",
".",
"__dict__",
"[",
"funcname",
"]",
".",
"__doc__",
"if",
"method",
".",
"_... | Private wrapper function to inherit docstrings from Base class
Usage example:
class mood(object):
'describes typical reactions of a person in a specific mood'
def how_are_you(self):
'returns a typical answer to How are you? being in specific mood'
raise NotImple... | [
"Private",
"wrapper",
"function",
"to",
"inherit",
"docstrings",
"from",
"Base",
"class",
"Usage",
"example",
":",
"class",
"mood",
"(",
"object",
")",
":",
"describes",
"typical",
"reactions",
"of",
"a",
"person",
"in",
"a",
"specific",
"mood",
"def",
"how_... | python | train |
jleclanche/fireplace | fireplace/entity.py | https://github.com/jleclanche/fireplace/blob/d0fc0e97e185c0210de86631be20638659c0609e/fireplace/entity.py#L79-L86 | def get_damage(self, amount: int, target) -> int:
"""
Override to modify the damage dealt to a target from the given amount.
"""
if target.immune:
self.log("%r is immune to %s for %i damage", target, self, amount)
return 0
return amount | [
"def",
"get_damage",
"(",
"self",
",",
"amount",
":",
"int",
",",
"target",
")",
"->",
"int",
":",
"if",
"target",
".",
"immune",
":",
"self",
".",
"log",
"(",
"\"%r is immune to %s for %i damage\"",
",",
"target",
",",
"self",
",",
"amount",
")",
"retur... | Override to modify the damage dealt to a target from the given amount. | [
"Override",
"to",
"modify",
"the",
"damage",
"dealt",
"to",
"a",
"target",
"from",
"the",
"given",
"amount",
"."
] | python | train |
tmontaigu/pylas | pylas/point/record.py | https://github.com/tmontaigu/pylas/blob/8335a1a7d7677f0e4bc391bb6fa3c75b42ed5b06/pylas/point/record.py#L253-L282 | def from_stream(cls, stream, point_format, count):
""" Construct the point record by reading the points from the stream
"""
points_dtype = point_format.dtype
point_data_buffer = bytearray(stream.read(count * points_dtype.itemsize))
try:
data = np.frombuffer(point_dat... | [
"def",
"from_stream",
"(",
"cls",
",",
"stream",
",",
"point_format",
",",
"count",
")",
":",
"points_dtype",
"=",
"point_format",
".",
"dtype",
"point_data_buffer",
"=",
"bytearray",
"(",
"stream",
".",
"read",
"(",
"count",
"*",
"points_dtype",
".",
"items... | Construct the point record by reading the points from the stream | [
"Construct",
"the",
"point",
"record",
"by",
"reading",
"the",
"points",
"from",
"the",
"stream"
] | python | test |
DarkEnergySurvey/ugali | ugali/utils/logger.py | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/logger.py#L39-L45 | def file_found(filename,force):
"""Check if a file exists"""
if os.path.exists(filename) and not force:
logger.info("Found %s; skipping..."%filename)
return True
else:
return False | [
"def",
"file_found",
"(",
"filename",
",",
"force",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
"and",
"not",
"force",
":",
"logger",
".",
"info",
"(",
"\"Found %s; skipping...\"",
"%",
"filename",
")",
"return",
"True",
"else... | Check if a file exists | [
"Check",
"if",
"a",
"file",
"exists"
] | python | train |
google/grr | grr/server/grr_response_server/hunt.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/hunt.py#L197-L207 | def CreateHunt(hunt_obj):
"""Creates a hunt using a given hunt object."""
data_store.REL_DB.WriteHuntObject(hunt_obj)
if hunt_obj.HasField("output_plugins"):
output_plugins_states = flow.GetOutputPluginStates(
hunt_obj.output_plugins,
source="hunts/%s" % hunt_obj.hunt_id,
token=access... | [
"def",
"CreateHunt",
"(",
"hunt_obj",
")",
":",
"data_store",
".",
"REL_DB",
".",
"WriteHuntObject",
"(",
"hunt_obj",
")",
"if",
"hunt_obj",
".",
"HasField",
"(",
"\"output_plugins\"",
")",
":",
"output_plugins_states",
"=",
"flow",
".",
"GetOutputPluginStates",
... | Creates a hunt using a given hunt object. | [
"Creates",
"a",
"hunt",
"using",
"a",
"given",
"hunt",
"object",
"."
] | python | train |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L7250-L7276 | def plot(self, plot_cmd=None, tf=lambda y: y):
"""plot the data we have, return ``self``"""
if not plot_cmd:
plot_cmd = self.plot_cmd
colors = 'bgrcmyk'
pyplot.hold(False)
res = self.res
flatx, flatf = self.flattened()
minf = np.inf
for i in f... | [
"def",
"plot",
"(",
"self",
",",
"plot_cmd",
"=",
"None",
",",
"tf",
"=",
"lambda",
"y",
":",
"y",
")",
":",
"if",
"not",
"plot_cmd",
":",
"plot_cmd",
"=",
"self",
".",
"plot_cmd",
"colors",
"=",
"'bgrcmyk'",
"pyplot",
".",
"hold",
"(",
"False",
")... | plot the data we have, return ``self`` | [
"plot",
"the",
"data",
"we",
"have",
"return",
"self"
] | python | train |
istresearch/scrapy-cluster | crawler/crawling/pipelines.py | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/pipelines.py#L138-L153 | def _clean_item(self, item):
'''
Cleans the item to be logged
'''
item_copy = dict(item)
del item_copy['body']
del item_copy['links']
del item_copy['response_headers']
del item_copy['request_headers']
del item_copy['status_code']
del item_c... | [
"def",
"_clean_item",
"(",
"self",
",",
"item",
")",
":",
"item_copy",
"=",
"dict",
"(",
"item",
")",
"del",
"item_copy",
"[",
"'body'",
"]",
"del",
"item_copy",
"[",
"'links'",
"]",
"del",
"item_copy",
"[",
"'response_headers'",
"]",
"del",
"item_copy",
... | Cleans the item to be logged | [
"Cleans",
"the",
"item",
"to",
"be",
"logged"
] | python | train |
tdegeus/GooseMPL | GooseMPL/__init__.py | https://github.com/tdegeus/GooseMPL/blob/16e1e06cbcf7131ac98c03ca7251ce83734ef905/GooseMPL/__init__.py#L1080-L1129 | def hist(P, edges, **kwargs):
r'''
Plot histogram.
'''
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
# extract local options
axis = kwargs.pop( 'axis' , plt.gca() )
cindex = kwargs.pop( 'cindex' , None )
autoscale = kwargs.pop( 'auto... | [
"def",
"hist",
"(",
"P",
",",
"edges",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"matplotlib",
".",
"collections",
"import",
"PatchCollection",
"from",
"matplotlib",
".",
"patches",
"import",
"Polygon",
"# extract local options",
"axis",
"=",
"kwargs",
".",
... | r'''
Plot histogram. | [
"r",
"Plot",
"histogram",
"."
] | python | train |
deanmalmgren/textract | textract/parsers/html_parser.py | https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L27-L34 | def _visible(self, element):
"""Used to filter text elements that have invisible text on the page.
"""
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True | [
"def",
"_visible",
"(",
"self",
",",
"element",
")",
":",
"if",
"element",
".",
"name",
"in",
"self",
".",
"_disallowed_names",
":",
"return",
"False",
"elif",
"re",
".",
"match",
"(",
"u'<!--.*-->'",
",",
"six",
".",
"text_type",
"(",
"element",
".",
... | Used to filter text elements that have invisible text on the page. | [
"Used",
"to",
"filter",
"text",
"elements",
"that",
"have",
"invisible",
"text",
"on",
"the",
"page",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/models/research/glow_ops.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/glow_ops.py#L548-L603 | def conv_block(name, x, mid_channels, dilations=None, activation="relu",
dropout=0.0):
"""2 layer conv block used in the affine coupling layer.
Args:
name: variable scope.
x: 4-D or 5-D Tensor.
mid_channels: Output channels of the second layer.
dilations: Optional, list of integers.
... | [
"def",
"conv_block",
"(",
"name",
",",
"x",
",",
"mid_channels",
",",
"dilations",
"=",
"None",
",",
"activation",
"=",
"\"relu\"",
",",
"dropout",
"=",
"0.0",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"reuse",
"=",
"tf",
".",
... | 2 layer conv block used in the affine coupling layer.
Args:
name: variable scope.
x: 4-D or 5-D Tensor.
mid_channels: Output channels of the second layer.
dilations: Optional, list of integers.
activation: relu or gatu.
If relu, the second layer is relu(W*x)
If gatu, the second layer ... | [
"2",
"layer",
"conv",
"block",
"used",
"in",
"the",
"affine",
"coupling",
"layer",
"."
] | python | train |
Robpol86/libnl | libnl/genl/family.py | https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/libnl/genl/family.py#L171-L184 | def genl_family_add_grp(family, id_, name):
"""https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/family.c#L366.
Positional arguments:
family -- Generic Netlink family object (genl_family class instance).
id_ -- new numeric identifier (integer).
name -- new human readable name (string).
... | [
"def",
"genl_family_add_grp",
"(",
"family",
",",
"id_",
",",
"name",
")",
":",
"grp",
"=",
"genl_family_grp",
"(",
"id_",
"=",
"id_",
",",
"name",
"=",
"name",
")",
"nl_list_add_tail",
"(",
"grp",
".",
"list_",
",",
"family",
".",
"gf_mc_grps",
")",
"... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/family.c#L366.
Positional arguments:
family -- Generic Netlink family object (genl_family class instance).
id_ -- new numeric identifier (integer).
name -- new human readable name (string).
Returns:
0 | [
"https",
":",
"//",
"github",
".",
"com",
"/",
"thom311",
"/",
"libnl",
"/",
"blob",
"/",
"libnl3_2_25",
"/",
"lib",
"/",
"genl",
"/",
"family",
".",
"c#L366",
"."
] | python | train |
saltstack/salt | salt/utils/verify.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/verify.py#L120-L146 | def verify_socket(interface, pub_port, ret_port):
'''
Attempt to bind to the sockets to verify that they are available
'''
addr_family = lookup_family(interface)
for port in pub_port, ret_port:
sock = socket.socket(addr_family, socket.SOCK_STREAM)
try:
sock.setsockopt(so... | [
"def",
"verify_socket",
"(",
"interface",
",",
"pub_port",
",",
"ret_port",
")",
":",
"addr_family",
"=",
"lookup_family",
"(",
"interface",
")",
"for",
"port",
"in",
"pub_port",
",",
"ret_port",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"addr_family",... | Attempt to bind to the sockets to verify that they are available | [
"Attempt",
"to",
"bind",
"to",
"the",
"sockets",
"to",
"verify",
"that",
"they",
"are",
"available"
] | python | train |
fm4d/KickassAPI | KickassAPI.py | https://github.com/fm4d/KickassAPI/blob/6ecc6846dcec0d6f6e493bf776031aa92d55604f/KickassAPI.py#L322-L326 | def all(self):
"""
Yield torrents in range from current page to last page
"""
return self.pages(self.url.page, self.url.max_page) | [
"def",
"all",
"(",
"self",
")",
":",
"return",
"self",
".",
"pages",
"(",
"self",
".",
"url",
".",
"page",
",",
"self",
".",
"url",
".",
"max_page",
")"
] | Yield torrents in range from current page to last page | [
"Yield",
"torrents",
"in",
"range",
"from",
"current",
"page",
"to",
"last",
"page"
] | python | train |
bitesofcode/projexui | projexui/dialogs/xwizardbrowserdialog/xwizardplugin.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/dialogs/xwizardbrowserdialog/xwizardplugin.py#L152-L167 | def groupIcon( cls, groupName, default = None ):
"""
Returns the icon for the inputed group name.
:param groupName | <str>
default | <str> || None
:return <str>
"""
if ( cls._groupIcons is None ):
cls.... | [
"def",
"groupIcon",
"(",
"cls",
",",
"groupName",
",",
"default",
"=",
"None",
")",
":",
"if",
"(",
"cls",
".",
"_groupIcons",
"is",
"None",
")",
":",
"cls",
".",
"_groupIcons",
"=",
"{",
"}",
"if",
"(",
"not",
"default",
")",
":",
"default",
"=",
... | Returns the icon for the inputed group name.
:param groupName | <str>
default | <str> || None
:return <str> | [
"Returns",
"the",
"icon",
"for",
"the",
"inputed",
"group",
"name",
".",
":",
"param",
"groupName",
"|",
"<str",
">",
"default",
"|",
"<str",
">",
"||",
"None",
":",
"return",
"<str",
">"
] | python | train |
quodlibet/mutagen | mutagen/_util.py | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/_util.py#L942-L971 | def encode_endian(text, encoding, errors="strict", le=True):
"""Like text.encode(encoding) but always returns little endian/big endian
BOMs instead of the system one.
Args:
text (text)
encoding (str)
errors (str)
le (boolean): if little endian
Returns:
bytes
... | [
"def",
"encode_endian",
"(",
"text",
",",
"encoding",
",",
"errors",
"=",
"\"strict\"",
",",
"le",
"=",
"True",
")",
":",
"encoding",
"=",
"codecs",
".",
"lookup",
"(",
"encoding",
")",
".",
"name",
"if",
"encoding",
"==",
"\"utf-16\"",
":",
"if",
"le"... | Like text.encode(encoding) but always returns little endian/big endian
BOMs instead of the system one.
Args:
text (text)
encoding (str)
errors (str)
le (boolean): if little endian
Returns:
bytes
Raises:
UnicodeEncodeError
LookupError | [
"Like",
"text",
".",
"encode",
"(",
"encoding",
")",
"but",
"always",
"returns",
"little",
"endian",
"/",
"big",
"endian",
"BOMs",
"instead",
"of",
"the",
"system",
"one",
"."
] | python | train |
kstaniek/condoor | condoor/utils.py | https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/utils.py#L49-L82 | def is_reachable(host, port=23):
"""Check reachability for specified hostname/port.
It tries to open TCP socket.
It supports IPv6.
:param host: hostname or ip address string
:rtype: str
:param port: tcp port number
:rtype: number
:return: True if host is reachable else false
"""
... | [
"def",
"is_reachable",
"(",
"host",
",",
"port",
"=",
"23",
")",
":",
"try",
":",
"addresses",
"=",
"socket",
".",
"getaddrinfo",
"(",
"host",
",",
"port",
",",
"socket",
".",
"AF_UNSPEC",
",",
"socket",
".",
"SOCK_STREAM",
")",
"except",
"socket",
"."... | Check reachability for specified hostname/port.
It tries to open TCP socket.
It supports IPv6.
:param host: hostname or ip address string
:rtype: str
:param port: tcp port number
:rtype: number
:return: True if host is reachable else false | [
"Check",
"reachability",
"for",
"specified",
"hostname",
"/",
"port",
"."
] | python | train |
wummel/patool | patoolib/programs/py_gzip.py | https://github.com/wummel/patool/blob/d7e64d9fd60faaa4b3f824bd97c43ce59b185c40/patoolib/programs/py_gzip.py#L24-L37 | def extract_gzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a GZIP archive with the gzip Python module."""
targetname = util.get_single_outfile(outdir, archive)
try:
with gzip.GzipFile(archive) as gzipfile:
with open(targetname, 'wb') as targetfile:
... | [
"def",
"extract_gzip",
"(",
"archive",
",",
"compression",
",",
"cmd",
",",
"verbosity",
",",
"interactive",
",",
"outdir",
")",
":",
"targetname",
"=",
"util",
".",
"get_single_outfile",
"(",
"outdir",
",",
"archive",
")",
"try",
":",
"with",
"gzip",
".",... | Extract a GZIP archive with the gzip Python module. | [
"Extract",
"a",
"GZIP",
"archive",
"with",
"the",
"gzip",
"Python",
"module",
"."
] | python | train |
heitzmann/gdspy | gdspy/__init__.py | https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L100-L120 | def _eight_byte_real_to_float(value):
"""
Convert a number from GDSII 8 byte real format to float.
Parameters
----------
value : string
The GDSII binary string representation of the number.
Returns
-------
out : float
The number represented by ``value``.
"""
sho... | [
"def",
"_eight_byte_real_to_float",
"(",
"value",
")",
":",
"short1",
",",
"short2",
",",
"long3",
"=",
"struct",
".",
"unpack",
"(",
"'>HHL'",
",",
"value",
")",
"exponent",
"=",
"(",
"short1",
"&",
"0x7f00",
")",
"//",
"256",
"-",
"64",
"mantissa",
"... | Convert a number from GDSII 8 byte real format to float.
Parameters
----------
value : string
The GDSII binary string representation of the number.
Returns
-------
out : float
The number represented by ``value``. | [
"Convert",
"a",
"number",
"from",
"GDSII",
"8",
"byte",
"real",
"format",
"to",
"float",
"."
] | python | train |
dossier/dossier.web | dossier/web/label_folders.py | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/label_folders.py#L157-L185 | def items(self, folder_id, subfolder_id, ann_id=None):
'''Yields an unodered generator of items in a subfolder.
The generator yields items, which are represented by a tuple
of ``content_id`` and ``subtopic_id``. The format of these
identifiers is unspecified.
By default (with `... | [
"def",
"items",
"(",
"self",
",",
"folder_id",
",",
"subfolder_id",
",",
"ann_id",
"=",
"None",
")",
":",
"self",
".",
"assert_valid_folder_id",
"(",
"folder_id",
")",
"self",
".",
"assert_valid_folder_id",
"(",
"subfolder_id",
")",
"ann_id",
"=",
"self",
".... | Yields an unodered generator of items in a subfolder.
The generator yields items, which are represented by a tuple
of ``content_id`` and ``subtopic_id``. The format of these
identifiers is unspecified.
By default (with ``ann_id=None``), subfolders are shown for all
anonymous us... | [
"Yields",
"an",
"unodered",
"generator",
"of",
"items",
"in",
"a",
"subfolder",
"."
] | python | train |
minio/minio-py | minio/api.py | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L840-L908 | def list_objects(self, bucket_name, prefix='', recursive=False):
"""
List objects in the given bucket.
Examples:
objects = minio.list_objects('foo')
for current_object in objects:
print(current_object)
# hello
# hello/
... | [
"def",
"list_objects",
"(",
"self",
",",
"bucket_name",
",",
"prefix",
"=",
"''",
",",
"recursive",
"=",
"False",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"# If someone explicitly set prefix to None convert it to empty string.",
"if",
"prefix",
"is",
... | List objects in the given bucket.
Examples:
objects = minio.list_objects('foo')
for current_object in objects:
print(current_object)
# hello
# hello/
# hello/
# world/
objects = minio.list_objects('foo', prefix... | [
"List",
"objects",
"in",
"the",
"given",
"bucket",
"."
] | python | train |
google/gin-config | gin/config.py | https://github.com/google/gin-config/blob/17a170e0a6711005d1c78e67cf493dc44674d44f/gin/config.py#L565-L602 | def bind_parameter(binding_key, value):
"""Binds the parameter value specified by `binding_key` to `value`.
The `binding_key` argument should either be a string of the form
`maybe/scope/optional.module.names.configurable_name.parameter_name`, or a
list or tuple of `(scope, selector, parameter_name)`, where `se... | [
"def",
"bind_parameter",
"(",
"binding_key",
",",
"value",
")",
":",
"if",
"config_is_locked",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'Attempted to modify locked Gin config.'",
")",
"pbk",
"=",
"ParsedBindingKey",
"(",
"binding_key",
")",
"fn_dict",
"=",
"_... | Binds the parameter value specified by `binding_key` to `value`.
The `binding_key` argument should either be a string of the form
`maybe/scope/optional.module.names.configurable_name.parameter_name`, or a
list or tuple of `(scope, selector, parameter_name)`, where `selector`
corresponds to `optional.module.nam... | [
"Binds",
"the",
"parameter",
"value",
"specified",
"by",
"binding_key",
"to",
"value",
"."
] | python | test |
bcbio/bcbio-nextgen | bcbio/variation/coverage.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/coverage.py#L249-L269 | def coverage_region_detailed_stats(target_name, bed_file, data, out_dir):
"""
Calculate coverage at different completeness cutoff
for region in coverage option.
"""
if bed_file and utils.file_exists(bed_file):
ready_depth = tz.get_in(["depth", target_name], data)
if ready_depth:
... | [
"def",
"coverage_region_detailed_stats",
"(",
"target_name",
",",
"bed_file",
",",
"data",
",",
"out_dir",
")",
":",
"if",
"bed_file",
"and",
"utils",
".",
"file_exists",
"(",
"bed_file",
")",
":",
"ready_depth",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"depth\... | Calculate coverage at different completeness cutoff
for region in coverage option. | [
"Calculate",
"coverage",
"at",
"different",
"completeness",
"cutoff",
"for",
"region",
"in",
"coverage",
"option",
"."
] | python | train |
wilson-eft/wilson | wilson/util/wetutil.py | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/wetutil.py#L83-L105 | def JMS_to_array(C, sectors=None):
"""For a dictionary with JMS Wilson coefficients, return a dictionary
of arrays."""
if sectors is None:
wc_keys = wcxf.Basis['WET', 'JMS'].all_wcs
else:
try:
wc_keys = [k for s in sectors for k in wcxf.Basis['WET', 'JMS'].sectors[s]]
... | [
"def",
"JMS_to_array",
"(",
"C",
",",
"sectors",
"=",
"None",
")",
":",
"if",
"sectors",
"is",
"None",
":",
"wc_keys",
"=",
"wcxf",
".",
"Basis",
"[",
"'WET'",
",",
"'JMS'",
"]",
".",
"all_wcs",
"else",
":",
"try",
":",
"wc_keys",
"=",
"[",
"k",
... | For a dictionary with JMS Wilson coefficients, return a dictionary
of arrays. | [
"For",
"a",
"dictionary",
"with",
"JMS",
"Wilson",
"coefficients",
"return",
"a",
"dictionary",
"of",
"arrays",
"."
] | python | train |
paydunya/paydunya-python | paydunya/opr.py | https://github.com/paydunya/paydunya-python/blob/bb55791e2814788aec74162d9d78970815f37c30/paydunya/opr.py#L38-L45 | def charge(self, data):
"""Second stage of an OPR request"""
token = data.get("token", self._response["token"])
data = {
"token": token,
"confirm_token": data.get("confirm_token")
}
return self._process('opr/charge', data) | [
"def",
"charge",
"(",
"self",
",",
"data",
")",
":",
"token",
"=",
"data",
".",
"get",
"(",
"\"token\"",
",",
"self",
".",
"_response",
"[",
"\"token\"",
"]",
")",
"data",
"=",
"{",
"\"token\"",
":",
"token",
",",
"\"confirm_token\"",
":",
"data",
".... | Second stage of an OPR request | [
"Second",
"stage",
"of",
"an",
"OPR",
"request"
] | python | train |
tensorflow/probability | tensorflow_probability/python/distributions/dirichlet_multinomial.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/dirichlet_multinomial.py#L340-L350 | def _maybe_assert_valid_sample(self, counts):
"""Check counts for proper shape, values, then return tensor version."""
if not self.validate_args:
return counts
counts = distribution_util.embed_check_nonnegative_integer_form(counts)
return distribution_util.with_dependencies([
assert_util.a... | [
"def",
"_maybe_assert_valid_sample",
"(",
"self",
",",
"counts",
")",
":",
"if",
"not",
"self",
".",
"validate_args",
":",
"return",
"counts",
"counts",
"=",
"distribution_util",
".",
"embed_check_nonnegative_integer_form",
"(",
"counts",
")",
"return",
"distributio... | Check counts for proper shape, values, then return tensor version. | [
"Check",
"counts",
"for",
"proper",
"shape",
"values",
"then",
"return",
"tensor",
"version",
"."
] | python | test |
array-split/array_split | array_split/split.py | https://github.com/array-split/array_split/blob/e07abe3001209394dde809f7e6f505f9f49a1c26/array_split/split.py#L1588-L1615 | def array_split(
ary,
indices_or_sections=None,
axis=None,
tile_shape=None,
max_tile_bytes=None,
max_tile_shape=None,
sub_tile_shape=None,
halo=None
):
"To be replaced."
return [
ary[slyce]
for slyce in
shape_split(
array_shape=ary.shape,
... | [
"def",
"array_split",
"(",
"ary",
",",
"indices_or_sections",
"=",
"None",
",",
"axis",
"=",
"None",
",",
"tile_shape",
"=",
"None",
",",
"max_tile_bytes",
"=",
"None",
",",
"max_tile_shape",
"=",
"None",
",",
"sub_tile_shape",
"=",
"None",
",",
"halo",
"=... | To be replaced. | [
"To",
"be",
"replaced",
"."
] | python | train |
ARMmbed/icetea | icetea_lib/Result.py | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Result.py#L232-L241 | def build_data(self):
"""
get build data.
:return: build data or None if not found
"""
# pylint: disable=len-as-condition
if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None):
return self.dutinformation.get(0).build.get_data()
... | [
"def",
"build_data",
"(",
"self",
")",
":",
"# pylint: disable=len-as-condition",
"if",
"len",
"(",
"self",
".",
"dutinformation",
")",
">",
"0",
"and",
"(",
"self",
".",
"dutinformation",
".",
"get",
"(",
"0",
")",
".",
"build",
"is",
"not",
"None",
")"... | get build data.
:return: build data or None if not found | [
"get",
"build",
"data",
"."
] | python | train |
klen/django-netauth | netauth/utils.py | https://github.com/klen/django-netauth/blob/228e4297fda98d5f9df35f86a01f87c6fb05ab1d/netauth/utils.py#L12-L21 | def parse_template(template_path, **kwargs):
""" Load and render template.
First line of template should contain the subject of email.
Return tuple with subject and content.
"""
template = get_template(template_path)
context = Context(kwargs)
data = template.render(context).strip()
... | [
"def",
"parse_template",
"(",
"template_path",
",",
"*",
"*",
"kwargs",
")",
":",
"template",
"=",
"get_template",
"(",
"template_path",
")",
"context",
"=",
"Context",
"(",
"kwargs",
")",
"data",
"=",
"template",
".",
"render",
"(",
"context",
")",
".",
... | Load and render template.
First line of template should contain the subject of email.
Return tuple with subject and content. | [
"Load",
"and",
"render",
"template",
".",
"First",
"line",
"of",
"template",
"should",
"contain",
"the",
"subject",
"of",
"email",
".",
"Return",
"tuple",
"with",
"subject",
"and",
"content",
"."
] | python | train |
numenta/htmresearch | projects/union_path_integration/convergence_simulation.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/union_path_integration/convergence_simulation.py#L256-L281 | def runMultiprocessNoiseExperiment(resultName, repeat, numWorkers,
appendResults, **kwargs):
"""
:param kwargs: Pass lists to distribute as lists, lists that should be passed intact as tuples.
:return: results, in the format [(arguments, results)]. Also saved to json at resultN... | [
"def",
"runMultiprocessNoiseExperiment",
"(",
"resultName",
",",
"repeat",
",",
"numWorkers",
",",
"appendResults",
",",
"*",
"*",
"kwargs",
")",
":",
"experiments",
"=",
"[",
"{",
"}",
"]",
"for",
"key",
",",
"values",
"in",
"kwargs",
".",
"items",
"(",
... | :param kwargs: Pass lists to distribute as lists, lists that should be passed intact as tuples.
:return: results, in the format [(arguments, results)]. Also saved to json at resultName, in the same format. | [
":",
"param",
"kwargs",
":",
"Pass",
"lists",
"to",
"distribute",
"as",
"lists",
"lists",
"that",
"should",
"be",
"passed",
"intact",
"as",
"tuples",
".",
":",
"return",
":",
"results",
"in",
"the",
"format",
"[",
"(",
"arguments",
"results",
")",
"]",
... | python | train |
ebroecker/canmatrix | src/canmatrix/copy.py | https://github.com/ebroecker/canmatrix/blob/d6150b7a648350f051a11c431e9628308c8d5593/src/canmatrix/copy.py#L131-L200 | def copy_frame(frame_id, source_db, target_db):
# type: (cm.ArbitrationId, cm.CanMatrix, cm.CanMatrix) -> bool
"""
Copy a Frame identified by ArbitrationId from source CAN matrix to target CAN matrix.
This function additionally copy all relevant ECUs and Defines.
:param frame_id: Frame arbitration ... | [
"def",
"copy_frame",
"(",
"frame_id",
",",
"source_db",
",",
"target_db",
")",
":",
"# type: (cm.ArbitrationId, cm.CanMatrix, cm.CanMatrix) -> bool",
"frame_list",
"=",
"[",
"source_db",
".",
"frame_by_id",
"(",
"frame_id",
")",
"]",
"for",
"frame",
"in",
"frame_list"... | Copy a Frame identified by ArbitrationId from source CAN matrix to target CAN matrix.
This function additionally copy all relevant ECUs and Defines.
:param frame_id: Frame arbitration od
:param source_db: Source CAN matrix
:param target_db: Destination CAN matrix | [
"Copy",
"a",
"Frame",
"identified",
"by",
"ArbitrationId",
"from",
"source",
"CAN",
"matrix",
"to",
"target",
"CAN",
"matrix",
".",
"This",
"function",
"additionally",
"copy",
"all",
"relevant",
"ECUs",
"and",
"Defines",
"."
] | python | train |
nitely/django-hooks | hooks/signalhook.py | https://github.com/nitely/django-hooks/blob/26ea2150c9be110e90b9ee60fbfd1065ac30ab1d/hooks/signalhook.py#L72-L88 | def send(self, name, sender=None, **kwargs):
"""
Sends the signal. Return every function response\
that was hooked to hook-name as a list: [(func, response), ]
:param str name: The hook name
:param class sender: Optional sender __class__ to which\
registered callback sho... | [
"def",
"send",
"(",
"self",
",",
"name",
",",
"sender",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"signal",
"=",
"self",
".",
"_registry",
"[",
"name",
"]",
"except",
"KeyError",
":",
"return",
"[",
"]",
"return",
"signal",
".",
... | Sends the signal. Return every function response\
that was hooked to hook-name as a list: [(func, response), ]
:param str name: The hook name
:param class sender: Optional sender __class__ to which\
registered callback should match (see :py:func:`.connect` method)
:return: Signa... | [
"Sends",
"the",
"signal",
".",
"Return",
"every",
"function",
"response",
"\\",
"that",
"was",
"hooked",
"to",
"hook",
"-",
"name",
"as",
"a",
"list",
":",
"[",
"(",
"func",
"response",
")",
"]"
] | python | train |
tjvr/kurt | kurt/scratch14/objtable.py | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/scratch14/objtable.py#L383-L443 | def encode_network(root):
"""Yield ref-containing obj table entries from object network"""
def fix_values(obj):
if isinstance(obj, Container):
obj.update((k, get_ref(v)) for (k, v) in obj.items()
if k != 'class_name')
fixed_obj = obj
... | [
"def",
"encode_network",
"(",
"root",
")",
":",
"def",
"fix_values",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Container",
")",
":",
"obj",
".",
"update",
"(",
"(",
"k",
",",
"get_ref",
"(",
"v",
")",
")",
"for",
"(",
"k",
",",
... | Yield ref-containing obj table entries from object network | [
"Yield",
"ref",
"-",
"containing",
"obj",
"table",
"entries",
"from",
"object",
"network"
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/frontend/terminal/console/interactiveshell.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/terminal/console/interactiveshell.py#L220-L233 | def wait_for_kernel(self, timeout=None):
"""method to wait for a kernel to be ready"""
tic = time.time()
self.km.hb_channel.unpause()
while True:
self.run_cell('1', False)
if self.km.hb_channel.is_beating():
# heart failure was not the reason this ... | [
"def",
"wait_for_kernel",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"tic",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"km",
".",
"hb_channel",
".",
"unpause",
"(",
")",
"while",
"True",
":",
"self",
".",
"run_cell",
"(",
"'1'",
",",... | method to wait for a kernel to be ready | [
"method",
"to",
"wait",
"for",
"a",
"kernel",
"to",
"be",
"ready"
] | python | test |
LLNL/certipy | certipy/certipy.py | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L393-L412 | def remove_record(self, common_name):
"""Delete the record associated with this common name"""
bundle = self.get_files(common_name)
num_signees = len(Counter(bundle.record['signees']))
if bundle.is_ca() and num_signees > 0:
raise CertificateAuthorityInUseError(
... | [
"def",
"remove_record",
"(",
"self",
",",
"common_name",
")",
":",
"bundle",
"=",
"self",
".",
"get_files",
"(",
"common_name",
")",
"num_signees",
"=",
"len",
"(",
"Counter",
"(",
"bundle",
".",
"record",
"[",
"'signees'",
"]",
")",
")",
"if",
"bundle",... | Delete the record associated with this common name | [
"Delete",
"the",
"record",
"associated",
"with",
"this",
"common",
"name"
] | python | train |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L187-L192 | def save_state(self):
"""Save current state of GUI to configuration file."""
set_setting('lastSourceDir', self.source_directory.text())
set_setting('lastOutputDir', self.output_directory.text())
set_setting(
'useDefaultOutputDir', self.scenario_directory_radio.isChecked()) | [
"def",
"save_state",
"(",
"self",
")",
":",
"set_setting",
"(",
"'lastSourceDir'",
",",
"self",
".",
"source_directory",
".",
"text",
"(",
")",
")",
"set_setting",
"(",
"'lastOutputDir'",
",",
"self",
".",
"output_directory",
".",
"text",
"(",
")",
")",
"s... | Save current state of GUI to configuration file. | [
"Save",
"current",
"state",
"of",
"GUI",
"to",
"configuration",
"file",
"."
] | python | train |
daknuett/py_register_machine2 | core/processor.py | https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/core/processor.py#L218-L226 | def interrupt(self, address):
"""
Interrupts the Processor and forces him to jump to ``address``.
If ``push_pc`` is enabled this will push the PC to the stack.
"""
if(self.push_pc):
self.memory_bus.write_word(self.sp, self.pc)
self._set_sp(self.sp - 1)
self._set_pc(address) | [
"def",
"interrupt",
"(",
"self",
",",
"address",
")",
":",
"if",
"(",
"self",
".",
"push_pc",
")",
":",
"self",
".",
"memory_bus",
".",
"write_word",
"(",
"self",
".",
"sp",
",",
"self",
".",
"pc",
")",
"self",
".",
"_set_sp",
"(",
"self",
".",
"... | Interrupts the Processor and forces him to jump to ``address``.
If ``push_pc`` is enabled this will push the PC to the stack. | [
"Interrupts",
"the",
"Processor",
"and",
"forces",
"him",
"to",
"jump",
"to",
"address",
".",
"If",
"push_pc",
"is",
"enabled",
"this",
"will",
"push",
"the",
"PC",
"to",
"the",
"stack",
"."
] | python | train |
KnowledgeLinks/rdfframework | rdfframework/rdfclass/esconversion.py | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/esconversion.py#L67-L83 | def get_idx_types(rng_def, ranges):
"""
Returns the elasticsearch index types for the obj
args:
rng_def: the range defintion dictionay
ranges: rdfproperty ranges
"""
idx_types = rng_def.get('kds_esIndexType', []).copy()
if not idx_types:
nested = False
for rng in... | [
"def",
"get_idx_types",
"(",
"rng_def",
",",
"ranges",
")",
":",
"idx_types",
"=",
"rng_def",
".",
"get",
"(",
"'kds_esIndexType'",
",",
"[",
"]",
")",
".",
"copy",
"(",
")",
"if",
"not",
"idx_types",
":",
"nested",
"=",
"False",
"for",
"rng",
"in",
... | Returns the elasticsearch index types for the obj
args:
rng_def: the range defintion dictionay
ranges: rdfproperty ranges | [
"Returns",
"the",
"elasticsearch",
"index",
"types",
"for",
"the",
"obj"
] | python | train |
studionow/pybrightcove | pybrightcove/video.py | https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/video.py#L537-L557 | def save(self, create_multiple_renditions=True,
preserve_source_rendition=True,
encode_to=enums.EncodeToEnum.FLV):
"""
Creates or updates the video
"""
if is_ftp_connection(self.connection) and len(self.assets) > 0:
self.connection.post(xml=self.to_xml(), asse... | [
"def",
"save",
"(",
"self",
",",
"create_multiple_renditions",
"=",
"True",
",",
"preserve_source_rendition",
"=",
"True",
",",
"encode_to",
"=",
"enums",
".",
"EncodeToEnum",
".",
"FLV",
")",
":",
"if",
"is_ftp_connection",
"(",
"self",
".",
"connection",
")"... | Creates or updates the video | [
"Creates",
"or",
"updates",
"the",
"video"
] | python | train |
mixmastamyk/console | console/detection.py | https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L452-L525 | def get_color(name, number=None):
''' Query the default terminal, for colors, etc.
Direct queries supported on xterm, iTerm, perhaps others.
Arguments:
str: name, one of ('foreground', 'fg', 'background', 'bg',
or 'index') # index grabs a palette ind... | [
"def",
"get_color",
"(",
"name",
",",
"number",
"=",
"None",
")",
":",
"colors",
"=",
"(",
")",
"if",
"is_a_tty",
"(",
")",
"and",
"not",
"env",
".",
"SSH_CLIENT",
":",
"if",
"not",
"'index'",
"in",
"_color_code_map",
":",
"_color_code_map",
"[",
"'ind... | Query the default terminal, for colors, etc.
Direct queries supported on xterm, iTerm, perhaps others.
Arguments:
str: name, one of ('foreground', 'fg', 'background', 'bg',
or 'index') # index grabs a palette index
int: or a "dynamic color n... | [
"Query",
"the",
"default",
"terminal",
"for",
"colors",
"etc",
"."
] | python | train |
PyFilesystem/pyfilesystem2 | fs/wildcard.py | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/wildcard.py#L61-L78 | def match_any(patterns, name):
# type: (Iterable[Text], Text) -> bool
"""Test if a name matches any of a list of patterns.
Will return `True` if ``patterns`` is an empty list.
Arguments:
patterns (list): A list of wildcard pattern, e.g ``["*.py",
"*.pyc"]``
name (str): A fi... | [
"def",
"match_any",
"(",
"patterns",
",",
"name",
")",
":",
"# type: (Iterable[Text], Text) -> bool",
"if",
"not",
"patterns",
":",
"return",
"True",
"return",
"any",
"(",
"match",
"(",
"pattern",
",",
"name",
")",
"for",
"pattern",
"in",
"patterns",
")"
] | Test if a name matches any of a list of patterns.
Will return `True` if ``patterns`` is an empty list.
Arguments:
patterns (list): A list of wildcard pattern, e.g ``["*.py",
"*.pyc"]``
name (str): A filename.
Returns:
bool: `True` if the name matches at least one of th... | [
"Test",
"if",
"a",
"name",
"matches",
"any",
"of",
"a",
"list",
"of",
"patterns",
"."
] | python | train |
FujiMakoto/IPS-Vagrant | ips_vagrant/common/progress.py | https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/common/progress.py#L88-L97 | def update(self, pbar):
"""
Handle progress bar updates
@type pbar: ProgressBar
@rtype: str
"""
if pbar.label != self._label:
self.label = pbar.label
return self.label | [
"def",
"update",
"(",
"self",
",",
"pbar",
")",
":",
"if",
"pbar",
".",
"label",
"!=",
"self",
".",
"_label",
":",
"self",
".",
"label",
"=",
"pbar",
".",
"label",
"return",
"self",
".",
"label"
] | Handle progress bar updates
@type pbar: ProgressBar
@rtype: str | [
"Handle",
"progress",
"bar",
"updates"
] | python | train |
google/grumpy | third_party/pythonparser/parser.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pythonparser/parser.py#L1278-L1289 | def with_stmt__26(self, with_loc, context, with_var, colon_loc, body):
"""(2.6, 3.0) with_stmt: 'with' test [ with_var ] ':' suite"""
if with_var:
as_loc, optional_vars = with_var
item = ast.withitem(context_expr=context, optional_vars=optional_vars,
... | [
"def",
"with_stmt__26",
"(",
"self",
",",
"with_loc",
",",
"context",
",",
"with_var",
",",
"colon_loc",
",",
"body",
")",
":",
"if",
"with_var",
":",
"as_loc",
",",
"optional_vars",
"=",
"with_var",
"item",
"=",
"ast",
".",
"withitem",
"(",
"context_expr"... | (2.6, 3.0) with_stmt: 'with' test [ with_var ] ':' suite | [
"(",
"2",
".",
"6",
"3",
".",
"0",
")",
"with_stmt",
":",
"with",
"test",
"[",
"with_var",
"]",
":",
"suite"
] | python | valid |
StaticCube/python-synology | SynologyDSM/SynologyDSM.py | https://github.com/StaticCube/python-synology/blob/a5446a052fc91a38f7589803dc7a654180db2566/SynologyDSM/SynologyDSM.py#L280-L296 | def volume_disk_temp_avg(self, volume):
"""Average temperature of all disks making up the volume"""
volume = self._get_volume(volume)
if volume is not None:
vol_disks = volume["disks"]
if vol_disks is not None:
total_temp = 0
total_d... | [
"def",
"volume_disk_temp_avg",
"(",
"self",
",",
"volume",
")",
":",
"volume",
"=",
"self",
".",
"_get_volume",
"(",
"volume",
")",
"if",
"volume",
"is",
"not",
"None",
":",
"vol_disks",
"=",
"volume",
"[",
"\"disks\"",
"]",
"if",
"vol_disks",
"is",
"not... | Average temperature of all disks making up the volume | [
"Average",
"temperature",
"of",
"all",
"disks",
"making",
"up",
"the",
"volume"
] | python | test |
devassistant/devassistant | devassistant/command_runners.py | https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/command_runners.py#L42-L61 | def register_command_runner(arg):
"""Decorator that registers a command runner. Accepts either:
- CommandRunner directly or
- String prefix to register a command runner under (returning a decorator)
"""
if isinstance(arg, str):
def inner(command_runner):
command_runners.setdefau... | [
"def",
"register_command_runner",
"(",
"arg",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"str",
")",
":",
"def",
"inner",
"(",
"command_runner",
")",
":",
"command_runners",
".",
"setdefault",
"(",
"arg",
",",
"[",
"]",
")",
"command_runners",
"[",
"... | Decorator that registers a command runner. Accepts either:
- CommandRunner directly or
- String prefix to register a command runner under (returning a decorator) | [
"Decorator",
"that",
"registers",
"a",
"command",
"runner",
".",
"Accepts",
"either",
":"
] | python | train |
python-diamond/Diamond | src/diamond/handler/null.py | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/null.py#L21-L30 | def get_default_config_help(self):
"""
Returns the help text for the configuration options for this handler
"""
config = super(NullHandler, self).get_default_config_help()
config.update({
})
return config | [
"def",
"get_default_config_help",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"NullHandler",
",",
"self",
")",
".",
"get_default_config_help",
"(",
")",
"config",
".",
"update",
"(",
"{",
"}",
")",
"return",
"config"
] | Returns the help text for the configuration options for this handler | [
"Returns",
"the",
"help",
"text",
"for",
"the",
"configuration",
"options",
"for",
"this",
"handler"
] | python | train |
someones/jaweson | jaweson/serialisable.py | https://github.com/someones/jaweson/blob/744c3ca0f3af86c48738e2d89ea69646f48cc013/jaweson/serialisable.py#L76-L90 | def from_dict(cls, jobj):
'''Deserialises the object.
Automatically inspects the object's __init__ function and
extracts the parameters.
Can be trivially over-written.
'''
try:
obj = cls.__new__(cls)
blacklist = set(['__class__', '__type__'] + cls.... | [
"def",
"from_dict",
"(",
"cls",
",",
"jobj",
")",
":",
"try",
":",
"obj",
"=",
"cls",
".",
"__new__",
"(",
"cls",
")",
"blacklist",
"=",
"set",
"(",
"[",
"'__class__'",
",",
"'__type__'",
"]",
"+",
"cls",
".",
"__blacklist",
")",
"for",
"k",
"in",
... | Deserialises the object.
Automatically inspects the object's __init__ function and
extracts the parameters.
Can be trivially over-written. | [
"Deserialises",
"the",
"object",
".",
"Automatically",
"inspects",
"the",
"object",
"s",
"__init__",
"function",
"and",
"extracts",
"the",
"parameters",
".",
"Can",
"be",
"trivially",
"over",
"-",
"written",
"."
] | python | train |
berkeley-cocosci/Wallace | examples/rogers/experiment.py | https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/examples/rogers/experiment.py#L369-L376 | def step(self):
"""Prompt the environment to change."""
current_state = max(self.infos(type=State),
key=attrgetter('creation_time'))
current_contents = float(current_state.contents)
new_contents = 1 - current_contents
info_out = State(origin=self, cont... | [
"def",
"step",
"(",
"self",
")",
":",
"current_state",
"=",
"max",
"(",
"self",
".",
"infos",
"(",
"type",
"=",
"State",
")",
",",
"key",
"=",
"attrgetter",
"(",
"'creation_time'",
")",
")",
"current_contents",
"=",
"float",
"(",
"current_state",
".",
... | Prompt the environment to change. | [
"Prompt",
"the",
"environment",
"to",
"change",
"."
] | python | train |
flask-restful/flask-restful | flask_restful/__init__.py | https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L239-L247 | def _has_fr_route(self):
"""Encapsulating the rules for whether the request was to a Flask endpoint"""
# 404's, 405's, which might not have a url_rule
if self._should_use_fr_error_handler():
return True
# for all other errors, just check if FR dispatched the route
if ... | [
"def",
"_has_fr_route",
"(",
"self",
")",
":",
"# 404's, 405's, which might not have a url_rule",
"if",
"self",
".",
"_should_use_fr_error_handler",
"(",
")",
":",
"return",
"True",
"# for all other errors, just check if FR dispatched the route",
"if",
"not",
"request",
".",
... | Encapsulating the rules for whether the request was to a Flask endpoint | [
"Encapsulating",
"the",
"rules",
"for",
"whether",
"the",
"request",
"was",
"to",
"a",
"Flask",
"endpoint"
] | python | train |
foremast/foremast | src/foremast/pipeline/create_pipeline.py | https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/pipeline/create_pipeline.py#L161-L191 | def compare_with_existing(self, region='us-east-1', onetime=False):
"""Compare desired pipeline with existing pipelines.
Args:
region (str): Region of desired pipeline.
onetime (bool): Looks for different pipeline if Onetime
Returns:
str: pipeline_id if exis... | [
"def",
"compare_with_existing",
"(",
"self",
",",
"region",
"=",
"'us-east-1'",
",",
"onetime",
"=",
"False",
")",
":",
"pipelines",
"=",
"self",
".",
"get_existing_pipelines",
"(",
")",
"pipeline_id",
"=",
"None",
"found",
"=",
"False",
"for",
"pipeline",
"... | Compare desired pipeline with existing pipelines.
Args:
region (str): Region of desired pipeline.
onetime (bool): Looks for different pipeline if Onetime
Returns:
str: pipeline_id if existing, empty string of not. | [
"Compare",
"desired",
"pipeline",
"with",
"existing",
"pipelines",
"."
] | python | train |
scikit-hep/root_numpy | root_numpy/_matrix.py | https://github.com/scikit-hep/root_numpy/blob/3a9bfbcf89f90dc20ca6869480a63a85e1ceebb8/root_numpy/_matrix.py#L9-L42 | def matrix(mat):
"""Convert a ROOT TMatrix into a NumPy matrix.
Parameters
----------
mat : ROOT TMatrixT
A ROOT TMatrixD or TMatrixF
Returns
-------
mat : numpy.matrix
A NumPy matrix
Examples
--------
>>> from root_numpy import matrix
>>> from ROOT import ... | [
"def",
"matrix",
"(",
"mat",
")",
":",
"import",
"ROOT",
"if",
"isinstance",
"(",
"mat",
",",
"(",
"ROOT",
".",
"TMatrixD",
",",
"ROOT",
".",
"TMatrixDSym",
")",
")",
":",
"return",
"_librootnumpy",
".",
"matrix_d",
"(",
"ROOT",
".",
"AsCObject",
"(",
... | Convert a ROOT TMatrix into a NumPy matrix.
Parameters
----------
mat : ROOT TMatrixT
A ROOT TMatrixD or TMatrixF
Returns
-------
mat : numpy.matrix
A NumPy matrix
Examples
--------
>>> from root_numpy import matrix
>>> from ROOT import TMatrixD
>>> a = TMa... | [
"Convert",
"a",
"ROOT",
"TMatrix",
"into",
"a",
"NumPy",
"matrix",
"."
] | python | train |
saltstack/salt | salt/utils/hashutils.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/hashutils.py#L152-L171 | def get_hash(path, form='sha256', chunk_size=65536):
'''
Get the hash sum of a file
This is better than ``get_sum`` for the following reasons:
- It does not read the entire file into memory.
- It does not return a string on error. The returned value of
``get_sum`` cannot really ... | [
"def",
"get_hash",
"(",
"path",
",",
"form",
"=",
"'sha256'",
",",
"chunk_size",
"=",
"65536",
")",
":",
"hash_type",
"=",
"hasattr",
"(",
"hashlib",
",",
"form",
")",
"and",
"getattr",
"(",
"hashlib",
",",
"form",
")",
"or",
"None",
"if",
"hash_type",... | Get the hash sum of a file
This is better than ``get_sum`` for the following reasons:
- It does not read the entire file into memory.
- It does not return a string on error. The returned value of
``get_sum`` cannot really be trusted since it is vulnerable to
collisions: ``ge... | [
"Get",
"the",
"hash",
"sum",
"of",
"a",
"file"
] | python | train |
FlorianRhiem/pyGLFW | glfw/__init__.py | https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L110-L116 | def wrap(self, video_mode):
"""
Wraps a nested python sequence.
"""
size, bits, self.refresh_rate = video_mode
self.width, self.height = size
self.red_bits, self.green_bits, self.blue_bits = bits | [
"def",
"wrap",
"(",
"self",
",",
"video_mode",
")",
":",
"size",
",",
"bits",
",",
"self",
".",
"refresh_rate",
"=",
"video_mode",
"self",
".",
"width",
",",
"self",
".",
"height",
"=",
"size",
"self",
".",
"red_bits",
",",
"self",
".",
"green_bits",
... | Wraps a nested python sequence. | [
"Wraps",
"a",
"nested",
"python",
"sequence",
"."
] | python | train |
inveniosoftware/invenio-deposit | invenio_deposit/api.py | https://github.com/inveniosoftware/invenio-deposit/blob/f243ea1d01ab0a3bc92ade3262d1abdd2bc32447/invenio_deposit/api.py#L303-L348 | def publish(self, pid=None, id_=None):
"""Publish a deposit.
If it's the first time:
* it calls the minter and set the following meta information inside
the deposit:
.. code-block:: python
deposit['_deposit'] = {
'type': pid_type,
... | [
"def",
"publish",
"(",
"self",
",",
"pid",
"=",
"None",
",",
"id_",
"=",
"None",
")",
":",
"pid",
"=",
"pid",
"or",
"self",
".",
"pid",
"if",
"not",
"pid",
".",
"is_registered",
"(",
")",
":",
"raise",
"PIDInvalidAction",
"(",
")",
"self",
"[",
"... | Publish a deposit.
If it's the first time:
* it calls the minter and set the following meta information inside
the deposit:
.. code-block:: python
deposit['_deposit'] = {
'type': pid_type,
'value': pid_value,
'revision_i... | [
"Publish",
"a",
"deposit",
"."
] | python | valid |
xolox/python-rotate-backups | rotate_backups/__init__.py | https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L603-L649 | def apply_rotation_scheme(self, backups_by_frequency, most_recent_backup):
"""
Apply the user defined rotation scheme to the result of :func:`group_backups()`.
:param backups_by_frequency: A :class:`dict` in the format generated by
:func:`group_backups()`.
... | [
"def",
"apply_rotation_scheme",
"(",
"self",
",",
"backups_by_frequency",
",",
"most_recent_backup",
")",
":",
"if",
"not",
"self",
".",
"rotation_scheme",
":",
"raise",
"ValueError",
"(",
"\"Refusing to use empty rotation scheme! (all backups would be deleted)\"",
")",
"fo... | Apply the user defined rotation scheme to the result of :func:`group_backups()`.
:param backups_by_frequency: A :class:`dict` in the format generated by
:func:`group_backups()`.
:param most_recent_backup: The :class:`~datetime.datetime` of the most
... | [
"Apply",
"the",
"user",
"defined",
"rotation",
"scheme",
"to",
"the",
"result",
"of",
":",
"func",
":",
"group_backups",
"()",
"."
] | python | train |
waqasbhatti/astrobase | astrobase/lcproc/checkplotproc.py | https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/lcproc/checkplotproc.py#L952-L1126 | def parallel_update_objectinfo_cpdir(cpdir,
cpglob='checkplot-*.pkl*',
liststartindex=None,
maxobjects=None,
nworkers=NCPUS,
fast_mode=... | [
"def",
"parallel_update_objectinfo_cpdir",
"(",
"cpdir",
",",
"cpglob",
"=",
"'checkplot-*.pkl*'",
",",
"liststartindex",
"=",
"None",
",",
"maxobjects",
"=",
"None",
",",
"nworkers",
"=",
"NCPUS",
",",
"fast_mode",
"=",
"False",
",",
"findercmap",
"=",
"'gray_r... | This updates the objectinfo for a directory of checkplot pickles.
Useful in cases where a previous round of GAIA/finderchart/external catalog
acquisition failed. This will preserve the following keys in the checkplots
if they exist:
comments
varinfo
objectinfo.objecttags
Parameters
--... | [
"This",
"updates",
"the",
"objectinfo",
"for",
"a",
"directory",
"of",
"checkplot",
"pickles",
"."
] | python | valid |
tino/pyFirmata | pyfirmata/pyfirmata.py | https://github.com/tino/pyFirmata/blob/05881909c4d7c4e808e9ed457144670b2136706e/pyfirmata/pyfirmata.py#L183-L194 | def add_cmd_handler(self, cmd, func):
"""Adds a command handler for a command."""
len_args = len(inspect.getargspec(func)[0])
def add_meta(f):
def decorator(*args, **kwargs):
f(*args, **kwargs)
decorator.bytes_needed = len_args - 1 # exclude self
... | [
"def",
"add_cmd_handler",
"(",
"self",
",",
"cmd",
",",
"func",
")",
":",
"len_args",
"=",
"len",
"(",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"[",
"0",
"]",
")",
"def",
"add_meta",
"(",
"f",
")",
":",
"def",
"decorator",
"(",
"*",
"args",
... | Adds a command handler for a command. | [
"Adds",
"a",
"command",
"handler",
"for",
"a",
"command",
"."
] | python | train |
pybel/pybel | src/pybel/tokens.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/tokens.py#L48-L76 | def _fusion_to_dsl(tokens) -> FusionBase:
"""Convert a PyParsing data dictionary to a PyBEL fusion data dictionary.
:param tokens: A PyParsing data dictionary representing a fusion
:type tokens: ParseResult
"""
func = tokens[FUNCTION]
fusion_dsl = FUNC_TO_FUSION_DSL[func]
member_dsl = FUNC_... | [
"def",
"_fusion_to_dsl",
"(",
"tokens",
")",
"->",
"FusionBase",
":",
"func",
"=",
"tokens",
"[",
"FUNCTION",
"]",
"fusion_dsl",
"=",
"FUNC_TO_FUSION_DSL",
"[",
"func",
"]",
"member_dsl",
"=",
"FUNC_TO_DSL",
"[",
"func",
"]",
"partner_5p",
"=",
"member_dsl",
... | Convert a PyParsing data dictionary to a PyBEL fusion data dictionary.
:param tokens: A PyParsing data dictionary representing a fusion
:type tokens: ParseResult | [
"Convert",
"a",
"PyParsing",
"data",
"dictionary",
"to",
"a",
"PyBEL",
"fusion",
"data",
"dictionary",
"."
] | python | train |
LordSputnik/mutagen | mutagen/id3.py | https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/id3.py#L833-L887 | def MakeID3v1(id3):
"""Return an ID3v1.1 tag string from a dict of ID3v2.4 frames."""
v1 = {}
for v2id, name in {"TIT2": "title", "TPE1": "artist",
"TALB": "album"}.items():
if v2id in id3:
text = id3[v2id].text[0].encode('latin1', 'replace')[:30]
else:
... | [
"def",
"MakeID3v1",
"(",
"id3",
")",
":",
"v1",
"=",
"{",
"}",
"for",
"v2id",
",",
"name",
"in",
"{",
"\"TIT2\"",
":",
"\"title\"",
",",
"\"TPE1\"",
":",
"\"artist\"",
",",
"\"TALB\"",
":",
"\"album\"",
"}",
".",
"items",
"(",
")",
":",
"if",
"v2id... | Return an ID3v1.1 tag string from a dict of ID3v2.4 frames. | [
"Return",
"an",
"ID3v1",
".",
"1",
"tag",
"string",
"from",
"a",
"dict",
"of",
"ID3v2",
".",
"4",
"frames",
"."
] | python | test |
pandas-dev/pandas | pandas/core/generic.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L2678-L2773 | def to_xarray(self):
"""
Return an xarray object from the pandas object.
Returns
-------
xarray.DataArray or xarray.Dataset
Data in the pandas structure converted to Dataset if the object is
a DataFrame, or a DataArray if the object is a Series.
... | [
"def",
"to_xarray",
"(",
"self",
")",
":",
"try",
":",
"import",
"xarray",
"except",
"ImportError",
":",
"# Give a nice error message",
"raise",
"ImportError",
"(",
"\"the xarray library is not installed\\n\"",
"\"you can install via conda\\n\"",
"\"conda install xarray\\n\"",
... | Return an xarray object from the pandas object.
Returns
-------
xarray.DataArray or xarray.Dataset
Data in the pandas structure converted to Dataset if the object is
a DataFrame, or a DataArray if the object is a Series.
See Also
--------
DataFra... | [
"Return",
"an",
"xarray",
"object",
"from",
"the",
"pandas",
"object",
"."
] | python | train |
raymondEhlers/pachyderm | pachyderm/remove_outliers.py | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/remove_outliers.py#L165-L235 | def _determine_outliers_for_moving_average(moving_average: np.ndarray,
moving_average_threshold: float,
number_of_values_to_search_ahead: int,
limit_of_number_of_values_below_threshold: int) ... | [
"def",
"_determine_outliers_for_moving_average",
"(",
"moving_average",
":",
"np",
".",
"ndarray",
",",
"moving_average_threshold",
":",
"float",
",",
"number_of_values_to_search_ahead",
":",
"int",
",",
"limit_of_number_of_values_below_threshold",
":",
"int",
")",
"->",
... | Determine outliers to remove from a given moving average.
Note:
The index returned is when the moving average first drops below the threshold for a moving average
calculated with that bin at the center. This is somewhat different from a standard moving average
calculation which would only l... | [
"Determine",
"outliers",
"to",
"remove",
"from",
"a",
"given",
"moving",
"average",
"."
] | python | train |
mfcloud/python-zvm-sdk | zvmsdk/dist.py | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/dist.py#L679-L688 | def _set_sysfs(self, fcp, target_wwpn, target_lun):
"""rhel6 set WWPN and LUN in sysfs"""
device = '0.0.%s' % fcp
port_add = "echo '%s' > " % target_wwpn
port_add += "/sys/bus/ccw/drivers/zfcp/%s/port_add" % device
unit_add = "echo '%s' > " % target_lun
unit_add += "/sys/... | [
"def",
"_set_sysfs",
"(",
"self",
",",
"fcp",
",",
"target_wwpn",
",",
"target_lun",
")",
":",
"device",
"=",
"'0.0.%s'",
"%",
"fcp",
"port_add",
"=",
"\"echo '%s' > \"",
"%",
"target_wwpn",
"port_add",
"+=",
"\"/sys/bus/ccw/drivers/zfcp/%s/port_add\"",
"%",
"devi... | rhel6 set WWPN and LUN in sysfs | [
"rhel6",
"set",
"WWPN",
"and",
"LUN",
"in",
"sysfs"
] | python | train |
elastic/elasticsearch-py | elasticsearch/client/cat.py | https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/cat.py#L229-L246 | def segments(self, index=None, params=None):
"""
The segments command is the detailed view of Lucene segments per index.
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-segments.html>`_
:arg index: A comma-separated list of index names to limit the returned
... | [
"def",
"segments",
"(",
"self",
",",
"index",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"transport",
".",
"perform_request",
"(",
"'GET'",
",",
"_make_path",
"(",
"'_cat'",
",",
"'segments'",
",",
"index",
")",
",",
"par... | The segments command is the detailed view of Lucene segments per index.
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-segments.html>`_
:arg index: A comma-separated list of index names to limit the returned
information
:arg bytes: The unit in which to display... | [
"The",
"segments",
"command",
"is",
"the",
"detailed",
"view",
"of",
"Lucene",
"segments",
"per",
"index",
".",
"<https",
":",
"//",
"www",
".",
"elastic",
".",
"co",
"/",
"guide",
"/",
"en",
"/",
"elasticsearch",
"/",
"reference",
"/",
"current",
"/",
... | python | train |
bloomreach/s4cmd | s4cmd.py | https://github.com/bloomreach/s4cmd/blob/bb51075bf43703e7cd95aa39288cf7732ec13a6d/s4cmd.py#L1754-L1761 | def match_date(self, value):
'''Search for date information in the string'''
m = self.REGEX_DATE.search(value)
date = datetime.datetime.utcnow().date()
if m:
date = datetime.date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
value = self.REGEX_DATE.sub('', value)
return (date, value... | [
"def",
"match_date",
"(",
"self",
",",
"value",
")",
":",
"m",
"=",
"self",
".",
"REGEX_DATE",
".",
"search",
"(",
"value",
")",
"date",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"date",
"(",
")",
"if",
"m",
":",
"date",
"="... | Search for date information in the string | [
"Search",
"for",
"date",
"information",
"in",
"the",
"string"
] | python | test |
splitkeycoffee/pyhottop | pyhottop/pyhottop.py | https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L919-L930 | def set_cooling_motor(self, cooling_motor):
"""Set the cooling motor config.
:param cooling_motor: Value to set the cooling motor
:type cooling_motor: bool
:returns: None
:raises: InvalidInput
"""
if type(cooling_motor) != bool:
raise InvalidInput("Co... | [
"def",
"set_cooling_motor",
"(",
"self",
",",
"cooling_motor",
")",
":",
"if",
"type",
"(",
"cooling_motor",
")",
"!=",
"bool",
":",
"raise",
"InvalidInput",
"(",
"\"Cooling motor value must be bool\"",
")",
"self",
".",
"_config",
"[",
"'cooling_motor'",
"]",
"... | Set the cooling motor config.
:param cooling_motor: Value to set the cooling motor
:type cooling_motor: bool
:returns: None
:raises: InvalidInput | [
"Set",
"the",
"cooling",
"motor",
"config",
"."
] | python | train |
Alignak-monitoring/alignak | alignak/http/arbiter_interface.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L138-L224 | def command(self, command=None,
timestamp=None, element=None, host=None, service=None, user=None, parameters=None):
# pylint: disable=too-many-branches
""" Request to execute an external command
Allowed parameters are:
`command`: mandatory parameter containing the whole ... | [
"def",
"command",
"(",
"self",
",",
"command",
"=",
"None",
",",
"timestamp",
"=",
"None",
",",
"element",
"=",
"None",
",",
"host",
"=",
"None",
",",
"service",
"=",
"None",
",",
"user",
"=",
"None",
",",
"parameters",
"=",
"None",
")",
":",
"# py... | Request to execute an external command
Allowed parameters are:
`command`: mandatory parameter containing the whole command line or only the command name
`timestamp`: optional parameter containing the timestamp. If not present, the
current timestamp is added in the command line
... | [
"Request",
"to",
"execute",
"an",
"external",
"command"
] | python | train |
bokeh/bokeh | bokeh/document/document.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L671-L678 | def on_session_destroyed(self, *callbacks):
''' Provide callbacks to invoke when the session serving the Document
is destroyed
'''
for callback in callbacks:
_check_callback(callback, ('session_context',))
self._session_destroyed_callbacks.add(callback) | [
"def",
"on_session_destroyed",
"(",
"self",
",",
"*",
"callbacks",
")",
":",
"for",
"callback",
"in",
"callbacks",
":",
"_check_callback",
"(",
"callback",
",",
"(",
"'session_context'",
",",
")",
")",
"self",
".",
"_session_destroyed_callbacks",
".",
"add",
"... | Provide callbacks to invoke when the session serving the Document
is destroyed | [
"Provide",
"callbacks",
"to",
"invoke",
"when",
"the",
"session",
"serving",
"the",
"Document",
"is",
"destroyed"
] | python | train |
edx/ecommerce-worker | ecommerce_worker/sailthru/v1/tasks.py | https://github.com/edx/ecommerce-worker/blob/55246961d805b1f64d661a5c0bae0a216589401f/ecommerce_worker/sailthru/v1/tasks.py#L57-L85 | def _record_purchase(sailthru_client, email, item, purchase_incomplete, message_id, options):
"""Record a purchase in Sailthru
Arguments:
sailthru_client (object): SailthruClient
email (str): user's email address
item (dict): Sailthru required information about the course
purcha... | [
"def",
"_record_purchase",
"(",
"sailthru_client",
",",
"email",
",",
"item",
",",
"purchase_incomplete",
",",
"message_id",
",",
"options",
")",
":",
"try",
":",
"sailthru_response",
"=",
"sailthru_client",
".",
"purchase",
"(",
"email",
",",
"[",
"item",
"]"... | Record a purchase in Sailthru
Arguments:
sailthru_client (object): SailthruClient
email (str): user's email address
item (dict): Sailthru required information about the course
purchase_incomplete (boolean): True if adding item to shopping cart
message_id (str): Cookie used t... | [
"Record",
"a",
"purchase",
"in",
"Sailthru"
] | python | test |
inveniosoftware/invenio-migrator | invenio_migrator/legacy/bibdocfile.py | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/bibdocfile.py#L143-L150 | def check(id_):
"""Check bibdocs."""
BibRecDocs, BibDoc = _import_bibdoc()
try:
BibDoc(id_).list_all_files()
except Exception:
click.secho("BibDoc {0} failed check.".format(id_), fg='red') | [
"def",
"check",
"(",
"id_",
")",
":",
"BibRecDocs",
",",
"BibDoc",
"=",
"_import_bibdoc",
"(",
")",
"try",
":",
"BibDoc",
"(",
"id_",
")",
".",
"list_all_files",
"(",
")",
"except",
"Exception",
":",
"click",
".",
"secho",
"(",
"\"BibDoc {0} failed check.\... | Check bibdocs. | [
"Check",
"bibdocs",
"."
] | python | test |
pyvisa/pyvisa | pyvisa/shell.py | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/shell.py#L278-L356 | def do_attr(self, args):
"""Get or set the state for a visa attribute.
List all attributes:
attr
Get an attribute state:
attr <name>
Set an attribute state:
attr <name> <state>
"""
if not self.current:
print('There ar... | [
"def",
"do_attr",
"(",
"self",
",",
"args",
")",
":",
"if",
"not",
"self",
".",
"current",
":",
"print",
"(",
"'There are no resources in use. Use the command \"open\".'",
")",
"return",
"args",
"=",
"args",
".",
"strip",
"(",
")",
"if",
"not",
"args",
":",
... | Get or set the state for a visa attribute.
List all attributes:
attr
Get an attribute state:
attr <name>
Set an attribute state:
attr <name> <state> | [
"Get",
"or",
"set",
"the",
"state",
"for",
"a",
"visa",
"attribute",
"."
] | python | train |
secnot/rectpack | rectpack/packer.py | https://github.com/secnot/rectpack/blob/21d46be48fd453500ea49de699bc9eabc427bdf7/rectpack/packer.py#L404-L420 | def _find_best_fit(self, pbin):
"""
Return best fitness rectangle from rectangles packing _sorted_rect list
Arguments:
pbin (PackingAlgorithm): Packing bin
Returns:
key of the rectangle with best fitness
"""
fit = ((pbin.fitness(r[0], r[1]), k) f... | [
"def",
"_find_best_fit",
"(",
"self",
",",
"pbin",
")",
":",
"fit",
"=",
"(",
"(",
"pbin",
".",
"fitness",
"(",
"r",
"[",
"0",
"]",
",",
"r",
"[",
"1",
"]",
")",
",",
"k",
")",
"for",
"k",
",",
"r",
"in",
"self",
".",
"_sorted_rect",
".",
"... | Return best fitness rectangle from rectangles packing _sorted_rect list
Arguments:
pbin (PackingAlgorithm): Packing bin
Returns:
key of the rectangle with best fitness | [
"Return",
"best",
"fitness",
"rectangle",
"from",
"rectangles",
"packing",
"_sorted_rect",
"list"
] | python | train |
littlemo/moear-api-common | moear_api_common/utils/img.py | https://github.com/littlemo/moear-api-common/blob/2a89a052d92592dd8e67bd50ec2fadc0219ac5d0/moear_api_common/utils/img.py#L5-L64 | def rescale_image(
data, maxsizeb=4000000, dimen=None,
png2jpg=False, graying=True, reduceto=(600, 800)):
'''
若 ``png2jpg`` 为 ``True`` 则将图片转换为 ``JPEG`` 格式,所有透明像素被设置为
*白色* 。确保结果图片尺寸小于 ``maxsizeb`` 的约束限制。
如果 ``dimen`` 不为空,则生成一个相应约束的缩略图。依据 ``dimen`` 的类型,设置约束为
``width=dimen, height=dime... | [
"def",
"rescale_image",
"(",
"data",
",",
"maxsizeb",
"=",
"4000000",
",",
"dimen",
"=",
"None",
",",
"png2jpg",
"=",
"False",
",",
"graying",
"=",
"True",
",",
"reduceto",
"=",
"(",
"600",
",",
"800",
")",
")",
":",
"if",
"not",
"isinstance",
"(",
... | 若 ``png2jpg`` 为 ``True`` 则将图片转换为 ``JPEG`` 格式,所有透明像素被设置为
*白色* 。确保结果图片尺寸小于 ``maxsizeb`` 的约束限制。
如果 ``dimen`` 不为空,则生成一个相应约束的缩略图。依据 ``dimen`` 的类型,设置约束为
``width=dimen, height=dimen`` 或者 ``width, height = dimen``
:param data: 原始图片字节数据
:type data: bytes or io.BytesIO
:param int maxsizeb: 文件大小约束,单位:字节
... | [
"若",
"png2jpg",
"为",
"True",
"则将图片转换为",
"JPEG",
"格式,所有透明像素被设置为",
"*",
"白色",
"*",
"。确保结果图片尺寸小于",
"maxsizeb",
"的约束限制。"
] | python | train |
merll/docker-map | dockermap/map/policy/utils.py | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/policy/utils.py#L54-L78 | def get_shared_volume_path(container_map, vol, instance=None):
"""
Resolves a volume alias of a container configuration or a tuple of two paths to the host and container paths.
:param container_map: Container map.
:type container_map: dockermap.map.config.main.ContainerMap
:param vol: SharedVolume ... | [
"def",
"get_shared_volume_path",
"(",
"container_map",
",",
"vol",
",",
"instance",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"vol",
",",
"HostVolume",
")",
":",
"c_path",
"=",
"resolve_value",
"(",
"vol",
".",
"path",
")",
"if",
"is_path",
"(",
"c... | Resolves a volume alias of a container configuration or a tuple of two paths to the host and container paths.
:param container_map: Container map.
:type container_map: dockermap.map.config.main.ContainerMap
:param vol: SharedVolume or HostVolume tuple.
:type vol: dockermap.map.input.HostVolume | docker... | [
"Resolves",
"a",
"volume",
"alias",
"of",
"a",
"container",
"configuration",
"or",
"a",
"tuple",
"of",
"two",
"paths",
"to",
"the",
"host",
"and",
"container",
"paths",
"."
] | python | train |
3ll3d00d/vibe | backend/src/analyser/common/signal.py | https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/analyser/common/signal.py#L252-L277 | def readWav(inputSignalFile, selectedChannel=1, start=None, end=None) -> Signal:
""" reads a wav file into a Signal.
:param inputSignalFile: a path to the input signal file
:param selectedChannel: the channel to read.
:param start: the time to start reading from in HH:mm:ss.SSS format.
:param end: t... | [
"def",
"readWav",
"(",
"inputSignalFile",
",",
"selectedChannel",
"=",
"1",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
"->",
"Signal",
":",
"def",
"asFrames",
"(",
"time",
",",
"fs",
")",
":",
"hours",
",",
"minutes",
",",
"seconds",
"=... | reads a wav file into a Signal.
:param inputSignalFile: a path to the input signal file
:param selectedChannel: the channel to read.
:param start: the time to start reading from in HH:mm:ss.SSS format.
:param end: the time to end reading from in HH:mm:ss.SSS format.
:returns: Signal. | [
"reads",
"a",
"wav",
"file",
"into",
"a",
"Signal",
".",
":",
"param",
"inputSignalFile",
":",
"a",
"path",
"to",
"the",
"input",
"signal",
"file",
":",
"param",
"selectedChannel",
":",
"the",
"channel",
"to",
"read",
".",
":",
"param",
"start",
":",
"... | python | train |
wmayner/pyphi | pyphi/cache.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/cache.py#L426-L458 | def method(cache_name, key_prefix=None):
"""Caching decorator for object-level method caches.
Cache key generation is delegated to the cache.
Args:
cache_name (str): The name of the (already-instantiated) cache
on the decorated object which should be used to store results
o... | [
"def",
"method",
"(",
"cache_name",
",",
"key_prefix",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"if",
"(",
"func",
".",
"__name__",
"in",
"[",
"'cause_repertoire'",
",",
"'effect_repertoire'",
"]",
"and",
"not",
"config",
".",
"C... | Caching decorator for object-level method caches.
Cache key generation is delegated to the cache.
Args:
cache_name (str): The name of the (already-instantiated) cache
on the decorated object which should be used to store results
of this method.
*key_prefix: A constant t... | [
"Caching",
"decorator",
"for",
"object",
"-",
"level",
"method",
"caches",
"."
] | python | train |
not-na/peng3d | peng3d/gui/button.py | https://github.com/not-na/peng3d/blob/1151be665b26cc8a479f6307086ba919e4d32d85/peng3d/gui/button.py#L126-L146 | def getColors(self):
"""
Overrideable function that generates the colors to be used by various borderstyles.
Should return a 5-tuple of ``(bg,o,i,s,h)``\ .
``bg`` is the base color of the background.
``o`` is the outer color, it is usually the same as t... | [
"def",
"getColors",
"(",
"self",
")",
":",
"bg",
"=",
"self",
".",
"submenu",
".",
"bg",
"[",
":",
"3",
"]",
"if",
"isinstance",
"(",
"self",
".",
"submenu",
".",
"bg",
",",
"list",
")",
"or",
"isinstance",
"(",
"self",
".",
"submenu",
".",
"bg",... | Overrideable function that generates the colors to be used by various borderstyles.
Should return a 5-tuple of ``(bg,o,i,s,h)``\ .
``bg`` is the base color of the background.
``o`` is the outer color, it is usually the same as the background color.
``i... | [
"Overrideable",
"function",
"that",
"generates",
"the",
"colors",
"to",
"be",
"used",
"by",
"various",
"borderstyles",
".",
"Should",
"return",
"a",
"5",
"-",
"tuple",
"of",
"(",
"bg",
"o",
"i",
"s",
"h",
")",
"\\",
".",
"bg",
"is",
"the",
"base",
"c... | python | test |
Cairnarvon/uptime | src/__init__.py | https://github.com/Cairnarvon/uptime/blob/1ddfd06bb300c00e6dc4bd2a9ddf9bf1aa27b1bb/src/__init__.py#L301-L323 | def _uptime_windows():
"""
Returns uptime in seconds or None, on Windows. Warning: may return
incorrect answers after 49.7 days on versions older than Vista.
"""
if hasattr(ctypes, 'windll') and hasattr(ctypes.windll, 'kernel32'):
lib = ctypes.windll.kernel32
else:
try:
... | [
"def",
"_uptime_windows",
"(",
")",
":",
"if",
"hasattr",
"(",
"ctypes",
",",
"'windll'",
")",
"and",
"hasattr",
"(",
"ctypes",
".",
"windll",
",",
"'kernel32'",
")",
":",
"lib",
"=",
"ctypes",
".",
"windll",
".",
"kernel32",
"else",
":",
"try",
":",
... | Returns uptime in seconds or None, on Windows. Warning: may return
incorrect answers after 49.7 days on versions older than Vista. | [
"Returns",
"uptime",
"in",
"seconds",
"or",
"None",
"on",
"Windows",
".",
"Warning",
":",
"may",
"return",
"incorrect",
"answers",
"after",
"49",
".",
"7",
"days",
"on",
"versions",
"older",
"than",
"Vista",
"."
] | python | valid |
jmgilman/Neolib | neolib/pyamf/amf3.py | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/amf3.py#L713-L721 | def addProxyObject(self, obj, proxied):
"""
Stores a reference to the unproxied and proxied versions of C{obj} for
later retrieval.
@since: 0.6
"""
self.proxied_objects[id(obj)] = proxied
self.proxied_objects[id(proxied)] = obj | [
"def",
"addProxyObject",
"(",
"self",
",",
"obj",
",",
"proxied",
")",
":",
"self",
".",
"proxied_objects",
"[",
"id",
"(",
"obj",
")",
"]",
"=",
"proxied",
"self",
".",
"proxied_objects",
"[",
"id",
"(",
"proxied",
")",
"]",
"=",
"obj"
] | Stores a reference to the unproxied and proxied versions of C{obj} for
later retrieval.
@since: 0.6 | [
"Stores",
"a",
"reference",
"to",
"the",
"unproxied",
"and",
"proxied",
"versions",
"of",
"C",
"{",
"obj",
"}",
"for",
"later",
"retrieval",
"."
] | python | train |
freshbooks/refreshbooks | refreshbooks/api.py | https://github.com/freshbooks/refreshbooks/blob/cfd65ecd38cb6be3b61dbf6a01f93800603f34b1/refreshbooks/api.py#L94-L120 | def TokenClient(
domain,
token,
user_agent=None,
request_encoder=default_request_encoder,
response_decoder=default_response_decoder,
):
"""Creates a Freshbooks client for a freshbooks domain, using
token-based auth.
The optional request_encoder and response_decoder parameters can be... | [
"def",
"TokenClient",
"(",
"domain",
",",
"token",
",",
"user_agent",
"=",
"None",
",",
"request_encoder",
"=",
"default_request_encoder",
",",
"response_decoder",
"=",
"default_response_decoder",
",",
")",
":",
"return",
"AuthorizingClient",
"(",
"domain",
",",
"... | Creates a Freshbooks client for a freshbooks domain, using
token-based auth.
The optional request_encoder and response_decoder parameters can be
passed the logging_request_encoder and logging_response_decoder objects
from this module, or custom encoders, to aid debugging or change the
behaviour... | [
"Creates",
"a",
"Freshbooks",
"client",
"for",
"a",
"freshbooks",
"domain",
"using",
"token",
"-",
"based",
"auth",
".",
"The",
"optional",
"request_encoder",
"and",
"response_decoder",
"parameters",
"can",
"be",
"passed",
"the",
"logging_request_encoder",
"and",
... | python | train |
pyvisa/pyvisa-sim | pyvisa-sim/devices.py | https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/devices.py#L214-L250 | def write(self, data):
"""Write data into the device input buffer.
:param data: single element byte
:type data: bytes
"""
logger.debug('Writing into device input buffer: %r' % data)
if not isinstance(data, bytes):
raise TypeError('data must be an instance of ... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"logger",
".",
"debug",
"(",
"'Writing into device input buffer: %r'",
"%",
"data",
")",
"if",
"not",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"raise",
"TypeError",
"(",
"'data must be an instance o... | Write data into the device input buffer.
:param data: single element byte
:type data: bytes | [
"Write",
"data",
"into",
"the",
"device",
"input",
"buffer",
"."
] | python | train |
planetarypy/planetaryimage | planetaryimage/pds3image.py | https://github.com/planetarypy/planetaryimage/blob/ee9aef4746ff7a003b1457565acb13f5f1db0375/planetaryimage/pds3image.py#L336-L341 | def dtype(self):
"""Pixel data type."""
try:
return self.data.dtype
except AttributeError:
return numpy.dtype('%s%d' % (self._sample_type, self._sample_bytes)) | [
"def",
"dtype",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"data",
".",
"dtype",
"except",
"AttributeError",
":",
"return",
"numpy",
".",
"dtype",
"(",
"'%s%d'",
"%",
"(",
"self",
".",
"_sample_type",
",",
"self",
".",
"_sample_bytes",
"... | Pixel data type. | [
"Pixel",
"data",
"type",
"."
] | python | train |
ChargePoint/pydnp3 | examples/master_cmd.py | https://github.com/ChargePoint/pydnp3/blob/5bcd8240d1fc0aa1579e71f2efcab63b4c61c547/examples/master_cmd.py#L123-L125 | def do_restart(self, line):
"""Request that the Outstation perform a cold restart. Command syntax is: restart"""
self.application.master.Restart(opendnp3.RestartType.COLD, restart_callback) | [
"def",
"do_restart",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"application",
".",
"master",
".",
"Restart",
"(",
"opendnp3",
".",
"RestartType",
".",
"COLD",
",",
"restart_callback",
")"
] | Request that the Outstation perform a cold restart. Command syntax is: restart | [
"Request",
"that",
"the",
"Outstation",
"perform",
"a",
"cold",
"restart",
".",
"Command",
"syntax",
"is",
":",
"restart"
] | python | valid |
scidash/sciunit | sciunit/models/backends.py | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L64-L72 | def init_disk_cache(self):
"""Initialize the on-disk version of the cache."""
try:
# Cleanup old disk cache files
path = self.disk_cache_location
os.remove(path)
except Exception:
pass
self.disk_cache_location = os.path.join(tempfile.mkdtem... | [
"def",
"init_disk_cache",
"(",
"self",
")",
":",
"try",
":",
"# Cleanup old disk cache files",
"path",
"=",
"self",
".",
"disk_cache_location",
"os",
".",
"remove",
"(",
"path",
")",
"except",
"Exception",
":",
"pass",
"self",
".",
"disk_cache_location",
"=",
... | Initialize the on-disk version of the cache. | [
"Initialize",
"the",
"on",
"-",
"disk",
"version",
"of",
"the",
"cache",
"."
] | python | train |
halcy/Mastodon.py | mastodon/Mastodon.py | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1622-L1630 | def status_mute(self, id):
"""
Mute notifications for a status.
Returns a `toot dict`_ with the now muted status
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/mute'.format(str(id))
return self.__api_request('POST', url) | [
"def",
"status_mute",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}/mute'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POS... | Mute notifications for a status.
Returns a `toot dict`_ with the now muted status | [
"Mute",
"notifications",
"for",
"a",
"status",
"."
] | python | train |
tylerbutler/engineer | engineer/devtools/theme_tools.py | https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/devtools/theme_tools.py#L20-L42 | def compile_theme(theme_id=None):
"""Compiles a theme."""
from engineer.processors import convert_less
from engineer.themes import ThemeManager
if theme_id is None:
themes = ThemeManager.themes().values()
else:
themes = [ThemeManager.theme(theme_id)]
with(indent(2)):
pu... | [
"def",
"compile_theme",
"(",
"theme_id",
"=",
"None",
")",
":",
"from",
"engineer",
".",
"processors",
"import",
"convert_less",
"from",
"engineer",
".",
"themes",
"import",
"ThemeManager",
"if",
"theme_id",
"is",
"None",
":",
"themes",
"=",
"ThemeManager",
".... | Compiles a theme. | [
"Compiles",
"a",
"theme",
"."
] | python | train |
jay-johnson/network-pipeline | network_pipeline/connect_forwarder.py | https://github.com/jay-johnson/network-pipeline/blob/4e53ae13fe12085e0cf2e5e1aff947368f4f1ffa/network_pipeline/connect_forwarder.py#L10-L56 | def connect_forwarder(forward_host=None,
forward_port=None,
max_retries=-1,
sleep_interval=1.0):
"""connect_forwarder
:param forward_host: host for receiving forwarded packets
:param forward_port: port for the forwarded packets
:param ma... | [
"def",
"connect_forwarder",
"(",
"forward_host",
"=",
"None",
",",
"forward_port",
"=",
"None",
",",
"max_retries",
"=",
"-",
"1",
",",
"sleep_interval",
"=",
"1.0",
")",
":",
"forward_skt",
"=",
"None",
"retry_count",
"=",
"0",
"if",
"max_retries",
"==",
... | connect_forwarder
:param forward_host: host for receiving forwarded packets
:param forward_port: port for the forwarded packets
:param max_retries: retries, -1 = infinite
:param sleep_interval: how often to retry in this loop | [
"connect_forwarder"
] | python | train |
jeffh/rpi_courses | rpi_courses/utils.py | https://github.com/jeffh/rpi_courses/blob/c97176f73f866f112c785910ebf3ff8a790e8e9a/rpi_courses/utils.py#L6-L19 | def safeInt(n, warn_only=False):
"""Throws an exception if the number starts with a 0 (may be significant).
If the value cannot be converted to an int, it is returned as is.
"""
if str(n).startswith('0'):
if not warn_only:
raise TypeError("Unsafe Int: " + str(n))
print "Unsa... | [
"def",
"safeInt",
"(",
"n",
",",
"warn_only",
"=",
"False",
")",
":",
"if",
"str",
"(",
"n",
")",
".",
"startswith",
"(",
"'0'",
")",
":",
"if",
"not",
"warn_only",
":",
"raise",
"TypeError",
"(",
"\"Unsafe Int: \"",
"+",
"str",
"(",
"n",
")",
")",... | Throws an exception if the number starts with a 0 (may be significant).
If the value cannot be converted to an int, it is returned as is. | [
"Throws",
"an",
"exception",
"if",
"the",
"number",
"starts",
"with",
"a",
"0",
"(",
"may",
"be",
"significant",
")",
"."
] | python | train |
Neurita/boyle | boyle/nifti/sets.py | https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/sets.py#L199-L272 | def to_matrix(self, smooth_fwhm=0, outdtype=None):
"""Return numpy.ndarray with the masked or flatten image data and
the relevant information (mask indices and volume shape).
Parameters
----------
smooth__fwhm: int
Integer indicating the size of the FWHM Gaussian ... | [
"def",
"to_matrix",
"(",
"self",
",",
"smooth_fwhm",
"=",
"0",
",",
"outdtype",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"all_compatible",
":",
"raise",
"ValueError",
"(",
"\"`self.all_compatible` must be True in order to use this function.\"",
")",
"if",
... | Return numpy.ndarray with the masked or flatten image data and
the relevant information (mask indices and volume shape).
Parameters
----------
smooth__fwhm: int
Integer indicating the size of the FWHM Gaussian smoothing kernel
to smooth the subject volumes bef... | [
"Return",
"numpy",
".",
"ndarray",
"with",
"the",
"masked",
"or",
"flatten",
"image",
"data",
"and",
"the",
"relevant",
"information",
"(",
"mask",
"indices",
"and",
"volume",
"shape",
")",
"."
] | python | valid |
log2timeline/plaso | plaso/parsers/sqlite.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/sqlite.py#L32-L93 | def CacheQueryResults(
self, sql_results, attribute_name, key_name, column_names):
"""Build a dictionary object based on a SQL command.
This function will take a SQL command, execute it and for
each resulting row it will store a key in a dictionary.
An example::
sql_results = A SQL result... | [
"def",
"CacheQueryResults",
"(",
"self",
",",
"sql_results",
",",
"attribute_name",
",",
"key_name",
",",
"column_names",
")",
":",
"row",
"=",
"sql_results",
".",
"fetchone",
"(",
")",
"if",
"not",
"row",
":",
"return",
"# Note that pysqlite does not accept a Uni... | Build a dictionary object based on a SQL command.
This function will take a SQL command, execute it and for
each resulting row it will store a key in a dictionary.
An example::
sql_results = A SQL result object after executing the
SQL command: 'SELECT foo, bla, bar FROM my_table... | [
"Build",
"a",
"dictionary",
"object",
"based",
"on",
"a",
"SQL",
"command",
"."
] | python | train |
ianmiell/shutit | shutit_class.py | https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1390-L1419 | def insert_text(self,
text,
fname,
pattern=None,
expect=None,
shutit_pexpect_child=None,
before=False,
force=False,
note=None,
replace=False,
line_ori... | [
"def",
"insert_text",
"(",
"self",
",",
"text",
",",
"fname",
",",
"pattern",
"=",
"None",
",",
"expect",
"=",
"None",
",",
"shutit_pexpect_child",
"=",
"None",
",",
"before",
"=",
"False",
",",
"force",
"=",
"False",
",",
"note",
"=",
"None",
",",
"... | Insert a chunk of text at the end of a file, or after (or before) the first matching pattern
in given file fname.
See change_text | [
"Insert",
"a",
"chunk",
"of",
"text",
"at",
"the",
"end",
"of",
"a",
"file",
"or",
"after",
"(",
"or",
"before",
")",
"the",
"first",
"matching",
"pattern",
"in",
"given",
"file",
"fname",
".",
"See",
"change_text"
] | python | train |
Autodesk/aomi | aomi/model/resource.py | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/model/resource.py#L31-L51 | def thaw(self, tmp_dir):
"""Will perform some validation and copy a
decrypted secret to it's final location"""
for sfile in self.secrets():
src_file = "%s/%s" % (tmp_dir, sfile)
err_msg = "%s secret missing from icefile" % (self)
if not os.path.exists(src_file... | [
"def",
"thaw",
"(",
"self",
",",
"tmp_dir",
")",
":",
"for",
"sfile",
"in",
"self",
".",
"secrets",
"(",
")",
":",
"src_file",
"=",
"\"%s/%s\"",
"%",
"(",
"tmp_dir",
",",
"sfile",
")",
"err_msg",
"=",
"\"%s secret missing from icefile\"",
"%",
"(",
"self... | Will perform some validation and copy a
decrypted secret to it's final location | [
"Will",
"perform",
"some",
"validation",
"and",
"copy",
"a",
"decrypted",
"secret",
"to",
"it",
"s",
"final",
"location"
] | python | train |
whiteclover/dbpy | db/__init__.py | https://github.com/whiteclover/dbpy/blob/3d9ce85f55cfb39cced22081e525f79581b26b3a/db/__init__.py#L94-L107 | def query(sql, args=None, many=None, as_dict=False, key='default'):
"""The connection raw sql query, when select table, show table
to fetch records, it is compatible the dbi execute method::
:param sql string: the sql stamtement like 'select * from %s'
:param args list: Wen set None, will use d... | [
"def",
"query",
"(",
"sql",
",",
"args",
"=",
"None",
",",
"many",
"=",
"None",
",",
"as_dict",
"=",
"False",
",",
"key",
"=",
"'default'",
")",
":",
"database",
"=",
"choice",
"(",
"__db",
"[",
"key",
"+",
"'.slave'",
"]",
")",
"return",
"database... | The connection raw sql query, when select table, show table
to fetch records, it is compatible the dbi execute method::
:param sql string: the sql stamtement like 'select * from %s'
:param args list: Wen set None, will use dbi execute(sql), else
dbi execute(sql, args), the args keep the ori... | [
"The",
"connection",
"raw",
"sql",
"query",
"when",
"select",
"table",
"show",
"table",
"to",
"fetch",
"records",
"it",
"is",
"compatible",
"the",
"dbi",
"execute",
"method",
"::"
] | python | train |
tensorflow/mesh | mesh_tensorflow/ops.py | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1099-L1119 | def make_slices(self, tf_tensor, tensor_shape):
"""Turns a single tf.Tensor into a list of slices, one for each processor.
Args:
tf_tensor: tf.Tensor.
tensor_shape: Shape.
Returns:
list of tf.tensor with length self.size.
"""
tensor_layout = self.tensor_layout(tensor_shape)
s... | [
"def",
"make_slices",
"(",
"self",
",",
"tf_tensor",
",",
"tensor_shape",
")",
":",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"slice_shape",
"=",
"self",
".",
"slice_shape",
"(",
"tensor_shape",
")",
"def",
"my_fn",
"(",
"... | Turns a single tf.Tensor into a list of slices, one for each processor.
Args:
tf_tensor: tf.Tensor.
tensor_shape: Shape.
Returns:
list of tf.tensor with length self.size. | [
"Turns",
"a",
"single",
"tf",
".",
"Tensor",
"into",
"a",
"list",
"of",
"slices",
"one",
"for",
"each",
"processor",
"."
] | python | train |
diffeo/rejester | rejester/workers.py | https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/workers.py#L790-L893 | def do_some_work(self, can_start_more):
'''Run one cycle of the main loop.
If the log child has died, restart it. If any of the worker
children have died, collect their status codes and remove them
from the child set. If there is a worker slot available, start
exactly one chil... | [
"def",
"do_some_work",
"(",
"self",
",",
"can_start_more",
")",
":",
"any_happy_children",
"=",
"False",
"any_sad_children",
"=",
"False",
"any_bored_children",
"=",
"False",
"self",
".",
"debug",
"(",
"'loop'",
",",
"'starting work loop, can_start_more={0!r}'",
".",
... | Run one cycle of the main loop.
If the log child has died, restart it. If any of the worker
children have died, collect their status codes and remove them
from the child set. If there is a worker slot available, start
exactly one child.
:param bool can_start_more: Allowed to ... | [
"Run",
"one",
"cycle",
"of",
"the",
"main",
"loop",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.