repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
MacHu-GWU/single_file_module-project | sfm/iterable.py | size_of_generator | def size_of_generator(generator, memory_efficient=True):
"""Get number of items in a generator function.
- memory_efficient = True, 3 times slower, but memory_efficient.
- memory_efficient = False, faster, but cost more memory.
**中文文档**
计算一个生成器函数中的元素的个数。使用memory_efficient=True的方法可以避免将生成器中的
所有... | python | def size_of_generator(generator, memory_efficient=True):
"""Get number of items in a generator function.
- memory_efficient = True, 3 times slower, but memory_efficient.
- memory_efficient = False, faster, but cost more memory.
**中文文档**
计算一个生成器函数中的元素的个数。使用memory_efficient=True的方法可以避免将生成器中的
所有... | [
"def",
"size_of_generator",
"(",
"generator",
",",
"memory_efficient",
"=",
"True",
")",
":",
"if",
"memory_efficient",
":",
"counter",
"=",
"0",
"for",
"_",
"in",
"generator",
":",
"counter",
"+=",
"1",
"return",
"counter",
"else",
":",
"return",
"len",
"... | Get number of items in a generator function.
- memory_efficient = True, 3 times slower, but memory_efficient.
- memory_efficient = False, faster, but cost more memory.
**中文文档**
计算一个生成器函数中的元素的个数。使用memory_efficient=True的方法可以避免将生成器中的
所有元素放入内存, 但是速度稍慢于memory_efficient=False的方法。 | [
"Get",
"number",
"of",
"items",
"in",
"a",
"generator",
"function",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/iterable.py#L443-L460 | train |
JanHendrikDolling/configvalidator | configvalidator/validators/__init__.py | AndValidator.validate | def validate(self, value):
"""validate function form OrValidator
Returns:
True if at least one of the validators
validate function return True
"""
errors = []
self._used_validator = []
for val in self._validators:
try:
... | python | def validate(self, value):
"""validate function form OrValidator
Returns:
True if at least one of the validators
validate function return True
"""
errors = []
self._used_validator = []
for val in self._validators:
try:
... | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"errors",
"=",
"[",
"]",
"self",
".",
"_used_validator",
"=",
"[",
"]",
"for",
"val",
"in",
"self",
".",
"_validators",
":",
"try",
":",
"val",
".",
"validate",
"(",
"value",
")",
"self",
".",... | validate function form OrValidator
Returns:
True if at least one of the validators
validate function return True | [
"validate",
"function",
"form",
"OrValidator"
] | efde23a9352ae1fd6702b04ad964783ce11cbca5 | https://github.com/JanHendrikDolling/configvalidator/blob/efde23a9352ae1fd6702b04ad964783ce11cbca5/configvalidator/validators/__init__.py#L598-L617 | train |
Godley/MuseParse | MuseParse/classes/ObjectHierarchy/TreeClasses/MeasureNode.py | MeasureNode.GetTotalValue | def GetTotalValue(self):
"""Gets the total value of the bar according to it's time signature"""
value = ""
if hasattr(self, "meter"):
top_value = self.meter.beats
bottom = self.meter.type
fraction = top_value / bottom
if fraction == 1:
... | python | def GetTotalValue(self):
"""Gets the total value of the bar according to it's time signature"""
value = ""
if hasattr(self, "meter"):
top_value = self.meter.beats
bottom = self.meter.type
fraction = top_value / bottom
if fraction == 1:
... | [
"def",
"GetTotalValue",
"(",
"self",
")",
":",
"value",
"=",
"\"\"",
"if",
"hasattr",
"(",
"self",
",",
"\"meter\"",
")",
":",
"top_value",
"=",
"self",
".",
"meter",
".",
"beats",
"bottom",
"=",
"self",
".",
"meter",
".",
"type",
"fraction",
"=",
"t... | Gets the total value of the bar according to it's time signature | [
"Gets",
"the",
"total",
"value",
"of",
"the",
"bar",
"according",
"to",
"it",
"s",
"time",
"signature"
] | 23cecafa1fdc0f2d6a87760553572b459f3c9904 | https://github.com/Godley/MuseParse/blob/23cecafa1fdc0f2d6a87760553572b459f3c9904/MuseParse/classes/ObjectHierarchy/TreeClasses/MeasureNode.py#L133-L151 | train |
Godley/MuseParse | MuseParse/classes/ObjectHierarchy/TreeClasses/MeasureNode.py | MeasureNode.GetLastKey | def GetLastKey(self, voice=1):
"""key as in musical key, not index"""
voice_obj = self.GetChild(voice)
if voice_obj is not None:
key = BackwardSearch(KeyNode, voice_obj, 1)
if key is not None:
return key
else:
if hasattr(self, ... | python | def GetLastKey(self, voice=1):
"""key as in musical key, not index"""
voice_obj = self.GetChild(voice)
if voice_obj is not None:
key = BackwardSearch(KeyNode, voice_obj, 1)
if key is not None:
return key
else:
if hasattr(self, ... | [
"def",
"GetLastKey",
"(",
"self",
",",
"voice",
"=",
"1",
")",
":",
"voice_obj",
"=",
"self",
".",
"GetChild",
"(",
"voice",
")",
"if",
"voice_obj",
"is",
"not",
"None",
":",
"key",
"=",
"BackwardSearch",
"(",
"KeyNode",
",",
"voice_obj",
",",
"1",
"... | key as in musical key, not index | [
"key",
"as",
"in",
"musical",
"key",
"not",
"index"
] | 23cecafa1fdc0f2d6a87760553572b459f3c9904 | https://github.com/Godley/MuseParse/blob/23cecafa1fdc0f2d6a87760553572b459f3c9904/MuseParse/classes/ObjectHierarchy/TreeClasses/MeasureNode.py#L165-L178 | train |
Godley/MuseParse | MuseParse/helpers.py | SplitString | def SplitString(value):
"""simple method that puts in spaces every 10 characters"""
string_length = len(value)
chunks = int(string_length / 10)
string_list = list(value)
lstring = ""
if chunks > 1:
lstring = "\\markup { \n\r \column { "
for i in range(int(chunks)):
l... | python | def SplitString(value):
"""simple method that puts in spaces every 10 characters"""
string_length = len(value)
chunks = int(string_length / 10)
string_list = list(value)
lstring = ""
if chunks > 1:
lstring = "\\markup { \n\r \column { "
for i in range(int(chunks)):
l... | [
"def",
"SplitString",
"(",
"value",
")",
":",
"string_length",
"=",
"len",
"(",
"value",
")",
"chunks",
"=",
"int",
"(",
"string_length",
"/",
"10",
")",
"string_list",
"=",
"list",
"(",
"value",
")",
"lstring",
"=",
"\"\"",
"if",
"chunks",
">",
"1",
... | simple method that puts in spaces every 10 characters | [
"simple",
"method",
"that",
"puts",
"in",
"spaces",
"every",
"10",
"characters"
] | 23cecafa1fdc0f2d6a87760553572b459f3c9904 | https://github.com/Godley/MuseParse/blob/23cecafa1fdc0f2d6a87760553572b459f3c9904/MuseParse/helpers.py#L4-L46 | train |
Godley/MuseParse | MuseParse/helpers.py | NumbersToWords | def NumbersToWords(number):
"""
little function that converts numbers to words. This could be more efficient,
and won't work if the number is bigger than 999 but it's for stave names,
and I doubt any part would have more than 10 staves let alone 999.
"""
units = [
'one',
'two',
... | python | def NumbersToWords(number):
"""
little function that converts numbers to words. This could be more efficient,
and won't work if the number is bigger than 999 but it's for stave names,
and I doubt any part would have more than 10 staves let alone 999.
"""
units = [
'one',
'two',
... | [
"def",
"NumbersToWords",
"(",
"number",
")",
":",
"units",
"=",
"[",
"'one'",
",",
"'two'",
",",
"'three'",
",",
"'four'",
",",
"'five'",
",",
"'six'",
",",
"'seven'",
",",
"'eight'",
",",
"'nine'",
"]",
"tens",
"=",
"[",
"'ten'",
",",
"'twenty'",
",... | little function that converts numbers to words. This could be more efficient,
and won't work if the number is bigger than 999 but it's for stave names,
and I doubt any part would have more than 10 staves let alone 999. | [
"little",
"function",
"that",
"converts",
"numbers",
"to",
"words",
".",
"This",
"could",
"be",
"more",
"efficient",
"and",
"won",
"t",
"work",
"if",
"the",
"number",
"is",
"bigger",
"than",
"999",
"but",
"it",
"s",
"for",
"stave",
"names",
"and",
"I",
... | 23cecafa1fdc0f2d6a87760553572b459f3c9904 | https://github.com/Godley/MuseParse/blob/23cecafa1fdc0f2d6a87760553572b459f3c9904/MuseParse/helpers.py#L63-L108 | train |
Godley/MuseParse | MuseParse/classes/ObjectHierarchy/TreeClasses/PartNode.py | PartNode.CheckTotals | def CheckTotals(self):
"""method to calculate the maximum total lilypond value for a measure without a time signature"""
staves = self.GetChildrenIndexes()
for staff in staves:
child = self.getStaff(staff)
child.CheckTotals() | python | def CheckTotals(self):
"""method to calculate the maximum total lilypond value for a measure without a time signature"""
staves = self.GetChildrenIndexes()
for staff in staves:
child = self.getStaff(staff)
child.CheckTotals() | [
"def",
"CheckTotals",
"(",
"self",
")",
":",
"staves",
"=",
"self",
".",
"GetChildrenIndexes",
"(",
")",
"for",
"staff",
"in",
"staves",
":",
"child",
"=",
"self",
".",
"getStaff",
"(",
"staff",
")",
"child",
".",
"CheckTotals",
"(",
")"
] | method to calculate the maximum total lilypond value for a measure without a time signature | [
"method",
"to",
"calculate",
"the",
"maximum",
"total",
"lilypond",
"value",
"for",
"a",
"measure",
"without",
"a",
"time",
"signature"
] | 23cecafa1fdc0f2d6a87760553572b459f3c9904 | https://github.com/Godley/MuseParse/blob/23cecafa1fdc0f2d6a87760553572b459f3c9904/MuseParse/classes/ObjectHierarchy/TreeClasses/PartNode.py#L60-L65 | train |
Godley/MuseParse | MuseParse/classes/ObjectHierarchy/TreeClasses/PartNode.py | PartNode.CheckPreviousBarline | def CheckPreviousBarline(self, staff):
"""method which checks the bar before the current for changes we need to make to it's barlines"""
measure_before_last = self.getMeasureAtPosition(-2, staff)
last_measure = self.getMeasureAtPosition(-1, staff)
if last_measure is not None and measure_... | python | def CheckPreviousBarline(self, staff):
"""method which checks the bar before the current for changes we need to make to it's barlines"""
measure_before_last = self.getMeasureAtPosition(-2, staff)
last_measure = self.getMeasureAtPosition(-1, staff)
if last_measure is not None and measure_... | [
"def",
"CheckPreviousBarline",
"(",
"self",
",",
"staff",
")",
":",
"measure_before_last",
"=",
"self",
".",
"getMeasureAtPosition",
"(",
"-",
"2",
",",
"staff",
")",
"last_measure",
"=",
"self",
".",
"getMeasureAtPosition",
"(",
"-",
"1",
",",
"staff",
")",... | method which checks the bar before the current for changes we need to make to it's barlines | [
"method",
"which",
"checks",
"the",
"bar",
"before",
"the",
"current",
"for",
"changes",
"we",
"need",
"to",
"make",
"to",
"it",
"s",
"barlines"
] | 23cecafa1fdc0f2d6a87760553572b459f3c9904 | https://github.com/Godley/MuseParse/blob/23cecafa1fdc0f2d6a87760553572b459f3c9904/MuseParse/classes/ObjectHierarchy/TreeClasses/PartNode.py#L78-L91 | train |
eweast/BencodePy | build/lib/bencodepy/decoder.py | Decoder.__parse | def __parse(self) -> object:
"""Selects the appropriate method to decode next bencode element and returns the result."""
char = self.data[self.idx: self.idx + 1]
if char in [b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'0']:
str_len = int(self.__read_to(b':'))
r... | python | def __parse(self) -> object:
"""Selects the appropriate method to decode next bencode element and returns the result."""
char = self.data[self.idx: self.idx + 1]
if char in [b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'0']:
str_len = int(self.__read_to(b':'))
r... | [
"def",
"__parse",
"(",
"self",
")",
"->",
"object",
":",
"char",
"=",
"self",
".",
"data",
"[",
"self",
".",
"idx",
":",
"self",
".",
"idx",
"+",
"1",
"]",
"if",
"char",
"in",
"[",
"b'1'",
",",
"b'2'",
",",
"b'3'",
",",
"b'4'",
",",
"b'5'",
"... | Selects the appropriate method to decode next bencode element and returns the result. | [
"Selects",
"the",
"appropriate",
"method",
"to",
"decode",
"next",
"bencode",
"element",
"and",
"returns",
"the",
"result",
"."
] | a9c145bd087c61dd8fb28a9dfad46d085c8b8290 | https://github.com/eweast/BencodePy/blob/a9c145bd087c61dd8fb28a9dfad46d085c8b8290/build/lib/bencodepy/decoder.py#L33-L50 | train |
eweast/BencodePy | build/lib/bencodepy/decoder.py | Decoder.decode | def decode(self) -> Iterable:
"""Start of decode process. Returns final results."""
if self.data[0:1] not in (b'd', b'l'):
return self.__wrap_with_tuple()
return self.__parse() | python | def decode(self) -> Iterable:
"""Start of decode process. Returns final results."""
if self.data[0:1] not in (b'd', b'l'):
return self.__wrap_with_tuple()
return self.__parse() | [
"def",
"decode",
"(",
"self",
")",
"->",
"Iterable",
":",
"if",
"self",
".",
"data",
"[",
"0",
":",
"1",
"]",
"not",
"in",
"(",
"b'd'",
",",
"b'l'",
")",
":",
"return",
"self",
".",
"__wrap_with_tuple",
"(",
")",
"return",
"self",
".",
"__parse",
... | Start of decode process. Returns final results. | [
"Start",
"of",
"decode",
"process",
".",
"Returns",
"final",
"results",
"."
] | a9c145bd087c61dd8fb28a9dfad46d085c8b8290 | https://github.com/eweast/BencodePy/blob/a9c145bd087c61dd8fb28a9dfad46d085c8b8290/build/lib/bencodepy/decoder.py#L52-L56 | train |
eweast/BencodePy | build/lib/bencodepy/decoder.py | Decoder.__wrap_with_tuple | def __wrap_with_tuple(self) -> tuple:
"""Returns a tuple of all nested bencode elements."""
l = list()
length = len(self.data)
while self.idx < length:
l.append(self.__parse())
return tuple(l) | python | def __wrap_with_tuple(self) -> tuple:
"""Returns a tuple of all nested bencode elements."""
l = list()
length = len(self.data)
while self.idx < length:
l.append(self.__parse())
return tuple(l) | [
"def",
"__wrap_with_tuple",
"(",
"self",
")",
"->",
"tuple",
":",
"l",
"=",
"list",
"(",
")",
"length",
"=",
"len",
"(",
"self",
".",
"data",
")",
"while",
"self",
".",
"idx",
"<",
"length",
":",
"l",
".",
"append",
"(",
"self",
".",
"__parse",
"... | Returns a tuple of all nested bencode elements. | [
"Returns",
"a",
"tuple",
"of",
"all",
"nested",
"bencode",
"elements",
"."
] | a9c145bd087c61dd8fb28a9dfad46d085c8b8290 | https://github.com/eweast/BencodePy/blob/a9c145bd087c61dd8fb28a9dfad46d085c8b8290/build/lib/bencodepy/decoder.py#L58-L64 | train |
eweast/BencodePy | build/lib/bencodepy/decoder.py | Decoder.__parse_dict | def __parse_dict(self) -> OrderedDict:
"""Returns an Ordered Dictionary of nested bencode elements."""
self.idx += 1
d = OrderedDict()
key_name = None
while self.data[self.idx: self.idx + 1] != b'e':
if key_name is None:
key_name = self.__parse()
... | python | def __parse_dict(self) -> OrderedDict:
"""Returns an Ordered Dictionary of nested bencode elements."""
self.idx += 1
d = OrderedDict()
key_name = None
while self.data[self.idx: self.idx + 1] != b'e':
if key_name is None:
key_name = self.__parse()
... | [
"def",
"__parse_dict",
"(",
"self",
")",
"->",
"OrderedDict",
":",
"self",
".",
"idx",
"+=",
"1",
"d",
"=",
"OrderedDict",
"(",
")",
"key_name",
"=",
"None",
"while",
"self",
".",
"data",
"[",
"self",
".",
"idx",
":",
"self",
".",
"idx",
"+",
"1",
... | Returns an Ordered Dictionary of nested bencode elements. | [
"Returns",
"an",
"Ordered",
"Dictionary",
"of",
"nested",
"bencode",
"elements",
"."
] | a9c145bd087c61dd8fb28a9dfad46d085c8b8290 | https://github.com/eweast/BencodePy/blob/a9c145bd087c61dd8fb28a9dfad46d085c8b8290/build/lib/bencodepy/decoder.py#L66-L78 | train |
eweast/BencodePy | build/lib/bencodepy/decoder.py | Decoder.__parse_list | def __parse_list(self) -> list:
"""Returns an list of nested bencode elements."""
self.idx += 1
l = []
while self.data[self.idx: self.idx + 1] != b'e':
l.append(self.__parse())
self.idx += 1
return l | python | def __parse_list(self) -> list:
"""Returns an list of nested bencode elements."""
self.idx += 1
l = []
while self.data[self.idx: self.idx + 1] != b'e':
l.append(self.__parse())
self.idx += 1
return l | [
"def",
"__parse_list",
"(",
"self",
")",
"->",
"list",
":",
"self",
".",
"idx",
"+=",
"1",
"l",
"=",
"[",
"]",
"while",
"self",
".",
"data",
"[",
"self",
".",
"idx",
":",
"self",
".",
"idx",
"+",
"1",
"]",
"!=",
"b'e'",
":",
"l",
".",
"append... | Returns an list of nested bencode elements. | [
"Returns",
"an",
"list",
"of",
"nested",
"bencode",
"elements",
"."
] | a9c145bd087c61dd8fb28a9dfad46d085c8b8290 | https://github.com/eweast/BencodePy/blob/a9c145bd087c61dd8fb28a9dfad46d085c8b8290/build/lib/bencodepy/decoder.py#L80-L87 | train |
Godley/MuseParse | MuseParse/classes/ObjectHierarchy/TreeClasses/BaseTree.py | Node.PopAllChildren | def PopAllChildren(self):
'''
Method to remove and return all children of current node
:return: list of children
'''
indexes = self.GetChildrenIndexes()
children = []
for c in indexes:
child = self.PopChild(c)
children.append(child)
... | python | def PopAllChildren(self):
'''
Method to remove and return all children of current node
:return: list of children
'''
indexes = self.GetChildrenIndexes()
children = []
for c in indexes:
child = self.PopChild(c)
children.append(child)
... | [
"def",
"PopAllChildren",
"(",
"self",
")",
":",
"indexes",
"=",
"self",
".",
"GetChildrenIndexes",
"(",
")",
"children",
"=",
"[",
"]",
"for",
"c",
"in",
"indexes",
":",
"child",
"=",
"self",
".",
"PopChild",
"(",
"c",
")",
"children",
".",
"append",
... | Method to remove and return all children of current node
:return: list of children | [
"Method",
"to",
"remove",
"and",
"return",
"all",
"children",
"of",
"current",
"node"
] | 23cecafa1fdc0f2d6a87760553572b459f3c9904 | https://github.com/Godley/MuseParse/blob/23cecafa1fdc0f2d6a87760553572b459f3c9904/MuseParse/classes/ObjectHierarchy/TreeClasses/BaseTree.py#L215-L226 | train |
vasilcovsky/pytinypng | pytinypng/pytinypng.py | _process_file | def _process_file(input_file, output_file, apikey):
"""Shrinks input_file to output_file.
This function should be used only inside process_directory.
It takes input_file, tries to shrink it and if shrink was successful
save compressed image to output_file. Otherwise raise exception.
@return compre... | python | def _process_file(input_file, output_file, apikey):
"""Shrinks input_file to output_file.
This function should be used only inside process_directory.
It takes input_file, tries to shrink it and if shrink was successful
save compressed image to output_file. Otherwise raise exception.
@return compre... | [
"def",
"_process_file",
"(",
"input_file",
",",
"output_file",
",",
"apikey",
")",
":",
"bytes_",
"=",
"read_binary",
"(",
"input_file",
")",
"compressed",
"=",
"shrink",
"(",
"bytes_",
",",
"apikey",
")",
"if",
"compressed",
".",
"success",
"and",
"compress... | Shrinks input_file to output_file.
This function should be used only inside process_directory.
It takes input_file, tries to shrink it and if shrink was successful
save compressed image to output_file. Otherwise raise exception.
@return compressed: PNGResponse | [
"Shrinks",
"input_file",
"to",
"output_file",
"."
] | ac633e4aa41122c49a806f411e43a76d8f73058e | https://github.com/vasilcovsky/pytinypng/blob/ac633e4aa41122c49a806f411e43a76d8f73058e/pytinypng/pytinypng.py#L29-L49 | train |
vasilcovsky/pytinypng | pytinypng/pytinypng.py | process_directory | def process_directory(source, target, apikey, handler, overwrite=False):
"""Optimize and save png files form source to target directory.
@param source: path to input directory
@param target: path to output directory
@param handler: callback holder, instance of handlers.BaseHandler
@param overwrite:... | python | def process_directory(source, target, apikey, handler, overwrite=False):
"""Optimize and save png files form source to target directory.
@param source: path to input directory
@param target: path to output directory
@param handler: callback holder, instance of handlers.BaseHandler
@param overwrite:... | [
"def",
"process_directory",
"(",
"source",
",",
"target",
",",
"apikey",
",",
"handler",
",",
"overwrite",
"=",
"False",
")",
":",
"handler",
".",
"on_start",
"(",
")",
"attempts",
"=",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
"input_files",
"=",
"fi... | Optimize and save png files form source to target directory.
@param source: path to input directory
@param target: path to output directory
@param handler: callback holder, instance of handlers.BaseHandler
@param overwrite: boolean flag to allow overwrite already existing
files in... | [
"Optimize",
"and",
"save",
"png",
"files",
"form",
"source",
"to",
"target",
"directory",
"."
] | ac633e4aa41122c49a806f411e43a76d8f73058e | https://github.com/vasilcovsky/pytinypng/blob/ac633e4aa41122c49a806f411e43a76d8f73058e/pytinypng/pytinypng.py#L52-L104 | train |
vasilcovsky/pytinypng | pytinypng/pytinypng.py | _main | def _main(args):
"""Batch compression.
args contains:
* input - path to input directory
* output - path to output directory or None
* apikey - TinyPNG API key
* overwrite - boolean flag
"""
if not args.apikey:
print("\nPlease provide TinyPNG API key")
print("To obta... | python | def _main(args):
"""Batch compression.
args contains:
* input - path to input directory
* output - path to output directory or None
* apikey - TinyPNG API key
* overwrite - boolean flag
"""
if not args.apikey:
print("\nPlease provide TinyPNG API key")
print("To obta... | [
"def",
"_main",
"(",
"args",
")",
":",
"if",
"not",
"args",
".",
"apikey",
":",
"print",
"(",
"\"\\nPlease provide TinyPNG API key\"",
")",
"print",
"(",
"\"To obtain key visit https://api.tinypng.com/developers\\n\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"inpu... | Batch compression.
args contains:
* input - path to input directory
* output - path to output directory or None
* apikey - TinyPNG API key
* overwrite - boolean flag | [
"Batch",
"compression",
"."
] | ac633e4aa41122c49a806f411e43a76d8f73058e | https://github.com/vasilcovsky/pytinypng/blob/ac633e4aa41122c49a806f411e43a76d8f73058e/pytinypng/pytinypng.py#L107-L138 | train |
envi-idl/envipyengine | envipyengine/taskengine/engine.py | Engine.task | def task(self, task_name):
"""
Returns an ENVI Py Engine Task object. See ENVI Py Engine Task for examples.
:param task_name: The name of the task to retrieve.
:return: An ENVI Py Engine Task object.
"""
return Task(uri=':'.join((self._engine_name, task_name)), cwd=self.... | python | def task(self, task_name):
"""
Returns an ENVI Py Engine Task object. See ENVI Py Engine Task for examples.
:param task_name: The name of the task to retrieve.
:return: An ENVI Py Engine Task object.
"""
return Task(uri=':'.join((self._engine_name, task_name)), cwd=self.... | [
"def",
"task",
"(",
"self",
",",
"task_name",
")",
":",
"return",
"Task",
"(",
"uri",
"=",
"':'",
".",
"join",
"(",
"(",
"self",
".",
"_engine_name",
",",
"task_name",
")",
")",
",",
"cwd",
"=",
"self",
".",
"_cwd",
")"
] | Returns an ENVI Py Engine Task object. See ENVI Py Engine Task for examples.
:param task_name: The name of the task to retrieve.
:return: An ENVI Py Engine Task object. | [
"Returns",
"an",
"ENVI",
"Py",
"Engine",
"Task",
"object",
".",
"See",
"ENVI",
"Py",
"Engine",
"Task",
"for",
"examples",
"."
] | 567b639d6592deec3289f6122a9e3d18f2f98432 | https://github.com/envi-idl/envipyengine/blob/567b639d6592deec3289f6122a9e3d18f2f98432/envipyengine/taskengine/engine.py#L27-L34 | train |
envi-idl/envipyengine | envipyengine/taskengine/engine.py | Engine.tasks | def tasks(self):
"""
Returns a list of all tasks known to the engine.
:return: A list of task names.
"""
task_input = {'taskName': 'QueryTaskCatalog'}
output = taskengine.execute(task_input, self._engine_name, cwd=self._cwd)
return output['outputParameters']['TAS... | python | def tasks(self):
"""
Returns a list of all tasks known to the engine.
:return: A list of task names.
"""
task_input = {'taskName': 'QueryTaskCatalog'}
output = taskengine.execute(task_input, self._engine_name, cwd=self._cwd)
return output['outputParameters']['TAS... | [
"def",
"tasks",
"(",
"self",
")",
":",
"task_input",
"=",
"{",
"'taskName'",
":",
"'QueryTaskCatalog'",
"}",
"output",
"=",
"taskengine",
".",
"execute",
"(",
"task_input",
",",
"self",
".",
"_engine_name",
",",
"cwd",
"=",
"self",
".",
"_cwd",
")",
"ret... | Returns a list of all tasks known to the engine.
:return: A list of task names. | [
"Returns",
"a",
"list",
"of",
"all",
"tasks",
"known",
"to",
"the",
"engine",
"."
] | 567b639d6592deec3289f6122a9e3d18f2f98432 | https://github.com/envi-idl/envipyengine/blob/567b639d6592deec3289f6122a9e3d18f2f98432/envipyengine/taskengine/engine.py#L37-L45 | train |
ariebovenberg/snug | snug/query.py | execute | def execute(query, auth=None, client=urllib_request.build_opener()):
"""Execute a query, returning its result
Parameters
----------
query: Query[T]
The query to resolve
auth: ~typing.Tuple[str, str] \
or ~typing.Callable[[Request], Request] or None
This may be:
* A ... | python | def execute(query, auth=None, client=urllib_request.build_opener()):
"""Execute a query, returning its result
Parameters
----------
query: Query[T]
The query to resolve
auth: ~typing.Tuple[str, str] \
or ~typing.Callable[[Request], Request] or None
This may be:
* A ... | [
"def",
"execute",
"(",
"query",
",",
"auth",
"=",
"None",
",",
"client",
"=",
"urllib_request",
".",
"build_opener",
"(",
")",
")",
":",
"exec_fn",
"=",
"getattr",
"(",
"type",
"(",
"query",
")",
",",
"'__execute__'",
",",
"_default_execute_method",
")",
... | Execute a query, returning its result
Parameters
----------
query: Query[T]
The query to resolve
auth: ~typing.Tuple[str, str] \
or ~typing.Callable[[Request], Request] or None
This may be:
* A (username, password)-tuple for basic authentication
* A callable to ... | [
"Execute",
"a",
"query",
"returning",
"its",
"result"
] | 4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef | https://github.com/ariebovenberg/snug/blob/4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef/snug/query.py#L192-L218 | train |
ariebovenberg/snug | snug/query.py | execute_async | def execute_async(query, auth=None, client=event_loop):
"""Execute a query asynchronously, returning its result
Parameters
----------
query: Query[T]
The query to resolve
auth: ~typing.Tuple[str, str] \
or ~typing.Callable[[Request], Request] or None
This may be:
* ... | python | def execute_async(query, auth=None, client=event_loop):
"""Execute a query asynchronously, returning its result
Parameters
----------
query: Query[T]
The query to resolve
auth: ~typing.Tuple[str, str] \
or ~typing.Callable[[Request], Request] or None
This may be:
* ... | [
"def",
"execute_async",
"(",
"query",
",",
"auth",
"=",
"None",
",",
"client",
"=",
"event_loop",
")",
":",
"exc_fn",
"=",
"getattr",
"(",
"type",
"(",
"query",
")",
",",
"'__execute_async__'",
",",
"Query",
".",
"__execute_async__",
")",
"return",
"exc_fn... | Execute a query asynchronously, returning its result
Parameters
----------
query: Query[T]
The query to resolve
auth: ~typing.Tuple[str, str] \
or ~typing.Callable[[Request], Request] or None
This may be:
* A (username, password)-tuple for basic authentication
*... | [
"Execute",
"a",
"query",
"asynchronously",
"returning",
"its",
"result"
] | 4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef | https://github.com/ariebovenberg/snug/blob/4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef/snug/query.py#L221-L252 | train |
blockstack/python-utilitybelt | utilitybelt/entropy.py | secure_randint | def secure_randint(min_value, max_value, system_random=None):
""" Return a random integer N such that a <= N <= b.
Uses SystemRandom for generating random numbers.
(which uses os.urandom(), which pulls from /dev/urandom)
"""
if not system_random:
system_random = random.SystemRandom(... | python | def secure_randint(min_value, max_value, system_random=None):
""" Return a random integer N such that a <= N <= b.
Uses SystemRandom for generating random numbers.
(which uses os.urandom(), which pulls from /dev/urandom)
"""
if not system_random:
system_random = random.SystemRandom(... | [
"def",
"secure_randint",
"(",
"min_value",
",",
"max_value",
",",
"system_random",
"=",
"None",
")",
":",
"if",
"not",
"system_random",
":",
"system_random",
"=",
"random",
".",
"SystemRandom",
"(",
")",
"return",
"system_random",
".",
"randint",
"(",
"min_val... | Return a random integer N such that a <= N <= b.
Uses SystemRandom for generating random numbers.
(which uses os.urandom(), which pulls from /dev/urandom) | [
"Return",
"a",
"random",
"integer",
"N",
"such",
"that",
"a",
"<",
"=",
"N",
"<",
"=",
"b",
"."
] | 13d3502aa1a486c9d775ad2c551fb8e7e48b0d96 | https://github.com/blockstack/python-utilitybelt/blob/13d3502aa1a486c9d775ad2c551fb8e7e48b0d96/utilitybelt/entropy.py#L41-L49 | train |
ariebovenberg/snug | snug/http.py | _merge_maps | def _merge_maps(m1, m2):
"""merge two Mapping objects, keeping the type of the first mapping"""
return type(m1)(chain(m1.items(), m2.items())) | python | def _merge_maps(m1, m2):
"""merge two Mapping objects, keeping the type of the first mapping"""
return type(m1)(chain(m1.items(), m2.items())) | [
"def",
"_merge_maps",
"(",
"m1",
",",
"m2",
")",
":",
"return",
"type",
"(",
"m1",
")",
"(",
"chain",
"(",
"m1",
".",
"items",
"(",
")",
",",
"m2",
".",
"items",
"(",
")",
")",
")"
] | merge two Mapping objects, keeping the type of the first mapping | [
"merge",
"two",
"Mapping",
"objects",
"keeping",
"the",
"type",
"of",
"the",
"first",
"mapping"
] | 4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef | https://github.com/ariebovenberg/snug/blob/4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef/snug/http.py#L64-L66 | train |
ariebovenberg/snug | snug/http.py | basic_auth | def basic_auth(credentials):
"""Create an HTTP basic authentication callable
Parameters
----------
credentials: ~typing.Tuple[str, str]
The (username, password)-tuple
Returns
-------
~typing.Callable[[Request], Request]
A callable which adds basic authentication to a :class... | python | def basic_auth(credentials):
"""Create an HTTP basic authentication callable
Parameters
----------
credentials: ~typing.Tuple[str, str]
The (username, password)-tuple
Returns
-------
~typing.Callable[[Request], Request]
A callable which adds basic authentication to a :class... | [
"def",
"basic_auth",
"(",
"credentials",
")",
":",
"encoded",
"=",
"b64encode",
"(",
"':'",
".",
"join",
"(",
"credentials",
")",
".",
"encode",
"(",
"'ascii'",
")",
")",
".",
"decode",
"(",
")",
"return",
"header_adder",
"(",
"{",
"'Authorization'",
":"... | Create an HTTP basic authentication callable
Parameters
----------
credentials: ~typing.Tuple[str, str]
The (username, password)-tuple
Returns
-------
~typing.Callable[[Request], Request]
A callable which adds basic authentication to a :class:`Request`. | [
"Create",
"an",
"HTTP",
"basic",
"authentication",
"callable"
] | 4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef | https://github.com/ariebovenberg/snug/blob/4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef/snug/http.py#L156-L170 | train |
ariebovenberg/snug | snug/http.py | Request.with_headers | def with_headers(self, headers):
"""Create a new request with added headers
Parameters
----------
headers: Mapping
the headers to add
"""
return self.replace(headers=_merge_maps(self.headers, headers)) | python | def with_headers(self, headers):
"""Create a new request with added headers
Parameters
----------
headers: Mapping
the headers to add
"""
return self.replace(headers=_merge_maps(self.headers, headers)) | [
"def",
"with_headers",
"(",
"self",
",",
"headers",
")",
":",
"return",
"self",
".",
"replace",
"(",
"headers",
"=",
"_merge_maps",
"(",
"self",
".",
"headers",
",",
"headers",
")",
")"
] | Create a new request with added headers
Parameters
----------
headers: Mapping
the headers to add | [
"Create",
"a",
"new",
"request",
"with",
"added",
"headers"
] | 4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef | https://github.com/ariebovenberg/snug/blob/4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef/snug/http.py#L96-L104 | train |
ariebovenberg/snug | snug/http.py | Request.with_params | def with_params(self, params):
"""Create a new request with added query parameters
Parameters
----------
params: Mapping
the query parameters to add
"""
return self.replace(params=_merge_maps(self.params, params)) | python | def with_params(self, params):
"""Create a new request with added query parameters
Parameters
----------
params: Mapping
the query parameters to add
"""
return self.replace(params=_merge_maps(self.params, params)) | [
"def",
"with_params",
"(",
"self",
",",
"params",
")",
":",
"return",
"self",
".",
"replace",
"(",
"params",
"=",
"_merge_maps",
"(",
"self",
".",
"params",
",",
"params",
")",
")"
] | Create a new request with added query parameters
Parameters
----------
params: Mapping
the query parameters to add | [
"Create",
"a",
"new",
"request",
"with",
"added",
"query",
"parameters"
] | 4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef | https://github.com/ariebovenberg/snug/blob/4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef/snug/http.py#L116-L124 | train |
azaghal/pydenticon | pydenticon/__init__.py | Generator._get_bit | def _get_bit(self, n, hash_bytes):
"""
Determines if the n-th bit of passed bytes is 1 or 0.
Arguments:
hash_bytes - List of hash byte values for which the n-th bit value
should be checked. Each element of the list should be an integer from
0 to 255.
Retu... | python | def _get_bit(self, n, hash_bytes):
"""
Determines if the n-th bit of passed bytes is 1 or 0.
Arguments:
hash_bytes - List of hash byte values for which the n-th bit value
should be checked. Each element of the list should be an integer from
0 to 255.
Retu... | [
"def",
"_get_bit",
"(",
"self",
",",
"n",
",",
"hash_bytes",
")",
":",
"if",
"hash_bytes",
"[",
"n",
"//",
"8",
"]",
">>",
"int",
"(",
"8",
"-",
"(",
"(",
"n",
"%",
"8",
")",
"+",
"1",
")",
")",
"&",
"1",
"==",
"1",
":",
"return",
"True",
... | Determines if the n-th bit of passed bytes is 1 or 0.
Arguments:
hash_bytes - List of hash byte values for which the n-th bit value
should be checked. Each element of the list should be an integer from
0 to 255.
Returns:
True if the bit is 1. False if the bit ... | [
"Determines",
"if",
"the",
"n",
"-",
"th",
"bit",
"of",
"passed",
"bytes",
"is",
"1",
"or",
"0",
"."
] | 002ad10fd58adedfb465b5ef96eacbe6a595c2ac | https://github.com/azaghal/pydenticon/blob/002ad10fd58adedfb465b5ef96eacbe6a595c2ac/pydenticon/__init__.py#L88-L106 | train |
azaghal/pydenticon | pydenticon/__init__.py | Generator._generate_matrix | def _generate_matrix(self, hash_bytes):
"""
Generates matrix that describes which blocks should be coloured.
Arguments:
hash_bytes - List of hash byte values for which the identicon is being
generated. Each element of the list should be an integer from 0 to
255.
... | python | def _generate_matrix(self, hash_bytes):
"""
Generates matrix that describes which blocks should be coloured.
Arguments:
hash_bytes - List of hash byte values for which the identicon is being
generated. Each element of the list should be an integer from 0 to
255.
... | [
"def",
"_generate_matrix",
"(",
"self",
",",
"hash_bytes",
")",
":",
"# Since the identicon needs to be symmetric, we'll need to work on half",
"# the columns (rounded-up), and reflect where necessary.",
"half_columns",
"=",
"self",
".",
"columns",
"//",
"2",
"+",
"self",
".",
... | Generates matrix that describes which blocks should be coloured.
Arguments:
hash_bytes - List of hash byte values for which the identicon is being
generated. Each element of the list should be an integer from 0 to
255.
Returns:
List of rows, where each element i... | [
"Generates",
"matrix",
"that",
"describes",
"which",
"blocks",
"should",
"be",
"coloured",
"."
] | 002ad10fd58adedfb465b5ef96eacbe6a595c2ac | https://github.com/azaghal/pydenticon/blob/002ad10fd58adedfb465b5ef96eacbe6a595c2ac/pydenticon/__init__.py#L108-L148 | train |
azaghal/pydenticon | pydenticon/__init__.py | Generator._generate_image | def _generate_image(self, matrix, width, height, padding, foreground, background, image_format):
"""
Generates an identicon image in requested image format out of the passed
block matrix, with the requested width, height, padding, foreground
colour, background colour, and image format.
... | python | def _generate_image(self, matrix, width, height, padding, foreground, background, image_format):
"""
Generates an identicon image in requested image format out of the passed
block matrix, with the requested width, height, padding, foreground
colour, background colour, and image format.
... | [
"def",
"_generate_image",
"(",
"self",
",",
"matrix",
",",
"width",
",",
"height",
",",
"padding",
",",
"foreground",
",",
"background",
",",
"image_format",
")",
":",
"# Set-up a new image object, setting the background to provided value.",
"image",
"=",
"Image",
"."... | Generates an identicon image in requested image format out of the passed
block matrix, with the requested width, height, padding, foreground
colour, background colour, and image format.
Arguments:
matrix - Matrix describing which blocks in the identicon should be
painted wi... | [
"Generates",
"an",
"identicon",
"image",
"in",
"requested",
"image",
"format",
"out",
"of",
"the",
"passed",
"block",
"matrix",
"with",
"the",
"requested",
"width",
"height",
"padding",
"foreground",
"colour",
"background",
"colour",
"and",
"image",
"format",
".... | 002ad10fd58adedfb465b5ef96eacbe6a595c2ac | https://github.com/azaghal/pydenticon/blob/002ad10fd58adedfb465b5ef96eacbe6a595c2ac/pydenticon/__init__.py#L187-L261 | train |
azaghal/pydenticon | pydenticon/__init__.py | Generator._generate_ascii | def _generate_ascii(self, matrix, foreground, background):
"""
Generates an identicon "image" in the ASCII format. The image will just
output the matrix used to generate the identicon.
Arguments:
matrix - Matrix describing which blocks in the identicon should be
pai... | python | def _generate_ascii(self, matrix, foreground, background):
"""
Generates an identicon "image" in the ASCII format. The image will just
output the matrix used to generate the identicon.
Arguments:
matrix - Matrix describing which blocks in the identicon should be
pai... | [
"def",
"_generate_ascii",
"(",
"self",
",",
"matrix",
",",
"foreground",
",",
"background",
")",
":",
"return",
"\"\\n\"",
".",
"join",
"(",
"[",
"\"\"",
".",
"join",
"(",
"[",
"foreground",
"if",
"cell",
"else",
"background",
"for",
"cell",
"in",
"row",... | Generates an identicon "image" in the ASCII format. The image will just
output the matrix used to generate the identicon.
Arguments:
matrix - Matrix describing which blocks in the identicon should be
painted with foreground (background if inverted) colour.
foreground - C... | [
"Generates",
"an",
"identicon",
"image",
"in",
"the",
"ASCII",
"format",
".",
"The",
"image",
"will",
"just",
"output",
"the",
"matrix",
"used",
"to",
"generate",
"the",
"identicon",
"."
] | 002ad10fd58adedfb465b5ef96eacbe6a595c2ac | https://github.com/azaghal/pydenticon/blob/002ad10fd58adedfb465b5ef96eacbe6a595c2ac/pydenticon/__init__.py#L263-L285 | train |
eclipse/unide.python | src/unide/util.py | local_timezone | def local_timezone(value):
"""Add the local timezone to `value` to make it aware."""
if hasattr(value, "tzinfo") and value.tzinfo is None:
return value.replace(tzinfo=dateutil.tz.tzlocal())
return value | python | def local_timezone(value):
"""Add the local timezone to `value` to make it aware."""
if hasattr(value, "tzinfo") and value.tzinfo is None:
return value.replace(tzinfo=dateutil.tz.tzlocal())
return value | [
"def",
"local_timezone",
"(",
"value",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"\"tzinfo\"",
")",
"and",
"value",
".",
"tzinfo",
"is",
"None",
":",
"return",
"value",
".",
"replace",
"(",
"tzinfo",
"=",
"dateutil",
".",
"tz",
".",
"tzlocal",
"(",... | Add the local timezone to `value` to make it aware. | [
"Add",
"the",
"local",
"timezone",
"to",
"value",
"to",
"make",
"it",
"aware",
"."
] | b82e6a0bf7cc44a463c5d7cdb3d2199f8320c493 | https://github.com/eclipse/unide.python/blob/b82e6a0bf7cc44a463c5d7cdb3d2199f8320c493/src/unide/util.py#L37-L41 | train |
eclipse/unide.python | src/unide/util.py | dumps | def dumps(data, **kwargs):
"""Convert a PPMP entity to JSON. Additional arguments are the same as
accepted by `json.dumps`."""
def _encoder(value):
if isinstance(value, datetime.datetime):
return value.isoformat()
if hasattr(value, "_data"):
return value._data
... | python | def dumps(data, **kwargs):
"""Convert a PPMP entity to JSON. Additional arguments are the same as
accepted by `json.dumps`."""
def _encoder(value):
if isinstance(value, datetime.datetime):
return value.isoformat()
if hasattr(value, "_data"):
return value._data
... | [
"def",
"dumps",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_encoder",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"value",
".",
"isoformat",
"(",
")",
"if",
"hasattr",
... | Convert a PPMP entity to JSON. Additional arguments are the same as
accepted by `json.dumps`. | [
"Convert",
"a",
"PPMP",
"entity",
"to",
"JSON",
".",
"Additional",
"arguments",
"are",
"the",
"same",
"as",
"accepted",
"by",
"json",
".",
"dumps",
"."
] | b82e6a0bf7cc44a463c5d7cdb3d2199f8320c493 | https://github.com/eclipse/unide.python/blob/b82e6a0bf7cc44a463c5d7cdb3d2199f8320c493/src/unide/util.py#L68-L81 | train |
Godley/MuseParse | MuseParse/classes/Output/helpers.py | setup_lilypond | def setup_lilypond(path_to_lilypond_folder="default"):
'''
Optional helper method which works out the platform and calls the relevant setup method
* param path_to_lilypond_folder: the path where lilypond.exe or the lilypond runner tool in mac is located. Not needed if
setup is default, or if using linu... | python | def setup_lilypond(path_to_lilypond_folder="default"):
'''
Optional helper method which works out the platform and calls the relevant setup method
* param path_to_lilypond_folder: the path where lilypond.exe or the lilypond runner tool in mac is located. Not needed if
setup is default, or if using linu... | [
"def",
"setup_lilypond",
"(",
"path_to_lilypond_folder",
"=",
"\"default\"",
")",
":",
"options",
"=",
"{",
"\"win32\"",
":",
"setup_lilypond_windows",
",",
"\"darwin\"",
":",
"setup_lilypond_osx",
"}",
"if",
"platform",
".",
"startswith",
"(",
"\"linux\"",
")",
"... | Optional helper method which works out the platform and calls the relevant setup method
* param path_to_lilypond_folder: the path where lilypond.exe or the lilypond runner tool in mac is located. Not needed if
setup is default, or if using linux
* :return: None | [
"Optional",
"helper",
"method",
"which",
"works",
"out",
"the",
"platform",
"and",
"calls",
"the",
"relevant",
"setup",
"method"
] | 23cecafa1fdc0f2d6a87760553572b459f3c9904 | https://github.com/Godley/MuseParse/blob/23cecafa1fdc0f2d6a87760553572b459f3c9904/MuseParse/classes/Output/helpers.py#L13-L26 | train |
Godley/MuseParse | MuseParse/classes/Output/helpers.py | setup_lilypond_windows | def setup_lilypond_windows(path="default"):
'''
Optional helper method which does the environment setup for lilypond in windows. If you've ran this method, you do not need and should not provide
a lyscript when you instantiate this class. As this method is static, you can run this method before you set up t... | python | def setup_lilypond_windows(path="default"):
'''
Optional helper method which does the environment setup for lilypond in windows. If you've ran this method, you do not need and should not provide
a lyscript when you instantiate this class. As this method is static, you can run this method before you set up t... | [
"def",
"setup_lilypond_windows",
"(",
"path",
"=",
"\"default\"",
")",
":",
"default",
"=",
"\"C:/Program Files (x86)/LilyPond/usr/bin\"",
"path_variable",
"=",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
".",
"split",
"(",
"\";\"",
")",
"if",
"path",
"==",
"\"def... | Optional helper method which does the environment setup for lilypond in windows. If you've ran this method, you do not need and should not provide
a lyscript when you instantiate this class. As this method is static, you can run this method before you set up the LilypondRenderer
instance.
* parameter: path... | [
"Optional",
"helper",
"method",
"which",
"does",
"the",
"environment",
"setup",
"for",
"lilypond",
"in",
"windows",
".",
"If",
"you",
"ve",
"ran",
"this",
"method",
"you",
"do",
"not",
"need",
"and",
"should",
"not",
"provide",
"a",
"lyscript",
"when",
"yo... | 23cecafa1fdc0f2d6a87760553572b459f3c9904 | https://github.com/Godley/MuseParse/blob/23cecafa1fdc0f2d6a87760553572b459f3c9904/MuseParse/classes/Output/helpers.py#L29-L46 | train |
blockstack/python-utilitybelt | utilitybelt/dicts.py | recursive_dict_to_dict | def recursive_dict_to_dict(rdict):
""" Convert a recursive dict to a plain ol' dict.
"""
d = {}
for (k, v) in rdict.items():
if isinstance(v, defaultdict):
d[k] = recursive_dict_to_dict(v)
else:
d[k] = v
return d | python | def recursive_dict_to_dict(rdict):
""" Convert a recursive dict to a plain ol' dict.
"""
d = {}
for (k, v) in rdict.items():
if isinstance(v, defaultdict):
d[k] = recursive_dict_to_dict(v)
else:
d[k] = v
return d | [
"def",
"recursive_dict_to_dict",
"(",
"rdict",
")",
":",
"d",
"=",
"{",
"}",
"for",
"(",
"k",
",",
"v",
")",
"in",
"rdict",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"defaultdict",
")",
":",
"d",
"[",
"k",
"]",
"=",
"recur... | Convert a recursive dict to a plain ol' dict. | [
"Convert",
"a",
"recursive",
"dict",
"to",
"a",
"plain",
"ol",
"dict",
"."
] | 13d3502aa1a486c9d775ad2c551fb8e7e48b0d96 | https://github.com/blockstack/python-utilitybelt/blob/13d3502aa1a486c9d775ad2c551fb8e7e48b0d96/utilitybelt/dicts.py#L17-L26 | train |
blockstack/python-utilitybelt | utilitybelt/dicts.py | scrub_dict | def scrub_dict(d):
""" Recursively inspect a dictionary and remove all empty values, including
empty strings, lists, and dictionaries.
"""
if type(d) is dict:
return dict(
(k, scrub_dict(v)) for k, v in d.iteritems() if v and scrub_dict(v)
)
elif type(d) is list:
... | python | def scrub_dict(d):
""" Recursively inspect a dictionary and remove all empty values, including
empty strings, lists, and dictionaries.
"""
if type(d) is dict:
return dict(
(k, scrub_dict(v)) for k, v in d.iteritems() if v and scrub_dict(v)
)
elif type(d) is list:
... | [
"def",
"scrub_dict",
"(",
"d",
")",
":",
"if",
"type",
"(",
"d",
")",
"is",
"dict",
":",
"return",
"dict",
"(",
"(",
"k",
",",
"scrub_dict",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"d",
".",
"iteritems",
"(",
")",
"if",
"v",
"and",
... | Recursively inspect a dictionary and remove all empty values, including
empty strings, lists, and dictionaries. | [
"Recursively",
"inspect",
"a",
"dictionary",
"and",
"remove",
"all",
"empty",
"values",
"including",
"empty",
"strings",
"lists",
"and",
"dictionaries",
"."
] | 13d3502aa1a486c9d775ad2c551fb8e7e48b0d96 | https://github.com/blockstack/python-utilitybelt/blob/13d3502aa1a486c9d775ad2c551fb8e7e48b0d96/utilitybelt/dicts.py#L29-L42 | train |
blockstack/python-utilitybelt | utilitybelt/dicts.py | _to_json_type | def _to_json_type(obj, classkey=None):
""" Recursively convert the object instance into a valid JSON type.
"""
if isinstance(obj, dict):
data = {}
for (k, v) in obj.items():
data[k] = _to_json_type(v, classkey)
return data
elif hasattr(obj, "_ast"):
return _to... | python | def _to_json_type(obj, classkey=None):
""" Recursively convert the object instance into a valid JSON type.
"""
if isinstance(obj, dict):
data = {}
for (k, v) in obj.items():
data[k] = _to_json_type(v, classkey)
return data
elif hasattr(obj, "_ast"):
return _to... | [
"def",
"_to_json_type",
"(",
"obj",
",",
"classkey",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"data",
"=",
"{",
"}",
"for",
"(",
"k",
",",
"v",
")",
"in",
"obj",
".",
"items",
"(",
")",
":",
"data",
"[",
"... | Recursively convert the object instance into a valid JSON type. | [
"Recursively",
"convert",
"the",
"object",
"instance",
"into",
"a",
"valid",
"JSON",
"type",
"."
] | 13d3502aa1a486c9d775ad2c551fb8e7e48b0d96 | https://github.com/blockstack/python-utilitybelt/blob/13d3502aa1a486c9d775ad2c551fb8e7e48b0d96/utilitybelt/dicts.py#L45-L67 | train |
blockstack/python-utilitybelt | utilitybelt/dicts.py | to_dict | def to_dict(obj):
""" Convert an instance of an object into a dict.
"""
d = _to_json_type(obj)
if isinstance(d, dict):
return scrub_dict(d)
else:
raise ValueError("The value provided must be an object.") | python | def to_dict(obj):
""" Convert an instance of an object into a dict.
"""
d = _to_json_type(obj)
if isinstance(d, dict):
return scrub_dict(d)
else:
raise ValueError("The value provided must be an object.") | [
"def",
"to_dict",
"(",
"obj",
")",
":",
"d",
"=",
"_to_json_type",
"(",
"obj",
")",
"if",
"isinstance",
"(",
"d",
",",
"dict",
")",
":",
"return",
"scrub_dict",
"(",
"d",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"The value provided must be an object... | Convert an instance of an object into a dict. | [
"Convert",
"an",
"instance",
"of",
"an",
"object",
"into",
"a",
"dict",
"."
] | 13d3502aa1a486c9d775ad2c551fb8e7e48b0d96 | https://github.com/blockstack/python-utilitybelt/blob/13d3502aa1a486c9d775ad2c551fb8e7e48b0d96/utilitybelt/dicts.py#L70-L77 | train |
TylerTemp/docpie | docpie/tracemore.py | print_exc_plus | def print_exc_plus(stream=sys.stdout):
'''print normal traceback information with some local arg values'''
# code of this mothod is mainly from <Python Cookbook>
write = stream.write # assert the mothod exists
flush = stream.flush
tp, value, tb = sys.exc_info()
while tb.tb_next:
tb = ... | python | def print_exc_plus(stream=sys.stdout):
'''print normal traceback information with some local arg values'''
# code of this mothod is mainly from <Python Cookbook>
write = stream.write # assert the mothod exists
flush = stream.flush
tp, value, tb = sys.exc_info()
while tb.tb_next:
tb = ... | [
"def",
"print_exc_plus",
"(",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"# code of this mothod is mainly from <Python Cookbook>",
"write",
"=",
"stream",
".",
"write",
"# assert the mothod exists",
"flush",
"=",
"stream",
".",
"flush",
"tp",
",",
"value",
",",
... | print normal traceback information with some local arg values | [
"print",
"normal",
"traceback",
"information",
"with",
"some",
"local",
"arg",
"values"
] | e658454b81b6c79a020d499f12ad73496392c09a | https://github.com/TylerTemp/docpie/blob/e658454b81b6c79a020d499f12ad73496392c09a/docpie/tracemore.py#L22-L56 | train |
MacHu-GWU/single_file_module-project | sfm/textformatter.py | format_single_space_only | def format_single_space_only(text):
"""Revise consecutive empty space to single space.
Example::
" I feel so GOOD!" => "This is so GOOD!"
**中文文档**
确保文本中不会出现多余连续1次的空格。
"""
return " ".join([word for word in text.strip().split(" ") if len(word) >= 1]) | python | def format_single_space_only(text):
"""Revise consecutive empty space to single space.
Example::
" I feel so GOOD!" => "This is so GOOD!"
**中文文档**
确保文本中不会出现多余连续1次的空格。
"""
return " ".join([word for word in text.strip().split(" ") if len(word) >= 1]) | [
"def",
"format_single_space_only",
"(",
"text",
")",
":",
"return",
"\" \"",
".",
"join",
"(",
"[",
"word",
"for",
"word",
"in",
"text",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\" \"",
")",
"if",
"len",
"(",
"word",
")",
">=",
"1",
"]",
")"
] | Revise consecutive empty space to single space.
Example::
" I feel so GOOD!" => "This is so GOOD!"
**中文文档**
确保文本中不会出现多余连续1次的空格。 | [
"Revise",
"consecutive",
"empty",
"space",
"to",
"single",
"space",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/textformatter.py#L26-L37 | train |
MacHu-GWU/single_file_module-project | sfm/textformatter.py | format_title | def format_title(text):
"""Capitalize first letter for each words except function words.
Example::
title = "Beautiful is Better than Ugly"
**中文文档**
将文本 "标题化", 即除了虚词, 每一个英文单词的第一个字母大写。
"""
text = text.strip()
# if empty string, return ""
if len(text) == 0:
return text
... | python | def format_title(text):
"""Capitalize first letter for each words except function words.
Example::
title = "Beautiful is Better than Ugly"
**中文文档**
将文本 "标题化", 即除了虚词, 每一个英文单词的第一个字母大写。
"""
text = text.strip()
# if empty string, return ""
if len(text) == 0:
return text
... | [
"def",
"format_title",
"(",
"text",
")",
":",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"# if empty string, return \"\"",
"if",
"len",
"(",
"text",
")",
"==",
"0",
":",
"return",
"text",
"else",
":",
"text",
"=",
"text",
".",
"lower",
"(",
")",
"#... | Capitalize first letter for each words except function words.
Example::
title = "Beautiful is Better than Ugly"
**中文文档**
将文本 "标题化", 即除了虚词, 每一个英文单词的第一个字母大写。 | [
"Capitalize",
"first",
"letter",
"for",
"each",
"words",
"except",
"function",
"words",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/textformatter.py#L40-L71 | train |
MacHu-GWU/single_file_module-project | sfm/textformatter.py | format_person_name | def format_person_name(text):
"""Capitalize first letter for each part of the name.
Example::
person_name = "James Bond"
**中文文档**
将文本修改为人名格式。每个单词的第一个字母大写。
"""
text = text.strip()
if len(text) == 0: # if empty string, return it
return text
else:
text = text.lo... | python | def format_person_name(text):
"""Capitalize first letter for each part of the name.
Example::
person_name = "James Bond"
**中文文档**
将文本修改为人名格式。每个单词的第一个字母大写。
"""
text = text.strip()
if len(text) == 0: # if empty string, return it
return text
else:
text = text.lo... | [
"def",
"format_person_name",
"(",
"text",
")",
":",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"text",
")",
"==",
"0",
":",
"# if empty string, return it",
"return",
"text",
"else",
":",
"text",
"=",
"text",
".",
"lower",
"(",
")",
... | Capitalize first letter for each part of the name.
Example::
person_name = "James Bond"
**中文文档**
将文本修改为人名格式。每个单词的第一个字母大写。 | [
"Capitalize",
"first",
"letter",
"for",
"each",
"part",
"of",
"the",
"name",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/textformatter.py#L74-L93 | train |
MacHu-GWU/single_file_module-project | sfm/dtree.py | DictTree.dump | def dump(self, path):
"""
dump DictTree data to json files.
"""
try:
with open(path, "wb") as f:
f.write(self.__str__().encode("utf-8"))
except:
pass
with open(path, "wb") as f:
pickle.dump(self.__data__, f) | python | def dump(self, path):
"""
dump DictTree data to json files.
"""
try:
with open(path, "wb") as f:
f.write(self.__str__().encode("utf-8"))
except:
pass
with open(path, "wb") as f:
pickle.dump(self.__data__, f) | [
"def",
"dump",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"with",
"open",
"(",
"path",
",",
"\"wb\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"self",
".",
"__str__",
"(",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"except",
":",
... | dump DictTree data to json files. | [
"dump",
"DictTree",
"data",
"to",
"json",
"files",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/dtree.py#L117-L128 | train |
MacHu-GWU/single_file_module-project | sfm/dtree.py | DictTree.load | def load(cls, path):
"""
load DictTree from json files.
"""
try:
with open(path, "rb") as f:
return cls(__data__=json.loads(f.read().decode("utf-8")))
except:
pass
with open(path, "rb") as f:
return cls(__data__=pickle.... | python | def load(cls, path):
"""
load DictTree from json files.
"""
try:
with open(path, "rb") as f:
return cls(__data__=json.loads(f.read().decode("utf-8")))
except:
pass
with open(path, "rb") as f:
return cls(__data__=pickle.... | [
"def",
"load",
"(",
"cls",
",",
"path",
")",
":",
"try",
":",
"with",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"return",
"cls",
"(",
"__data__",
"=",
"json",
".",
"loads",
"(",
"f",
".",
"read",
"(",
")",
".",
"decode",
"(",
"... | load DictTree from json files. | [
"load",
"DictTree",
"from",
"json",
"files",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/dtree.py#L131-L142 | train |
MacHu-GWU/single_file_module-project | sfm/dtree.py | DictTree.values | def values(self):
"""
Iterate values.
"""
for key, value in self.__data__.items():
if key not in (META, KEY):
yield DictTree(__data__=value) | python | def values(self):
"""
Iterate values.
"""
for key, value in self.__data__.items():
if key not in (META, KEY):
yield DictTree(__data__=value) | [
"def",
"values",
"(",
"self",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"__data__",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"(",
"META",
",",
"KEY",
")",
":",
"yield",
"DictTree",
"(",
"__data__",
"=",
"value",
")"
] | Iterate values. | [
"Iterate",
"values",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/dtree.py#L202-L208 | train |
MacHu-GWU/single_file_module-project | sfm/dtree.py | DictTree.keys_at | def keys_at(self, depth, counter=1):
"""
Iterate keys at specified depth.
"""
if depth < 1:
yield ROOT
else:
if counter == depth:
for key in self.keys():
yield key
else:
counter += 1
... | python | def keys_at(self, depth, counter=1):
"""
Iterate keys at specified depth.
"""
if depth < 1:
yield ROOT
else:
if counter == depth:
for key in self.keys():
yield key
else:
counter += 1
... | [
"def",
"keys_at",
"(",
"self",
",",
"depth",
",",
"counter",
"=",
"1",
")",
":",
"if",
"depth",
"<",
"1",
":",
"yield",
"ROOT",
"else",
":",
"if",
"counter",
"==",
"depth",
":",
"for",
"key",
"in",
"self",
".",
"keys",
"(",
")",
":",
"yield",
"... | Iterate keys at specified depth. | [
"Iterate",
"keys",
"at",
"specified",
"depth",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/dtree.py#L219-L233 | train |
MacHu-GWU/single_file_module-project | sfm/dtree.py | DictTree.values_at | def values_at(self, depth):
"""
Iterate values at specified depth.
"""
if depth < 1:
yield self
else:
for dict_tree in self.values():
for value in dict_tree.values_at(depth - 1):
yield value | python | def values_at(self, depth):
"""
Iterate values at specified depth.
"""
if depth < 1:
yield self
else:
for dict_tree in self.values():
for value in dict_tree.values_at(depth - 1):
yield value | [
"def",
"values_at",
"(",
"self",
",",
"depth",
")",
":",
"if",
"depth",
"<",
"1",
":",
"yield",
"self",
"else",
":",
"for",
"dict_tree",
"in",
"self",
".",
"values",
"(",
")",
":",
"for",
"value",
"in",
"dict_tree",
".",
"values_at",
"(",
"depth",
... | Iterate values at specified depth. | [
"Iterate",
"values",
"at",
"specified",
"depth",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/dtree.py#L235-L244 | train |
MacHu-GWU/single_file_module-project | sfm/dtree.py | DictTree.items_at | def items_at(self, depth):
"""
Iterate items at specified depth.
"""
if depth < 1:
yield ROOT, self
elif depth == 1:
for key, value in self.items():
yield key, value
else:
for dict_tree in self.values():
... | python | def items_at(self, depth):
"""
Iterate items at specified depth.
"""
if depth < 1:
yield ROOT, self
elif depth == 1:
for key, value in self.items():
yield key, value
else:
for dict_tree in self.values():
... | [
"def",
"items_at",
"(",
"self",
",",
"depth",
")",
":",
"if",
"depth",
"<",
"1",
":",
"yield",
"ROOT",
",",
"self",
"elif",
"depth",
"==",
"1",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"items",
"(",
")",
":",
"yield",
"key",
",",
"va... | Iterate items at specified depth. | [
"Iterate",
"items",
"at",
"specified",
"depth",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/dtree.py#L246-L258 | train |
MacHu-GWU/single_file_module-project | sfm/dtree.py | DictTree.stats | def stats(self, result=None, counter=0):
"""
Display the node stats info on specific depth in this dict.
::
[
{"depth": 0, "leaf": M0, "root": N0},
{"depth": 1, "leaf": M1, "root": N1},
...
{"depth": k, "leaf": Mk, "ro... | python | def stats(self, result=None, counter=0):
"""
Display the node stats info on specific depth in this dict.
::
[
{"depth": 0, "leaf": M0, "root": N0},
{"depth": 1, "leaf": M1, "root": N1},
...
{"depth": k, "leaf": Mk, "ro... | [
"def",
"stats",
"(",
"self",
",",
"result",
"=",
"None",
",",
"counter",
"=",
"0",
")",
":",
"if",
"result",
"is",
"None",
":",
"result",
"=",
"dict",
"(",
")",
"if",
"counter",
"==",
"0",
":",
"if",
"len",
"(",
"self",
")",
":",
"result",
"[",... | Display the node stats info on specific depth in this dict.
::
[
{"depth": 0, "leaf": M0, "root": N0},
{"depth": 1, "leaf": M1, "root": N1},
...
{"depth": k, "leaf": Mk, "root": Nk},
] | [
"Display",
"the",
"node",
"stats",
"info",
"on",
"specific",
"depth",
"in",
"this",
"dict",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/dtree.py#L271-L311 | train |
igorcoding/asynctnt-queue | asynctnt_queue/tube.py | Tube.put | async def put(self, data, *, pri=None, ttl=None, ttr=None, delay=None):
"""
Puts data to the queue and returns a newly created Task
:param data: Arbitrary task payload
:param pri: Task priority (0 by default)
:param ttl: Task time-to-live
:param ttr: ... | python | async def put(self, data, *, pri=None, ttl=None, ttr=None, delay=None):
"""
Puts data to the queue and returns a newly created Task
:param data: Arbitrary task payload
:param pri: Task priority (0 by default)
:param ttl: Task time-to-live
:param ttr: ... | [
"async",
"def",
"put",
"(",
"self",
",",
"data",
",",
"*",
",",
"pri",
"=",
"None",
",",
"ttl",
"=",
"None",
",",
"ttr",
"=",
"None",
",",
"delay",
"=",
"None",
")",
":",
"opts",
"=",
"{",
"}",
"if",
"pri",
"is",
"not",
"None",
":",
"opts",
... | Puts data to the queue and returns a newly created Task
:param data: Arbitrary task payload
:param pri: Task priority (0 by default)
:param ttl: Task time-to-live
:param ttr: Task time-to-run
:param delay: Task delay
:return: Task instance | [
"Puts",
"data",
"to",
"the",
"queue",
"and",
"returns",
"a",
"newly",
"created",
"Task"
] | 75719b2dd27e8314ae924aea6a7a85be8f48ecc5 | https://github.com/igorcoding/asynctnt-queue/blob/75719b2dd27e8314ae924aea6a7a85be8f48ecc5/asynctnt_queue/tube.py#L74-L100 | train |
igorcoding/asynctnt-queue | asynctnt_queue/tube.py | Tube.take | async def take(self, timeout=None):
"""
Takes task from the queue, waiting the timeout if specified
:param timeout: Seconds to wait for ready tasks
:return: Task instance
"""
args = None
if timeout is not None:
args = (timeout,)
r... | python | async def take(self, timeout=None):
"""
Takes task from the queue, waiting the timeout if specified
:param timeout: Seconds to wait for ready tasks
:return: Task instance
"""
args = None
if timeout is not None:
args = (timeout,)
r... | [
"async",
"def",
"take",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"args",
"=",
"None",
"if",
"timeout",
"is",
"not",
"None",
":",
"args",
"=",
"(",
"timeout",
",",
")",
"res",
"=",
"await",
"self",
".",
"conn",
".",
"call",
"(",
"self",... | Takes task from the queue, waiting the timeout if specified
:param timeout: Seconds to wait for ready tasks
:return: Task instance | [
"Takes",
"task",
"from",
"the",
"queue",
"waiting",
"the",
"timeout",
"if",
"specified"
] | 75719b2dd27e8314ae924aea6a7a85be8f48ecc5 | https://github.com/igorcoding/asynctnt-queue/blob/75719b2dd27e8314ae924aea6a7a85be8f48ecc5/asynctnt_queue/tube.py#L102-L116 | train |
igorcoding/asynctnt-queue | asynctnt_queue/tube.py | Tube.peek | async def peek(self, task_id):
"""
Get task without changing its state
:param task_id: Task id
:return: Task instance
"""
args = (task_id,)
res = await self.conn.call(self.__funcs['peek'], args)
return self._create_task(res.body) | python | async def peek(self, task_id):
"""
Get task without changing its state
:param task_id: Task id
:return: Task instance
"""
args = (task_id,)
res = await self.conn.call(self.__funcs['peek'], args)
return self._create_task(res.body) | [
"async",
"def",
"peek",
"(",
"self",
",",
"task_id",
")",
":",
"args",
"=",
"(",
"task_id",
",",
")",
"res",
"=",
"await",
"self",
".",
"conn",
".",
"call",
"(",
"self",
".",
"__funcs",
"[",
"'peek'",
"]",
",",
"args",
")",
"return",
"self",
".",... | Get task without changing its state
:param task_id: Task id
:return: Task instance | [
"Get",
"task",
"without",
"changing",
"its",
"state"
] | 75719b2dd27e8314ae924aea6a7a85be8f48ecc5 | https://github.com/igorcoding/asynctnt-queue/blob/75719b2dd27e8314ae924aea6a7a85be8f48ecc5/asynctnt_queue/tube.py#L156-L166 | train |
igorcoding/asynctnt-queue | asynctnt_queue/tube.py | Tube.kick | async def kick(self, count):
"""
Kick `count` tasks from queue
:param count: Tasks count to kick
:return: Number of tasks actually kicked
"""
args = (count,)
res = await self.conn.call(self.__funcs['kick'], args)
if self.conn.version < (1, 7):... | python | async def kick(self, count):
"""
Kick `count` tasks from queue
:param count: Tasks count to kick
:return: Number of tasks actually kicked
"""
args = (count,)
res = await self.conn.call(self.__funcs['kick'], args)
if self.conn.version < (1, 7):... | [
"async",
"def",
"kick",
"(",
"self",
",",
"count",
")",
":",
"args",
"=",
"(",
"count",
",",
")",
"res",
"=",
"await",
"self",
".",
"conn",
".",
"call",
"(",
"self",
".",
"__funcs",
"[",
"'kick'",
"]",
",",
"args",
")",
"if",
"self",
".",
"conn... | Kick `count` tasks from queue
:param count: Tasks count to kick
:return: Number of tasks actually kicked | [
"Kick",
"count",
"tasks",
"from",
"queue"
] | 75719b2dd27e8314ae924aea6a7a85be8f48ecc5 | https://github.com/igorcoding/asynctnt-queue/blob/75719b2dd27e8314ae924aea6a7a85be8f48ecc5/asynctnt_queue/tube.py#L190-L201 | train |
ariebovenberg/snug | examples/slack/query.py | _parse_content | def _parse_content(response):
"""parse the response body as JSON, raise on errors"""
if response.status_code != 200:
raise ApiError(f'unknown error: {response.content.decode()}')
result = json.loads(response.content)
if not result['ok']:
raise ApiError(f'{result["error"]}: {result.get("d... | python | def _parse_content(response):
"""parse the response body as JSON, raise on errors"""
if response.status_code != 200:
raise ApiError(f'unknown error: {response.content.decode()}')
result = json.loads(response.content)
if not result['ok']:
raise ApiError(f'{result["error"]}: {result.get("d... | [
"def",
"_parse_content",
"(",
"response",
")",
":",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"raise",
"ApiError",
"(",
"f'unknown error: {response.content.decode()}'",
")",
"result",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"content",
")",... | parse the response body as JSON, raise on errors | [
"parse",
"the",
"response",
"body",
"as",
"JSON",
"raise",
"on",
"errors"
] | 4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef | https://github.com/ariebovenberg/snug/blob/4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef/examples/slack/query.py#L19-L26 | train |
ariebovenberg/snug | examples/slack/query.py | paginated_retrieval | def paginated_retrieval(methodname, itemtype):
"""decorator factory for retrieval queries from query params"""
return compose(
reusable,
basic_interaction,
map_yield(partial(_params_as_get, methodname)),
) | python | def paginated_retrieval(methodname, itemtype):
"""decorator factory for retrieval queries from query params"""
return compose(
reusable,
basic_interaction,
map_yield(partial(_params_as_get, methodname)),
) | [
"def",
"paginated_retrieval",
"(",
"methodname",
",",
"itemtype",
")",
":",
"return",
"compose",
"(",
"reusable",
",",
"basic_interaction",
",",
"map_yield",
"(",
"partial",
"(",
"_params_as_get",
",",
"methodname",
")",
")",
",",
")"
] | decorator factory for retrieval queries from query params | [
"decorator",
"factory",
"for",
"retrieval",
"queries",
"from",
"query",
"params"
] | 4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef | https://github.com/ariebovenberg/snug/blob/4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef/examples/slack/query.py#L49-L55 | train |
ariebovenberg/snug | examples/slack/query.py | json_post | def json_post(methodname, rtype, key):
"""decorator factory for json POST queries"""
return compose(
reusable,
map_return(registry(rtype), itemgetter(key)),
basic_interaction,
map_yield(partial(_json_as_post, methodname)),
oneyield,
) | python | def json_post(methodname, rtype, key):
"""decorator factory for json POST queries"""
return compose(
reusable,
map_return(registry(rtype), itemgetter(key)),
basic_interaction,
map_yield(partial(_json_as_post, methodname)),
oneyield,
) | [
"def",
"json_post",
"(",
"methodname",
",",
"rtype",
",",
"key",
")",
":",
"return",
"compose",
"(",
"reusable",
",",
"map_return",
"(",
"registry",
"(",
"rtype",
")",
",",
"itemgetter",
"(",
"key",
")",
")",
",",
"basic_interaction",
",",
"map_yield",
"... | decorator factory for json POST queries | [
"decorator",
"factory",
"for",
"json",
"POST",
"queries"
] | 4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef | https://github.com/ariebovenberg/snug/blob/4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef/examples/slack/query.py#L62-L70 | train |
envi-idl/envipyengine | envipyengine/config.py | _read_config | def _read_config(cfg_file):
"""
Return a ConfigParser object populated from the settings.cfg file.
:return: A Config Parser object.
"""
config = ConfigParser()
# maintain case of options
config.optionxform = lambda option: option
if not os.path.exists(cfg_file):
# Create an empt... | python | def _read_config(cfg_file):
"""
Return a ConfigParser object populated from the settings.cfg file.
:return: A Config Parser object.
"""
config = ConfigParser()
# maintain case of options
config.optionxform = lambda option: option
if not os.path.exists(cfg_file):
# Create an empt... | [
"def",
"_read_config",
"(",
"cfg_file",
")",
":",
"config",
"=",
"ConfigParser",
"(",
")",
"# maintain case of options",
"config",
".",
"optionxform",
"=",
"lambda",
"option",
":",
"option",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"cfg_file",
")"... | Return a ConfigParser object populated from the settings.cfg file.
:return: A Config Parser object. | [
"Return",
"a",
"ConfigParser",
"object",
"populated",
"from",
"the",
"settings",
".",
"cfg",
"file",
"."
] | 567b639d6592deec3289f6122a9e3d18f2f98432 | https://github.com/envi-idl/envipyengine/blob/567b639d6592deec3289f6122a9e3d18f2f98432/envipyengine/config.py#L145-L160 | train |
envi-idl/envipyengine | envipyengine/config.py | _write_config | def _write_config(config, cfg_file):
"""
Write a config object to the settings.cfg file.
:param config: A ConfigParser object to write to the settings.cfg file.
"""
directory = os.path.dirname(cfg_file)
if not os.path.exists(directory):
os.makedirs(directory)
with open(cfg_file, "w+... | python | def _write_config(config, cfg_file):
"""
Write a config object to the settings.cfg file.
:param config: A ConfigParser object to write to the settings.cfg file.
"""
directory = os.path.dirname(cfg_file)
if not os.path.exists(directory):
os.makedirs(directory)
with open(cfg_file, "w+... | [
"def",
"_write_config",
"(",
"config",
",",
"cfg_file",
")",
":",
"directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"cfg_file",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
":",
"os",
".",
"makedirs",
"(",
"direc... | Write a config object to the settings.cfg file.
:param config: A ConfigParser object to write to the settings.cfg file. | [
"Write",
"a",
"config",
"object",
"to",
"the",
"settings",
".",
"cfg",
"file",
"."
] | 567b639d6592deec3289f6122a9e3d18f2f98432 | https://github.com/envi-idl/envipyengine/blob/567b639d6592deec3289f6122a9e3d18f2f98432/envipyengine/config.py#L163-L173 | train |
envi-idl/envipyengine | envipyengine/config.py | get_environment | def get_environment():
"""
Return all environment values from the config files. Values
stored in the user configuration file will take precedence
over values stored in the system configuration file.
:return: A dictionary containing the name/value pairs of all
environment settings in th... | python | def get_environment():
"""
Return all environment values from the config files. Values
stored in the user configuration file will take precedence
over values stored in the system configuration file.
:return: A dictionary containing the name/value pairs of all
environment settings in th... | [
"def",
"get_environment",
"(",
")",
":",
"section",
"=",
"_ENVIRONMENT_SECTION_NAME",
"# Read system",
"sys_cfg",
"=",
"_read_config",
"(",
"_SYSTEM_CONFIG_FILE",
")",
"sys_env",
"=",
"dict",
"(",
"sys_cfg",
".",
"items",
"(",
"section",
")",
")",
"if",
"sys_cfg... | Return all environment values from the config files. Values
stored in the user configuration file will take precedence
over values stored in the system configuration file.
:return: A dictionary containing the name/value pairs of all
environment settings in the config file. | [
"Return",
"all",
"environment",
"values",
"from",
"the",
"config",
"files",
".",
"Values",
"stored",
"in",
"the",
"user",
"configuration",
"file",
"will",
"take",
"precedence",
"over",
"values",
"stored",
"in",
"the",
"system",
"configuration",
"file",
"."
] | 567b639d6592deec3289f6122a9e3d18f2f98432 | https://github.com/envi-idl/envipyengine/blob/567b639d6592deec3289f6122a9e3d18f2f98432/envipyengine/config.py#L176-L199 | train |
envi-idl/envipyengine | envipyengine/config.py | set_environment | def set_environment(environment, system=False):
"""
Set engine environment values in the config file.
:param environment: A dictionary containing the environment variable
settings as key/value pairs.
:keyword system: Set to True to modify the system configuration file.
... | python | def set_environment(environment, system=False):
"""
Set engine environment values in the config file.
:param environment: A dictionary containing the environment variable
settings as key/value pairs.
:keyword system: Set to True to modify the system configuration file.
... | [
"def",
"set_environment",
"(",
"environment",
",",
"system",
"=",
"False",
")",
":",
"config_filename",
"=",
"_SYSTEM_CONFIG_FILE",
"if",
"system",
"is",
"True",
"else",
"_USER_CONFIG_FILE",
"config",
"=",
"_read_config",
"(",
"config_filename",
")",
"section",
"=... | Set engine environment values in the config file.
:param environment: A dictionary containing the environment variable
settings as key/value pairs.
:keyword system: Set to True to modify the system configuration file.
If not set, the user config file will be modifie... | [
"Set",
"engine",
"environment",
"values",
"in",
"the",
"config",
"file",
"."
] | 567b639d6592deec3289f6122a9e3d18f2f98432 | https://github.com/envi-idl/envipyengine/blob/567b639d6592deec3289f6122a9e3d18f2f98432/envipyengine/config.py#L202-L218 | train |
envi-idl/envipyengine | envipyengine/config.py | remove_environment | def remove_environment(environment_var_name, system=False):
"""
Remove the specified environment setting from the appropriate config file.
:param environment_var_name: The name of the environment setting to remove.
:keyword system: Set to True to modify the system configuration file.
... | python | def remove_environment(environment_var_name, system=False):
"""
Remove the specified environment setting from the appropriate config file.
:param environment_var_name: The name of the environment setting to remove.
:keyword system: Set to True to modify the system configuration file.
... | [
"def",
"remove_environment",
"(",
"environment_var_name",
",",
"system",
"=",
"False",
")",
":",
"config_filename",
"=",
"_SYSTEM_CONFIG_FILE",
"if",
"system",
"is",
"True",
"else",
"_USER_CONFIG_FILE",
"config",
"=",
"_read_config",
"(",
"config_filename",
")",
"se... | Remove the specified environment setting from the appropriate config file.
:param environment_var_name: The name of the environment setting to remove.
:keyword system: Set to True to modify the system configuration file.
If not set, the user config file will be modified. | [
"Remove",
"the",
"specified",
"environment",
"setting",
"from",
"the",
"appropriate",
"config",
"file",
"."
] | 567b639d6592deec3289f6122a9e3d18f2f98432 | https://github.com/envi-idl/envipyengine/blob/567b639d6592deec3289f6122a9e3d18f2f98432/envipyengine/config.py#L221-L235 | train |
envi-idl/envipyengine | envipyengine/config.py | get | def get(property_name):
"""
Returns the value of the specified configuration property.
Property values stored in the user configuration file take
precedence over values stored in the system configuration
file.
:param property_name: The name of the property to retrieve.
:return: The value of... | python | def get(property_name):
"""
Returns the value of the specified configuration property.
Property values stored in the user configuration file take
precedence over values stored in the system configuration
file.
:param property_name: The name of the property to retrieve.
:return: The value of... | [
"def",
"get",
"(",
"property_name",
")",
":",
"config",
"=",
"_read_config",
"(",
"_USER_CONFIG_FILE",
")",
"section",
"=",
"_MAIN_SECTION_NAME",
"try",
":",
"property_value",
"=",
"config",
".",
"get",
"(",
"section",
",",
"property_name",
")",
"except",
"(",... | Returns the value of the specified configuration property.
Property values stored in the user configuration file take
precedence over values stored in the system configuration
file.
:param property_name: The name of the property to retrieve.
:return: The value of the property. | [
"Returns",
"the",
"value",
"of",
"the",
"specified",
"configuration",
"property",
".",
"Property",
"values",
"stored",
"in",
"the",
"user",
"configuration",
"file",
"take",
"precedence",
"over",
"values",
"stored",
"in",
"the",
"system",
"configuration",
"file",
... | 567b639d6592deec3289f6122a9e3d18f2f98432 | https://github.com/envi-idl/envipyengine/blob/567b639d6592deec3289f6122a9e3d18f2f98432/envipyengine/config.py#L238-L261 | train |
envi-idl/envipyengine | envipyengine/config.py | set | def set(property_name, value, system=False):
"""
Sets the configuration property to the specified value.
:param property_name: The name of the property to set.
:param value: The value for the property.
:keyword system: Set to True to modify the system configuration file.
If not... | python | def set(property_name, value, system=False):
"""
Sets the configuration property to the specified value.
:param property_name: The name of the property to set.
:param value: The value for the property.
:keyword system: Set to True to modify the system configuration file.
If not... | [
"def",
"set",
"(",
"property_name",
",",
"value",
",",
"system",
"=",
"False",
")",
":",
"config_filename",
"=",
"_SYSTEM_CONFIG_FILE",
"if",
"system",
"is",
"True",
"else",
"_USER_CONFIG_FILE",
"config",
"=",
"_read_config",
"(",
"config_filename",
")",
"sectio... | Sets the configuration property to the specified value.
:param property_name: The name of the property to set.
:param value: The value for the property.
:keyword system: Set to True to modify the system configuration file.
If not set, the user config file will be modified. | [
"Sets",
"the",
"configuration",
"property",
"to",
"the",
"specified",
"value",
"."
] | 567b639d6592deec3289f6122a9e3d18f2f98432 | https://github.com/envi-idl/envipyengine/blob/567b639d6592deec3289f6122a9e3d18f2f98432/envipyengine/config.py#L264-L279 | train |
bigdatacesga/service-discovery | consul.py | Client.register | def register(self, id, name, address, port=None, tags=None, check=None):
"""Register a new service with the local consul agent"""
service = {}
service['ID'] = id
service['Name'] = name
service['Address'] = address
if port:
service['Port'] = int(port)
i... | python | def register(self, id, name, address, port=None, tags=None, check=None):
"""Register a new service with the local consul agent"""
service = {}
service['ID'] = id
service['Name'] = name
service['Address'] = address
if port:
service['Port'] = int(port)
i... | [
"def",
"register",
"(",
"self",
",",
"id",
",",
"name",
",",
"address",
",",
"port",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"check",
"=",
"None",
")",
":",
"service",
"=",
"{",
"}",
"service",
"[",
"'ID'",
"]",
"=",
"id",
"service",
"[",
"... | Register a new service with the local consul agent | [
"Register",
"a",
"new",
"service",
"with",
"the",
"local",
"consul",
"agent"
] | 5298d68e4dbe7b23848c95a6f75b9d469fb29e4a | https://github.com/bigdatacesga/service-discovery/blob/5298d68e4dbe7b23848c95a6f75b9d469fb29e4a/consul.py#L88-L104 | train |
bigdatacesga/service-discovery | consul.py | Client.deregister | def deregister(self, id):
"""Deregister a service with the local consul agent"""
r = requests.put('{}/{}'.format(self.url_deregister, id))
if r.status_code != 200:
raise consulDeregistrationError(
'PUT returned {}'.format(r.status_code))
return r | python | def deregister(self, id):
"""Deregister a service with the local consul agent"""
r = requests.put('{}/{}'.format(self.url_deregister, id))
if r.status_code != 200:
raise consulDeregistrationError(
'PUT returned {}'.format(r.status_code))
return r | [
"def",
"deregister",
"(",
"self",
",",
"id",
")",
":",
"r",
"=",
"requests",
".",
"put",
"(",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"url_deregister",
",",
"id",
")",
")",
"if",
"r",
".",
"status_code",
"!=",
"200",
":",
"raise",
"consulDeregist... | Deregister a service with the local consul agent | [
"Deregister",
"a",
"service",
"with",
"the",
"local",
"consul",
"agent"
] | 5298d68e4dbe7b23848c95a6f75b9d469fb29e4a | https://github.com/bigdatacesga/service-discovery/blob/5298d68e4dbe7b23848c95a6f75b9d469fb29e4a/consul.py#L106-L112 | train |
bigdatacesga/service-discovery | consul.py | Client.info | def info(self, name):
"""Info about a given service"""
r = requests.get('{}/{}'.format(self.url_service, name))
return r.json() | python | def info(self, name):
"""Info about a given service"""
r = requests.get('{}/{}'.format(self.url_service, name))
return r.json() | [
"def",
"info",
"(",
"self",
",",
"name",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"url_service",
",",
"name",
")",
")",
"return",
"r",
".",
"json",
"(",
")"
] | Info about a given service | [
"Info",
"about",
"a",
"given",
"service"
] | 5298d68e4dbe7b23848c95a6f75b9d469fb29e4a | https://github.com/bigdatacesga/service-discovery/blob/5298d68e4dbe7b23848c95a6f75b9d469fb29e4a/consul.py#L119-L122 | train |
ariebovenberg/snug | tutorial/relations.py | repo.star | def star(self) -> snug.Query[bool]:
"""star this repo"""
req = snug.PUT(BASE + f'/user/starred/{self.owner}/{self.name}')
return (yield req).status_code == 204 | python | def star(self) -> snug.Query[bool]:
"""star this repo"""
req = snug.PUT(BASE + f'/user/starred/{self.owner}/{self.name}')
return (yield req).status_code == 204 | [
"def",
"star",
"(",
"self",
")",
"->",
"snug",
".",
"Query",
"[",
"bool",
"]",
":",
"req",
"=",
"snug",
".",
"PUT",
"(",
"BASE",
"+",
"f'/user/starred/{self.owner}/{self.name}'",
")",
"return",
"(",
"yield",
"req",
")",
".",
"status_code",
"==",
"204"
] | star this repo | [
"star",
"this",
"repo"
] | 4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef | https://github.com/ariebovenberg/snug/blob/4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef/tutorial/relations.py#L15-L18 | train |
eclipse/unide.python | src/unide/message.py | device_message | def device_message(device,
code,
ts=None,
origin=None,
type=None,
severity=None,
title=None,
description=None,
hint=None,
**metaData):
# pylint: ... | python | def device_message(device,
code,
ts=None,
origin=None,
type=None,
severity=None,
title=None,
description=None,
hint=None,
**metaData):
# pylint: ... | [
"def",
"device_message",
"(",
"device",
",",
"code",
",",
"ts",
"=",
"None",
",",
"origin",
"=",
"None",
",",
"type",
"=",
"None",
",",
"severity",
"=",
"None",
",",
"title",
"=",
"None",
",",
"description",
"=",
"None",
",",
"hint",
"=",
"None",
"... | This quickly builds a time-stamped message. If `ts` is None, the
current time is used. | [
"This",
"quickly",
"builds",
"a",
"time",
"-",
"stamped",
"message",
".",
"If",
"ts",
"is",
"None",
"the",
"current",
"time",
"is",
"used",
"."
] | b82e6a0bf7cc44a463c5d7cdb3d2199f8320c493 | https://github.com/eclipse/unide.python/blob/b82e6a0bf7cc44a463c5d7cdb3d2199f8320c493/src/unide/message.py#L120-L148 | train |
MacHu-GWU/single_file_module-project | sfm/obj_file_io.py | _dump | def _dump(obj, abspath, serializer_type,
dumper_func=None,
compress=True,
overwrite=False,
verbose=False,
**kwargs):
"""Dump object to file.
:param abspath: The file path you want dump to.
:type abspath: str
:param serializer_type: 'binary' or 'str'.
... | python | def _dump(obj, abspath, serializer_type,
dumper_func=None,
compress=True,
overwrite=False,
verbose=False,
**kwargs):
"""Dump object to file.
:param abspath: The file path you want dump to.
:type abspath: str
:param serializer_type: 'binary' or 'str'.
... | [
"def",
"_dump",
"(",
"obj",
",",
"abspath",
",",
"serializer_type",
",",
"dumper_func",
"=",
"None",
",",
"compress",
"=",
"True",
",",
"overwrite",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"_check_serializer_type",
... | Dump object to file.
:param abspath: The file path you want dump to.
:type abspath: str
:param serializer_type: 'binary' or 'str'.
:type serializer_type: str
:param dumper_func: A dumper function that takes an object as input, return
binary or string.
:type dumper_func: callable funct... | [
"Dump",
"object",
"to",
"file",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/obj_file_io.py#L80-L145 | train |
MacHu-GWU/single_file_module-project | sfm/obj_file_io.py | _load | def _load(abspath, serializer_type,
loader_func=None,
decompress=True,
verbose=False,
**kwargs):
"""load object from file.
:param abspath: The file path you want load from.
:type abspath: str
:param serializer_type: 'binary' or 'str'.
:type serializer_type: ... | python | def _load(abspath, serializer_type,
loader_func=None,
decompress=True,
verbose=False,
**kwargs):
"""load object from file.
:param abspath: The file path you want load from.
:type abspath: str
:param serializer_type: 'binary' or 'str'.
:type serializer_type: ... | [
"def",
"_load",
"(",
"abspath",
",",
"serializer_type",
",",
"loader_func",
"=",
"None",
",",
"decompress",
"=",
"True",
",",
"verbose",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"_check_serializer_type",
"(",
"serializer_type",
")",
"if",
"not",
"i... | load object from file.
:param abspath: The file path you want load from.
:type abspath: str
:param serializer_type: 'binary' or 'str'.
:type serializer_type: str
:param loader_func: A loader function that takes binary as input, return
an object.
:type loader_func: callable function
... | [
"load",
"object",
"from",
"file",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/obj_file_io.py#L148-L196 | train |
Pythonity/python-ivona-api | ivona_api/ivona_api.py | IvonaAPI._get_response | def _get_response(self, method, endpoint, data=None):
"""
Helper method for wrapping API requests, mainly for catching errors
in one place.
:param method: valid HTTP method
:type method: str
:param endpoint: API endpoint
:type endpoint: str
:param data: e... | python | def _get_response(self, method, endpoint, data=None):
"""
Helper method for wrapping API requests, mainly for catching errors
in one place.
:param method: valid HTTP method
:type method: str
:param endpoint: API endpoint
:type endpoint: str
:param data: e... | [
"def",
"_get_response",
"(",
"self",
",",
"method",
",",
"endpoint",
",",
"data",
"=",
"None",
")",
":",
"url",
"=",
"urljoin",
"(",
"IVONA_REGION_ENDPOINTS",
"[",
"self",
".",
"region",
"]",
",",
"endpoint",
")",
"response",
"=",
"getattr",
"(",
"self",... | Helper method for wrapping API requests, mainly for catching errors
in one place.
:param method: valid HTTP method
:type method: str
:param endpoint: API endpoint
:type endpoint: str
:param data: extra parameters passed with the request
:type data: dict
:... | [
"Helper",
"method",
"for",
"wrapping",
"API",
"requests",
"mainly",
"for",
"catching",
"errors",
"in",
"one",
"place",
"."
] | 490a2e502d4aa769b9f41603eb5d5e5ebf1ea912 | https://github.com/Pythonity/python-ivona-api/blob/490a2e502d4aa769b9f41603eb5d5e5ebf1ea912/ivona_api/ivona_api.py#L88-L116 | train |
Pythonity/python-ivona-api | ivona_api/ivona_api.py | IvonaAPI.get_available_voices | def get_available_voices(self, language=None, gender=None):
"""
Returns a list of available voices, via 'ListVoices' endpoint
Docs:
http://developer.ivona.com/en/speechcloud/actions.html#ListVoices
:param language: returned voices language
:type language: str
... | python | def get_available_voices(self, language=None, gender=None):
"""
Returns a list of available voices, via 'ListVoices' endpoint
Docs:
http://developer.ivona.com/en/speechcloud/actions.html#ListVoices
:param language: returned voices language
:type language: str
... | [
"def",
"get_available_voices",
"(",
"self",
",",
"language",
"=",
"None",
",",
"gender",
"=",
"None",
")",
":",
"endpoint",
"=",
"'ListVoices'",
"data",
"=",
"dict",
"(",
")",
"if",
"language",
":",
"data",
".",
"update",
"(",
"{",
"'Voice'",
":",
"{",... | Returns a list of available voices, via 'ListVoices' endpoint
Docs:
http://developer.ivona.com/en/speechcloud/actions.html#ListVoices
:param language: returned voices language
:type language: str
:param gender: returned voices gender
:type gender: str | [
"Returns",
"a",
"list",
"of",
"available",
"voices",
"via",
"ListVoices",
"endpoint"
] | 490a2e502d4aa769b9f41603eb5d5e5ebf1ea912 | https://github.com/Pythonity/python-ivona-api/blob/490a2e502d4aa769b9f41603eb5d5e5ebf1ea912/ivona_api/ivona_api.py#L118-L143 | train |
Pythonity/python-ivona-api | ivona_api/ivona_api.py | IvonaAPI.text_to_speech | def text_to_speech(self, text, file, voice_name=None, language=None):
"""
Saves given text synthesized audio file, via 'CreateSpeech' endpoint
Docs:
http://developer.ivona.com/en/speechcloud/actions.html#CreateSpeech
:param text: text to synthesize
:type text: str
... | python | def text_to_speech(self, text, file, voice_name=None, language=None):
"""
Saves given text synthesized audio file, via 'CreateSpeech' endpoint
Docs:
http://developer.ivona.com/en/speechcloud/actions.html#CreateSpeech
:param text: text to synthesize
:type text: str
... | [
"def",
"text_to_speech",
"(",
"self",
",",
"text",
",",
"file",
",",
"voice_name",
"=",
"None",
",",
"language",
"=",
"None",
")",
":",
"endpoint",
"=",
"'CreateSpeech'",
"data",
"=",
"{",
"'Input'",
":",
"{",
"'Data'",
":",
"text",
",",
"}",
",",
"'... | Saves given text synthesized audio file, via 'CreateSpeech' endpoint
Docs:
http://developer.ivona.com/en/speechcloud/actions.html#CreateSpeech
:param text: text to synthesize
:type text: str
:param file: file that will be used to save the audio
:type file: file
... | [
"Saves",
"given",
"text",
"synthesized",
"audio",
"file",
"via",
"CreateSpeech",
"endpoint"
] | 490a2e502d4aa769b9f41603eb5d5e5ebf1ea912 | https://github.com/Pythonity/python-ivona-api/blob/490a2e502d4aa769b9f41603eb5d5e5ebf1ea912/ivona_api/ivona_api.py#L145-L184 | train |
configcat/python-sdk | configcatclient/__init__.py | create_client_with_auto_poll | def create_client_with_auto_poll(api_key, poll_interval_seconds=60, max_init_wait_time_seconds=5,
on_configuration_changed_callback=None, config_cache_class=None,
base_url=None):
"""
Create an instance of ConfigCatClient and setup Auto Poll mode ... | python | def create_client_with_auto_poll(api_key, poll_interval_seconds=60, max_init_wait_time_seconds=5,
on_configuration_changed_callback=None, config_cache_class=None,
base_url=None):
"""
Create an instance of ConfigCatClient and setup Auto Poll mode ... | [
"def",
"create_client_with_auto_poll",
"(",
"api_key",
",",
"poll_interval_seconds",
"=",
"60",
",",
"max_init_wait_time_seconds",
"=",
"5",
",",
"on_configuration_changed_callback",
"=",
"None",
",",
"config_cache_class",
"=",
"None",
",",
"base_url",
"=",
"None",
")... | Create an instance of ConfigCatClient and setup Auto Poll mode with custom options
:param api_key: ConfigCat ApiKey to access your configuration.
:param poll_interval_seconds: The client's poll interval in seconds. Default: 60 seconds.
:param on_configuration_changed_callback: You can subscribe to configur... | [
"Create",
"an",
"instance",
"of",
"ConfigCatClient",
"and",
"setup",
"Auto",
"Poll",
"mode",
"with",
"custom",
"options"
] | 7a893c7958d928276ca02c00d5239987a1acb8d6 | https://github.com/configcat/python-sdk/blob/7a893c7958d928276ca02c00d5239987a1acb8d6/configcatclient/__init__.py#L14-L39 | train |
configcat/python-sdk | configcatclient/__init__.py | create_client_with_lazy_load | def create_client_with_lazy_load(api_key, cache_time_to_live_seconds=60, config_cache_class=None,
base_url=None):
"""
Create an instance of ConfigCatClient and setup Lazy Load mode with custom options
:param api_key: ConfigCat ApiKey to access your configuration.
:param... | python | def create_client_with_lazy_load(api_key, cache_time_to_live_seconds=60, config_cache_class=None,
base_url=None):
"""
Create an instance of ConfigCatClient and setup Lazy Load mode with custom options
:param api_key: ConfigCat ApiKey to access your configuration.
:param... | [
"def",
"create_client_with_lazy_load",
"(",
"api_key",
",",
"cache_time_to_live_seconds",
"=",
"60",
",",
"config_cache_class",
"=",
"None",
",",
"base_url",
"=",
"None",
")",
":",
"if",
"api_key",
"is",
"None",
":",
"raise",
"ConfigCatClientException",
"(",
"'API... | Create an instance of ConfigCatClient and setup Lazy Load mode with custom options
:param api_key: ConfigCat ApiKey to access your configuration.
:param cache_time_to_live_seconds: The cache TTL.
:param config_cache_class: If you want to use custom caching instead of the client's default InMemoryConfigCach... | [
"Create",
"an",
"instance",
"of",
"ConfigCatClient",
"and",
"setup",
"Lazy",
"Load",
"mode",
"with",
"custom",
"options"
] | 7a893c7958d928276ca02c00d5239987a1acb8d6 | https://github.com/configcat/python-sdk/blob/7a893c7958d928276ca02c00d5239987a1acb8d6/configcatclient/__init__.py#L42-L60 | train |
configcat/python-sdk | configcatclient/__init__.py | create_client_with_manual_poll | def create_client_with_manual_poll(api_key, config_cache_class=None,
base_url=None):
"""
Create an instance of ConfigCatClient and setup Manual Poll mode with custom options
:param api_key: ConfigCat ApiKey to access your configuration.
:param config_cache_class: If y... | python | def create_client_with_manual_poll(api_key, config_cache_class=None,
base_url=None):
"""
Create an instance of ConfigCatClient and setup Manual Poll mode with custom options
:param api_key: ConfigCat ApiKey to access your configuration.
:param config_cache_class: If y... | [
"def",
"create_client_with_manual_poll",
"(",
"api_key",
",",
"config_cache_class",
"=",
"None",
",",
"base_url",
"=",
"None",
")",
":",
"if",
"api_key",
"is",
"None",
":",
"raise",
"ConfigCatClientException",
"(",
"'API Key is required.'",
")",
"return",
"ConfigCat... | Create an instance of ConfigCatClient and setup Manual Poll mode with custom options
:param api_key: ConfigCat ApiKey to access your configuration.
:param config_cache_class: If you want to use custom caching instead of the client's default InMemoryConfigCache,
You can provide an implementation of ConfigCa... | [
"Create",
"an",
"instance",
"of",
"ConfigCatClient",
"and",
"setup",
"Manual",
"Poll",
"mode",
"with",
"custom",
"options"
] | 7a893c7958d928276ca02c00d5239987a1acb8d6 | https://github.com/configcat/python-sdk/blob/7a893c7958d928276ca02c00d5239987a1acb8d6/configcatclient/__init__.py#L63-L77 | train |
ariebovenberg/snug | examples/ns/query.py | basic_query | def basic_query(returns):
"""decorator factory for NS queries"""
return compose(
reusable,
map_send(parse_request),
map_yield(prepare_params, snug.prefix_adder(API_PREFIX)),
map_return(loads(returns)),
oneyield,
) | python | def basic_query(returns):
"""decorator factory for NS queries"""
return compose(
reusable,
map_send(parse_request),
map_yield(prepare_params, snug.prefix_adder(API_PREFIX)),
map_return(loads(returns)),
oneyield,
) | [
"def",
"basic_query",
"(",
"returns",
")",
":",
"return",
"compose",
"(",
"reusable",
",",
"map_send",
"(",
"parse_request",
")",
",",
"map_yield",
"(",
"prepare_params",
",",
"snug",
".",
"prefix_adder",
"(",
"API_PREFIX",
")",
")",
",",
"map_return",
"(",
... | decorator factory for NS queries | [
"decorator",
"factory",
"for",
"NS",
"queries"
] | 4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef | https://github.com/ariebovenberg/snug/blob/4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef/examples/ns/query.py#L43-L51 | train |
ariebovenberg/snug | examples/ns/query.py | departures | def departures(station: str) -> snug.Query[t.List[Departure]]:
"""departures for a station"""
return snug.GET('avt', params={'station': station}) | python | def departures(station: str) -> snug.Query[t.List[Departure]]:
"""departures for a station"""
return snug.GET('avt', params={'station': station}) | [
"def",
"departures",
"(",
"station",
":",
"str",
")",
"->",
"snug",
".",
"Query",
"[",
"t",
".",
"List",
"[",
"Departure",
"]",
"]",
":",
"return",
"snug",
".",
"GET",
"(",
"'avt'",
",",
"params",
"=",
"{",
"'station'",
":",
"station",
"}",
")"
] | departures for a station | [
"departures",
"for",
"a",
"station"
] | 4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef | https://github.com/ariebovenberg/snug/blob/4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef/examples/ns/query.py#L61-L63 | train |
ariebovenberg/snug | examples/ns/query.py | journey_options | def journey_options(origin: str,
destination: str,
via: t.Optional[str]=None,
before: t.Optional[int]=None,
after: t.Optional[int]=None,
time: t.Optional[datetime]=None,
... | python | def journey_options(origin: str,
destination: str,
via: t.Optional[str]=None,
before: t.Optional[int]=None,
after: t.Optional[int]=None,
time: t.Optional[datetime]=None,
... | [
"def",
"journey_options",
"(",
"origin",
":",
"str",
",",
"destination",
":",
"str",
",",
"via",
":",
"t",
".",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"before",
":",
"t",
".",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"after",
":",
"... | journey recommendations from an origin to a destination station | [
"journey",
"recommendations",
"from",
"an",
"origin",
"to",
"a",
"destination",
"station"
] | 4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef | https://github.com/ariebovenberg/snug/blob/4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef/examples/ns/query.py#L67-L86 | train |
MacHu-GWU/single_file_module-project | sfm/rnd.py | rand_str | def rand_str(length, allowed=CHARSET_ALPHA_DIGITS):
"""Generate fixed-length random string from your allowed character pool.
:param length: total length of this string.
:param allowed: allowed charset.
Example::
>>> import string
>>> rand_str(32)
H6ExQPNLzb4Vp3YZtfpyzLNPFwdfnw... | python | def rand_str(length, allowed=CHARSET_ALPHA_DIGITS):
"""Generate fixed-length random string from your allowed character pool.
:param length: total length of this string.
:param allowed: allowed charset.
Example::
>>> import string
>>> rand_str(32)
H6ExQPNLzb4Vp3YZtfpyzLNPFwdfnw... | [
"def",
"rand_str",
"(",
"length",
",",
"allowed",
"=",
"CHARSET_ALPHA_DIGITS",
")",
":",
"res",
"=",
"list",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"length",
")",
":",
"res",
".",
"append",
"(",
"random",
".",
"choice",
"(",
"allowed",
")",
")",
... | Generate fixed-length random string from your allowed character pool.
:param length: total length of this string.
:param allowed: allowed charset.
Example::
>>> import string
>>> rand_str(32)
H6ExQPNLzb4Vp3YZtfpyzLNPFwdfnwz6 | [
"Generate",
"fixed",
"-",
"length",
"random",
"string",
"from",
"your",
"allowed",
"character",
"pool",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/rnd.py#L25-L40 | train |
MacHu-GWU/single_file_module-project | sfm/rnd.py | rand_hexstr | def rand_hexstr(length, lower=True):
"""Gererate fixed-length random hexstring, usually for md5.
:param length: total length of this string.
:param lower: use lower case or upper case.
"""
if lower:
return rand_str(length, allowed=CHARSET_HEXSTR_LOWER)
else:
return rand_str(leng... | python | def rand_hexstr(length, lower=True):
"""Gererate fixed-length random hexstring, usually for md5.
:param length: total length of this string.
:param lower: use lower case or upper case.
"""
if lower:
return rand_str(length, allowed=CHARSET_HEXSTR_LOWER)
else:
return rand_str(leng... | [
"def",
"rand_hexstr",
"(",
"length",
",",
"lower",
"=",
"True",
")",
":",
"if",
"lower",
":",
"return",
"rand_str",
"(",
"length",
",",
"allowed",
"=",
"CHARSET_HEXSTR_LOWER",
")",
"else",
":",
"return",
"rand_str",
"(",
"length",
",",
"allowed",
"=",
"C... | Gererate fixed-length random hexstring, usually for md5.
:param length: total length of this string.
:param lower: use lower case or upper case. | [
"Gererate",
"fixed",
"-",
"length",
"random",
"hexstring",
"usually",
"for",
"md5",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/rnd.py#L43-L52 | train |
MacHu-GWU/single_file_module-project | sfm/rnd.py | rand_alphastr | def rand_alphastr(length, lower=True, upper=True):
"""Generate fixed-length random alpha only string.
"""
if lower is True and upper is True:
return rand_str(length, allowed=string.ascii_letters)
if lower is True and upper is False:
return rand_str(length, allowed=string.ascii_lowercase)... | python | def rand_alphastr(length, lower=True, upper=True):
"""Generate fixed-length random alpha only string.
"""
if lower is True and upper is True:
return rand_str(length, allowed=string.ascii_letters)
if lower is True and upper is False:
return rand_str(length, allowed=string.ascii_lowercase)... | [
"def",
"rand_alphastr",
"(",
"length",
",",
"lower",
"=",
"True",
",",
"upper",
"=",
"True",
")",
":",
"if",
"lower",
"is",
"True",
"and",
"upper",
"is",
"True",
":",
"return",
"rand_str",
"(",
"length",
",",
"allowed",
"=",
"string",
".",
"ascii_lette... | Generate fixed-length random alpha only string. | [
"Generate",
"fixed",
"-",
"length",
"random",
"alpha",
"only",
"string",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/rnd.py#L55-L65 | train |
MacHu-GWU/single_file_module-project | sfm/rnd.py | rand_article | def rand_article(num_p=(4, 10), num_s=(2, 15), num_w=(5, 40)):
"""Random article text.
Example::
>>> rand_article()
...
"""
article = list()
for _ in range(random.randint(*num_p)):
p = list()
for _ in range(random.randint(*num_s)):
s = list()
... | python | def rand_article(num_p=(4, 10), num_s=(2, 15), num_w=(5, 40)):
"""Random article text.
Example::
>>> rand_article()
...
"""
article = list()
for _ in range(random.randint(*num_p)):
p = list()
for _ in range(random.randint(*num_s)):
s = list()
... | [
"def",
"rand_article",
"(",
"num_p",
"=",
"(",
"4",
",",
"10",
")",
",",
"num_s",
"=",
"(",
"2",
",",
"15",
")",
",",
"num_w",
"=",
"(",
"5",
",",
"40",
")",
")",
":",
"article",
"=",
"list",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"rando... | Random article text.
Example::
>>> rand_article()
... | [
"Random",
"article",
"text",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/rnd.py#L120-L138 | train |
JanHendrikDolling/configvalidator | configvalidator/tools/parser.py | ParseObj._resolve_dep | def _resolve_dep(self, key):
"""
this method resolves dependencies for the given key.
call the method afther the item "key" was added to the list of avalable items
"""
if key in self.future_values_key_dep:
# there are some dependencies that can be resoled
... | python | def _resolve_dep(self, key):
"""
this method resolves dependencies for the given key.
call the method afther the item "key" was added to the list of avalable items
"""
if key in self.future_values_key_dep:
# there are some dependencies that can be resoled
... | [
"def",
"_resolve_dep",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"future_values_key_dep",
":",
"# there are some dependencies that can be resoled",
"dep_list",
"=",
"self",
".",
"future_values_key_dep",
"[",
"key",
"]",
"del",
"self",
".",... | this method resolves dependencies for the given key.
call the method afther the item "key" was added to the list of avalable items | [
"this",
"method",
"resolves",
"dependencies",
"for",
"the",
"given",
"key",
".",
"call",
"the",
"method",
"afther",
"the",
"item",
"key",
"was",
"added",
"to",
"the",
"list",
"of",
"avalable",
"items"
] | efde23a9352ae1fd6702b04ad964783ce11cbca5 | https://github.com/JanHendrikDolling/configvalidator/blob/efde23a9352ae1fd6702b04ad964783ce11cbca5/configvalidator/tools/parser.py#L132-L148 | train |
JanHendrikDolling/configvalidator | configvalidator/tools/parser.py | ParseObj._get_all_refs | def _get_all_refs(self, dep, handled_refs=None):
"""
get al list of all dependencies for the given item "dep"
"""
if handled_refs is None:
handled_refs = [dep]
else:
if dep in handled_refs:
return []
res = []
if dep in self.... | python | def _get_all_refs(self, dep, handled_refs=None):
"""
get al list of all dependencies for the given item "dep"
"""
if handled_refs is None:
handled_refs = [dep]
else:
if dep in handled_refs:
return []
res = []
if dep in self.... | [
"def",
"_get_all_refs",
"(",
"self",
",",
"dep",
",",
"handled_refs",
"=",
"None",
")",
":",
"if",
"handled_refs",
"is",
"None",
":",
"handled_refs",
"=",
"[",
"dep",
"]",
"else",
":",
"if",
"dep",
"in",
"handled_refs",
":",
"return",
"[",
"]",
"res",
... | get al list of all dependencies for the given item "dep" | [
"get",
"al",
"list",
"of",
"all",
"dependencies",
"for",
"the",
"given",
"item",
"dep"
] | efde23a9352ae1fd6702b04ad964783ce11cbca5 | https://github.com/JanHendrikDolling/configvalidator/blob/efde23a9352ae1fd6702b04ad964783ce11cbca5/configvalidator/tools/parser.py#L189-L206 | train |
ariebovenberg/snug | examples/github/query.py | BaseQuery.parse | def parse(response):
"""check for errors"""
if response.status_code == 400:
try:
msg = json.loads(response.content)['message']
except (KeyError, ValueError):
msg = ''
raise ApiError(msg)
return response | python | def parse(response):
"""check for errors"""
if response.status_code == 400:
try:
msg = json.loads(response.content)['message']
except (KeyError, ValueError):
msg = ''
raise ApiError(msg)
return response | [
"def",
"parse",
"(",
"response",
")",
":",
"if",
"response",
".",
"status_code",
"==",
"400",
":",
"try",
":",
"msg",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"content",
")",
"[",
"'message'",
"]",
"except",
"(",
"KeyError",
",",
"ValueError",
... | check for errors | [
"check",
"for",
"errors"
] | 4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef | https://github.com/ariebovenberg/snug/blob/4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef/examples/github/query.py#L68-L76 | train |
nugget/python-anthemav | anthemav/connection.py | Connection.create | def create(cls, host='localhost', port=14999,
auto_reconnect=True, loop=None, protocol_class=AVR,
update_callback=None):
"""Initiate a connection to a specific device.
Here is where we supply the host and port and callback callables we
expect for this AVR class obj... | python | def create(cls, host='localhost', port=14999,
auto_reconnect=True, loop=None, protocol_class=AVR,
update_callback=None):
"""Initiate a connection to a specific device.
Here is where we supply the host and port and callback callables we
expect for this AVR class obj... | [
"def",
"create",
"(",
"cls",
",",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"14999",
",",
"auto_reconnect",
"=",
"True",
",",
"loop",
"=",
"None",
",",
"protocol_class",
"=",
"AVR",
",",
"update_callback",
"=",
"None",
")",
":",
"assert",
"port",
"... | Initiate a connection to a specific device.
Here is where we supply the host and port and callback callables we
expect for this AVR class object.
:param host:
Hostname or IP address of the device
:param port:
TCP port number of the device
:param auto_rec... | [
"Initiate",
"a",
"connection",
"to",
"a",
"specific",
"device",
"."
] | c3cee38f2d452c1ab1335d9885e0769ec24d5f90 | https://github.com/nugget/python-anthemav/blob/c3cee38f2d452c1ab1335d9885e0769ec24d5f90/anthemav/connection.py#L23-L76 | train |
nugget/python-anthemav | anthemav/connection.py | Connection.close | def close(self):
"""Close the AVR device connection and don't try to reconnect."""
self.log.warning('Closing connection to AVR')
self._closing = True
if self.protocol.transport:
self.protocol.transport.close() | python | def close(self):
"""Close the AVR device connection and don't try to reconnect."""
self.log.warning('Closing connection to AVR')
self._closing = True
if self.protocol.transport:
self.protocol.transport.close() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"warning",
"(",
"'Closing connection to AVR'",
")",
"self",
".",
"_closing",
"=",
"True",
"if",
"self",
".",
"protocol",
".",
"transport",
":",
"self",
".",
"protocol",
".",
"transport",
"."... | Close the AVR device connection and don't try to reconnect. | [
"Close",
"the",
"AVR",
"device",
"connection",
"and",
"don",
"t",
"try",
"to",
"reconnect",
"."
] | c3cee38f2d452c1ab1335d9885e0769ec24d5f90 | https://github.com/nugget/python-anthemav/blob/c3cee38f2d452c1ab1335d9885e0769ec24d5f90/anthemav/connection.py#L117-L122 | train |
MacHu-GWU/single_file_module-project | sfm/ziplib.py | _compress_obj | def _compress_obj(obj, level):
"""Compress object to bytes.
"""
return zlib.compress(pickle.dumps(obj, protocol=2), level) | python | def _compress_obj(obj, level):
"""Compress object to bytes.
"""
return zlib.compress(pickle.dumps(obj, protocol=2), level) | [
"def",
"_compress_obj",
"(",
"obj",
",",
"level",
")",
":",
"return",
"zlib",
".",
"compress",
"(",
"pickle",
".",
"dumps",
"(",
"obj",
",",
"protocol",
"=",
"2",
")",
",",
"level",
")"
] | Compress object to bytes. | [
"Compress",
"object",
"to",
"bytes",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/ziplib.py#L34-L37 | train |
MacHu-GWU/single_file_module-project | sfm/ziplib.py | compress | def compress(obj, level=6, return_type="bytes"):
"""Compress anything to bytes or string.
:param obj: could be any object, usually it could be binary, string, or
regular python objec.t
:param level:
:param return_type: if bytes, then return bytes; if str, then return
base64.b64encode by... | python | def compress(obj, level=6, return_type="bytes"):
"""Compress anything to bytes or string.
:param obj: could be any object, usually it could be binary, string, or
regular python objec.t
:param level:
:param return_type: if bytes, then return bytes; if str, then return
base64.b64encode by... | [
"def",
"compress",
"(",
"obj",
",",
"level",
"=",
"6",
",",
"return_type",
"=",
"\"bytes\"",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"binary_type",
")",
":",
"b",
"=",
"_compress_bytes",
"(",
"obj",
",",
"level",
")",
"elif",
"isinstance",
"(",
... | Compress anything to bytes or string.
:param obj: could be any object, usually it could be binary, string, or
regular python objec.t
:param level:
:param return_type: if bytes, then return bytes; if str, then return
base64.b64encode bytes in utf-8 string. | [
"Compress",
"anything",
"to",
"bytes",
"or",
"string",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/ziplib.py#L52-L73 | train |
MacHu-GWU/single_file_module-project | sfm/ziplib.py | decompress | def decompress(obj, return_type="bytes"):
"""
De-compress it to it's original.
:param obj: Compressed object, could be bytes or str.
:param return_type: if bytes, then return bytes; if str, then use
base64.b64decode; if obj, then use pickle.loads return an object.
"""
if isinstance(obj,... | python | def decompress(obj, return_type="bytes"):
"""
De-compress it to it's original.
:param obj: Compressed object, could be bytes or str.
:param return_type: if bytes, then return bytes; if str, then use
base64.b64decode; if obj, then use pickle.loads return an object.
"""
if isinstance(obj,... | [
"def",
"decompress",
"(",
"obj",
",",
"return_type",
"=",
"\"bytes\"",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"binary_type",
")",
":",
"b",
"=",
"zlib",
".",
"decompress",
"(",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"string_types",
... | De-compress it to it's original.
:param obj: Compressed object, could be bytes or str.
:param return_type: if bytes, then return bytes; if str, then use
base64.b64decode; if obj, then use pickle.loads return an object. | [
"De",
"-",
"compress",
"it",
"to",
"it",
"s",
"original",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/ziplib.py#L76-L99 | train |
PSPC-SPAC-buyandsell/didauth | didauth/utils.py | build_signature_template | def build_signature_template(key_id, algorithm, headers):
"""
Build the Signature template for use with the Authorization header.
key_id is the mandatory label indicating to the server which secret to use
algorithm is one of the supported algorithms
headers is a list of http headers to be included ... | python | def build_signature_template(key_id, algorithm, headers):
"""
Build the Signature template for use with the Authorization header.
key_id is the mandatory label indicating to the server which secret to use
algorithm is one of the supported algorithms
headers is a list of http headers to be included ... | [
"def",
"build_signature_template",
"(",
"key_id",
",",
"algorithm",
",",
"headers",
")",
":",
"param_map",
"=",
"{",
"'keyId'",
":",
"key_id",
",",
"'algorithm'",
":",
"algorithm",
",",
"'signature'",
":",
"'%s'",
"}",
"if",
"headers",
":",
"headers",
"=",
... | Build the Signature template for use with the Authorization header.
key_id is the mandatory label indicating to the server which secret to use
algorithm is one of the supported algorithms
headers is a list of http headers to be included in the signing string.
The signature must be interpolated into th... | [
"Build",
"the",
"Signature",
"template",
"for",
"use",
"with",
"the",
"Authorization",
"header",
"."
] | e242fff8eddebf6ed52a65b161a229cdfbf5226e | https://github.com/PSPC-SPAC-buyandsell/didauth/blob/e242fff8eddebf6ed52a65b161a229cdfbf5226e/didauth/utils.py#L115-L135 | train |
MacHu-GWU/single_file_module-project | sfm/geo_search.py | GeoSearchEngine.train | def train(self, data, key_id, key_lat, key_lng, clear_old=True):
"""
Feed data into database.
:type data: list
:param data: list of point object, can have other metadata, for example:
[{"id": 10001, "lat": xxx, "lng": xxx}, ...]
:type key_id: callable
:param... | python | def train(self, data, key_id, key_lat, key_lng, clear_old=True):
"""
Feed data into database.
:type data: list
:param data: list of point object, can have other metadata, for example:
[{"id": 10001, "lat": xxx, "lng": xxx}, ...]
:type key_id: callable
:param... | [
"def",
"train",
"(",
"self",
",",
"data",
",",
"key_id",
",",
"key_lat",
",",
"key_lng",
",",
"clear_old",
"=",
"True",
")",
":",
"engine",
",",
"t_point",
"=",
"self",
".",
"engine",
",",
"self",
".",
"t_point",
"if",
"clear_old",
":",
"try",
":",
... | Feed data into database.
:type data: list
:param data: list of point object, can have other metadata, for example:
[{"id": 10001, "lat": xxx, "lng": xxx}, ...]
:type key_id: callable
:param key_id: callable function, take point object as input, return object
id,... | [
"Feed",
"data",
"into",
"database",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/geo_search.py#L55-L95 | train |
MacHu-GWU/single_file_module-project | sfm/geo_search.py | GeoSearchEngine.find_n_nearest | def find_n_nearest(self, lat, lng, n=5, radius=None):
"""Find n nearest point within certain distance from a point.
:param lat: latitude of center point.
:param lng: longitude of center point.
:param n: max number of record to return.
:param radius: only search point within ``ra... | python | def find_n_nearest(self, lat, lng, n=5, radius=None):
"""Find n nearest point within certain distance from a point.
:param lat: latitude of center point.
:param lng: longitude of center point.
:param n: max number of record to return.
:param radius: only search point within ``ra... | [
"def",
"find_n_nearest",
"(",
"self",
",",
"lat",
",",
"lng",
",",
"n",
"=",
"5",
",",
"radius",
"=",
"None",
")",
":",
"engine",
",",
"t_point",
"=",
"self",
".",
"engine",
",",
"self",
".",
"t_point",
"if",
"radius",
":",
"# Use a simple box filter t... | Find n nearest point within certain distance from a point.
:param lat: latitude of center point.
:param lng: longitude of center point.
:param n: max number of record to return.
:param radius: only search point within ``radius`` distance.
**中文文档** | [
"Find",
"n",
"nearest",
"point",
"within",
"certain",
"distance",
"from",
"a",
"point",
"."
] | 01f7a6b250853bebfd73de275895bf274325cfc1 | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/geo_search.py#L97-L141 | train |
SMAPPNYU/pysmap | pysmap/twitterutil/smapp_dataset.py | SmappDataset.sample | def sample(self, k):
'''
this method is especially troublesome
i do not reccommend making any changes to it
you may notice it uplicates code fro smappdragon
there is no way around this as far as i can tell
it really might screw up a lot of stuff, stip tweets
has ... | python | def sample(self, k):
'''
this method is especially troublesome
i do not reccommend making any changes to it
you may notice it uplicates code fro smappdragon
there is no way around this as far as i can tell
it really might screw up a lot of stuff, stip tweets
has ... | [
"def",
"sample",
"(",
"self",
",",
"k",
")",
":",
"def",
"new_get_iterators",
"(",
")",
":",
"tweet_parser",
"=",
"smappdragon",
".",
"TweetParser",
"(",
")",
"it",
"=",
"iter",
"(",
"self",
".",
"get_collection_iterators",
"(",
")",
")",
"sample",
"=",
... | this method is especially troublesome
i do not reccommend making any changes to it
you may notice it uplicates code fro smappdragon
there is no way around this as far as i can tell
it really might screw up a lot of stuff, stip tweets
has been purposely omitted as it isnt support... | [
"this",
"method",
"is",
"especially",
"troublesome",
"i",
"do",
"not",
"reccommend",
"making",
"any",
"changes",
"to",
"it",
"you",
"may",
"notice",
"it",
"uplicates",
"code",
"fro",
"smappdragon",
"there",
"is",
"no",
"way",
"around",
"this",
"as",
"far",
... | eb871992f40c53125129535e871525d5623c8c2d | https://github.com/SMAPPNYU/pysmap/blob/eb871992f40c53125129535e871525d5623c8c2d/pysmap/twitterutil/smapp_dataset.py#L451-L478 | train |
koszullab/metaTOR | metator/scripts/network.py | merge_networks | def merge_networks(output_file="merged_network.txt", *files):
"""Merge networks into a larger network.
A naive implementation for merging two networks in edgelist format.
Parameters
---------
output_file : file, str, or pathlib.Path, optional
The output file to write the merged network int... | python | def merge_networks(output_file="merged_network.txt", *files):
"""Merge networks into a larger network.
A naive implementation for merging two networks in edgelist format.
Parameters
---------
output_file : file, str, or pathlib.Path, optional
The output file to write the merged network int... | [
"def",
"merge_networks",
"(",
"output_file",
"=",
"\"merged_network.txt\"",
",",
"*",
"files",
")",
":",
"contacts",
"=",
"dict",
"(",
")",
"for",
"network_file",
"in",
"files",
":",
"with",
"open",
"(",
"network_file",
")",
"as",
"network_file_handle",
":",
... | Merge networks into a larger network.
A naive implementation for merging two networks in edgelist format.
Parameters
---------
output_file : file, str, or pathlib.Path, optional
The output file to write the merged network into. Default is
merged_network.txt
`*files` : file, str or ... | [
"Merge",
"networks",
"into",
"a",
"larger",
"network",
"."
] | 0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a | https://github.com/koszullab/metaTOR/blob/0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a/metator/scripts/network.py#L351-L388 | train |
koszullab/metaTOR | metator/scripts/network.py | merge_chunk_data | def merge_chunk_data(output_file="merged_idx_contig_hit_size_cov.txt", *files):
"""Merge chunk data from different networks
Similarly to merge_network, this merges any number of chunk data files.
Parameters
---------
output_file : file, str, or pathlib.Path, optional
The output file to wri... | python | def merge_chunk_data(output_file="merged_idx_contig_hit_size_cov.txt", *files):
"""Merge chunk data from different networks
Similarly to merge_network, this merges any number of chunk data files.
Parameters
---------
output_file : file, str, or pathlib.Path, optional
The output file to wri... | [
"def",
"merge_chunk_data",
"(",
"output_file",
"=",
"\"merged_idx_contig_hit_size_cov.txt\"",
",",
"*",
"files",
")",
":",
"chunks",
"=",
"dict",
"(",
")",
"for",
"chunk_file",
"in",
"files",
":",
"with",
"open",
"(",
"chunk_file",
")",
"as",
"chunk_file_handle"... | Merge chunk data from different networks
Similarly to merge_network, this merges any number of chunk data files.
Parameters
---------
output_file : file, str, or pathlib.Path, optional
The output file to write the merged chunk data files into. Default is
merged_idx_contig_hit_size_cov.... | [
"Merge",
"chunk",
"data",
"from",
"different",
"networks"
] | 0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a | https://github.com/koszullab/metaTOR/blob/0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a/metator/scripts/network.py#L391-L435 | train |
koszullab/metaTOR | metator/scripts/network.py | alignment_to_reads | def alignment_to_reads(
sam_merged,
output_dir,
parameters=DEFAULT_PARAMETERS,
save_memory=True,
*bin_fasta
):
"""Generate reads from ambiguous alignment file
Extract reads found to be mapping an input FASTA bin.
If one read maps, the whole pair is extracted and written
to the outpu... | python | def alignment_to_reads(
sam_merged,
output_dir,
parameters=DEFAULT_PARAMETERS,
save_memory=True,
*bin_fasta
):
"""Generate reads from ambiguous alignment file
Extract reads found to be mapping an input FASTA bin.
If one read maps, the whole pair is extracted and written
to the outpu... | [
"def",
"alignment_to_reads",
"(",
"sam_merged",
",",
"output_dir",
",",
"parameters",
"=",
"DEFAULT_PARAMETERS",
",",
"save_memory",
"=",
"True",
",",
"*",
"bin_fasta",
")",
":",
"# Just in case file objects are sent as input",
"def",
"get_file_string",
"(",
"file_thi... | Generate reads from ambiguous alignment file
Extract reads found to be mapping an input FASTA bin.
If one read maps, the whole pair is extracted and written
to the output paired-end FASTQ files. Reads that mapped
and weren't part of a pair are kept in a third 'single'
file for people who need it (e... | [
"Generate",
"reads",
"from",
"ambiguous",
"alignment",
"file"
] | 0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a | https://github.com/koszullab/metaTOR/blob/0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a/metator/scripts/network.py#L438-L574 | train |
Godley/MuseParse | MuseParse/classes/Input/MxmlParser.py | MxmlParser.ResetHandler | def ResetHandler(self, name):
'''
Method which assigns handler to the tag encountered before the current, or else
sets it to None
:param name: name of the latest tag
:return:
'''
if name in self.tags:
if len(self.tags) > 1:
key = len(... | python | def ResetHandler(self, name):
'''
Method which assigns handler to the tag encountered before the current, or else
sets it to None
:param name: name of the latest tag
:return:
'''
if name in self.tags:
if len(self.tags) > 1:
key = len(... | [
"def",
"ResetHandler",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"tags",
":",
"if",
"len",
"(",
"self",
".",
"tags",
")",
">",
"1",
":",
"key",
"=",
"len",
"(",
"self",
".",
"tags",
")",
"-",
"2",
"self",
".",
"hand... | Method which assigns handler to the tag encountered before the current, or else
sets it to None
:param name: name of the latest tag
:return: | [
"Method",
"which",
"assigns",
"handler",
"to",
"the",
"tag",
"encountered",
"before",
"the",
"current",
"or",
"else",
"sets",
"it",
"to",
"None"
] | 23cecafa1fdc0f2d6a87760553572b459f3c9904 | https://github.com/Godley/MuseParse/blob/23cecafa1fdc0f2d6a87760553572b459f3c9904/MuseParse/classes/Input/MxmlParser.py#L205-L225 | train |
uberVU/mongo-pool | mongo_pool/mongo_pool.py | MongoPool.get_cluster | def get_cluster(self, label):
"""Returns a connection to a mongo-clusters.
Args:
label (string): the label of a cluster.
Returns:
A connection to the cluster labeld with label.
Raises:
AttributeError: there is no cluster with the given label in the
... | python | def get_cluster(self, label):
"""Returns a connection to a mongo-clusters.
Args:
label (string): the label of a cluster.
Returns:
A connection to the cluster labeld with label.
Raises:
AttributeError: there is no cluster with the given label in the
... | [
"def",
"get_cluster",
"(",
"self",
",",
"label",
")",
":",
"for",
"cluster",
"in",
"self",
".",
"_clusters",
":",
"if",
"label",
"==",
"cluster",
"[",
"'label'",
"]",
":",
"return",
"self",
".",
"_get_connection",
"(",
"cluster",
")",
"raise",
"Attribute... | Returns a connection to a mongo-clusters.
Args:
label (string): the label of a cluster.
Returns:
A connection to the cluster labeld with label.
Raises:
AttributeError: there is no cluster with the given label in the
config | [
"Returns",
"a",
"connection",
"to",
"a",
"mongo",
"-",
"clusters",
"."
] | 286d1d8e0b3c17d5d7d4860487fe69358941067d | https://github.com/uberVU/mongo-pool/blob/286d1d8e0b3c17d5d7d4860487fe69358941067d/mongo_pool/mongo_pool.py#L26-L42 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.