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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Aluriak/bubble-tools | bubbletools/utils.py | line_type | def line_type(line:str) -> str:
"""Give type of input line, as defined in LINE_TYPES
>>> line_type('IN\\ta\\tb')
'IN'
>>> line_type('')
'EMPTY'
"""
for regex, ltype in LINE_TYPES.items():
if re.fullmatch(regex, line):
return ltype
raise ValueError("Input line \"{}\"... | python | def line_type(line:str) -> str:
"""Give type of input line, as defined in LINE_TYPES
>>> line_type('IN\\ta\\tb')
'IN'
>>> line_type('')
'EMPTY'
"""
for regex, ltype in LINE_TYPES.items():
if re.fullmatch(regex, line):
return ltype
raise ValueError("Input line \"{}\"... | [
"def",
"line_type",
"(",
"line",
":",
"str",
")",
"->",
"str",
":",
"for",
"regex",
",",
"ltype",
"in",
"LINE_TYPES",
".",
"items",
"(",
")",
":",
"if",
"re",
".",
"fullmatch",
"(",
"regex",
",",
"line",
")",
":",
"return",
"ltype",
"raise",
"Value... | Give type of input line, as defined in LINE_TYPES
>>> line_type('IN\\ta\\tb')
'IN'
>>> line_type('')
'EMPTY' | [
"Give",
"type",
"of",
"input",
"line",
"as",
"defined",
"in",
"LINE_TYPES"
] | f014f4a1986abefc80dc418feaa05ed258c2221a | https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/utils.py#L90-L102 | train | 56,900 |
Aluriak/bubble-tools | bubbletools/utils.py | line_data | def line_data(line:str) -> tuple:
"""Return groups found in given line
>>> line_data('IN\\ta\\tb')
('IN', 'a', 'b')
>>> line_data('')
()
"""
for regex, _ in LINE_TYPES.items():
match = re.fullmatch(regex, line)
if match:
return match.groups()
raise ValueErro... | python | def line_data(line:str) -> tuple:
"""Return groups found in given line
>>> line_data('IN\\ta\\tb')
('IN', 'a', 'b')
>>> line_data('')
()
"""
for regex, _ in LINE_TYPES.items():
match = re.fullmatch(regex, line)
if match:
return match.groups()
raise ValueErro... | [
"def",
"line_data",
"(",
"line",
":",
"str",
")",
"->",
"tuple",
":",
"for",
"regex",
",",
"_",
"in",
"LINE_TYPES",
".",
"items",
"(",
")",
":",
"match",
"=",
"re",
".",
"fullmatch",
"(",
"regex",
",",
"line",
")",
"if",
"match",
":",
"return",
"... | Return groups found in given line
>>> line_data('IN\\ta\\tb')
('IN', 'a', 'b')
>>> line_data('')
() | [
"Return",
"groups",
"found",
"in",
"given",
"line"
] | f014f4a1986abefc80dc418feaa05ed258c2221a | https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/utils.py#L105-L118 | train | 56,901 |
mobinrg/rpi_spark_drives | JMRPiSpark/Drives/Screen/SSPILScreen.py | SSPILScreen._initBuffer | def _initBuffer(self, bufferColorMode, bufferSize):
"""!
\~english
Initialize the buffer object instance, use PIL Image as for buffer
@param bufferColorMode: "RGB" or "1"
@param bufferSize: (width, height)
\~chinese
初始化缓冲区对象实例,使用PIL Image作为缓冲区
@param buffe... | python | def _initBuffer(self, bufferColorMode, bufferSize):
"""!
\~english
Initialize the buffer object instance, use PIL Image as for buffer
@param bufferColorMode: "RGB" or "1"
@param bufferSize: (width, height)
\~chinese
初始化缓冲区对象实例,使用PIL Image作为缓冲区
@param buffe... | [
"def",
"_initBuffer",
"(",
"self",
",",
"bufferColorMode",
",",
"bufferSize",
")",
":",
"# super(SSScreenBase)._initBuffer(bufferColorMode, bufferSize)",
"self",
".",
"_buffer_color_mode",
"=",
"bufferColorMode",
"#create screen image buffer and canvas",
"if",
"bufferSize",
"==... | !
\~english
Initialize the buffer object instance, use PIL Image as for buffer
@param bufferColorMode: "RGB" or "1"
@param bufferSize: (width, height)
\~chinese
初始化缓冲区对象实例,使用PIL Image作为缓冲区
@param bufferColorMode: 色彩模式, 取值: "RGB" 或 "1"
@param bufferSize: 缓存... | [
"!",
"\\",
"~english",
"Initialize",
"the",
"buffer",
"object",
"instance",
"use",
"PIL",
"Image",
"as",
"for",
"buffer"
] | e1602d8268a5ef48e9e0a8b37de89e0233f946ea | https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Screen/SSPILScreen.py#L88-L110 | train | 56,902 |
mobinrg/rpi_spark_drives | JMRPiSpark/Drives/Screen/SSPILScreen.py | SSPILScreen.clearCanvas | def clearCanvas(self, fillColor = 0 ):
"""!
\~engliash
Clear up canvas and fill color at same time
@param fillColor: a color value
@note
The fillColor value range depends on the setting of _buffer_color_mode.
* If it is SS_COLOR_MODE_MONO ("1") monochrom... | python | def clearCanvas(self, fillColor = 0 ):
"""!
\~engliash
Clear up canvas and fill color at same time
@param fillColor: a color value
@note
The fillColor value range depends on the setting of _buffer_color_mode.
* If it is SS_COLOR_MODE_MONO ("1") monochrom... | [
"def",
"clearCanvas",
"(",
"self",
",",
"fillColor",
"=",
"0",
")",
":",
"self",
".",
"Canvas",
".",
"rectangle",
"(",
"(",
"0",
",",
"0",
",",
"self",
".",
"_display_size",
"[",
"0",
"]",
",",
"self",
".",
"_display_size",
"[",
"1",
"]",
")",
",... | !
\~engliash
Clear up canvas and fill color at same time
@param fillColor: a color value
@note
The fillColor value range depends on the setting of _buffer_color_mode.
* If it is SS_COLOR_MODE_MONO ("1") monochrome mode, it can only select 0: black and 1: white
... | [
"!",
"\\",
"~engliash",
"Clear",
"up",
"canvas",
"and",
"fill",
"color",
"at",
"same",
"time"
] | e1602d8268a5ef48e9e0a8b37de89e0233f946ea | https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Screen/SSPILScreen.py#L120-L137 | train | 56,903 |
mobinrg/rpi_spark_drives | JMRPiSpark/Drives/Screen/SScreen.py | SSRect.resize | def resize(self, newWidth = 0, newHeight = 0):
"""!
\~english
Resize width and height of rectangles
@param newWidth: new width value
@param newHeight: new height value
\~chinese
重新设定矩形高宽
@param newWidth: 新宽度
@param newHeight: 新高度
"""
... | python | def resize(self, newWidth = 0, newHeight = 0):
"""!
\~english
Resize width and height of rectangles
@param newWidth: new width value
@param newHeight: new height value
\~chinese
重新设定矩形高宽
@param newWidth: 新宽度
@param newHeight: 新高度
"""
... | [
"def",
"resize",
"(",
"self",
",",
"newWidth",
"=",
"0",
",",
"newHeight",
"=",
"0",
")",
":",
"self",
".",
"height",
"=",
"newHeight",
"self",
".",
"width",
"=",
"newWidth"
] | !
\~english
Resize width and height of rectangles
@param newWidth: new width value
@param newHeight: new height value
\~chinese
重新设定矩形高宽
@param newWidth: 新宽度
@param newHeight: 新高度 | [
"!",
"\\",
"~english",
"Resize",
"width",
"and",
"height",
"of",
"rectangles"
] | e1602d8268a5ef48e9e0a8b37de89e0233f946ea | https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Screen/SScreen.py#L67-L79 | train | 56,904 |
mobinrg/rpi_spark_drives | JMRPiSpark/Drives/Screen/SScreen.py | SScreenBase.rotateDirection | def rotateDirection(self, displayDirection):
"""!
\~english rotate screen direction
@param displayDirection: Screen Direction. value can be chosen: 0, 90, 180, 270
\~chinese 旋转显示屏方向
@param displayDirection: 显示屏方向。可选值: 0, 90, 180, 270
\~
@note
\~en... | python | def rotateDirection(self, displayDirection):
"""!
\~english rotate screen direction
@param displayDirection: Screen Direction. value can be chosen: 0, 90, 180, 270
\~chinese 旋转显示屏方向
@param displayDirection: 显示屏方向。可选值: 0, 90, 180, 270
\~
@note
\~en... | [
"def",
"rotateDirection",
"(",
"self",
",",
"displayDirection",
")",
":",
"if",
"self",
".",
"_needSwapWH",
"(",
"self",
".",
"_display_direction",
",",
"displayDirection",
")",
":",
"self",
".",
"_display_size",
"=",
"(",
"self",
".",
"_display_size",
"[",
... | !
\~english rotate screen direction
@param displayDirection: Screen Direction. value can be chosen: 0, 90, 180, 270
\~chinese 旋转显示屏方向
@param displayDirection: 显示屏方向。可选值: 0, 90, 180, 270
\~
@note
\~english after rotate the View resize to screen size
... | [
"!",
"\\",
"~english",
"rotate",
"screen",
"direction"
] | e1602d8268a5ef48e9e0a8b37de89e0233f946ea | https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Screen/SScreen.py#L261-L278 | train | 56,905 |
inveniosoftware-attic/invenio-utils | invenio_utils/autodiscovery/__init__.py | autodiscover_modules | def autodiscover_modules(packages, related_name_re='.+',
ignore_exceptions=False):
"""Autodiscover function follows the pattern used by Celery.
:param packages: List of package names to auto discover modules in.
:type packages: list of str
:param related_name_re: Regular expres... | python | def autodiscover_modules(packages, related_name_re='.+',
ignore_exceptions=False):
"""Autodiscover function follows the pattern used by Celery.
:param packages: List of package names to auto discover modules in.
:type packages: list of str
:param related_name_re: Regular expres... | [
"def",
"autodiscover_modules",
"(",
"packages",
",",
"related_name_re",
"=",
"'.+'",
",",
"ignore_exceptions",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"'autodiscover_modules has been deprecated. '",
"'Use Flask-Registry instead.'",
",",
"DeprecationWarning",
... | Autodiscover function follows the pattern used by Celery.
:param packages: List of package names to auto discover modules in.
:type packages: list of str
:param related_name_re: Regular expression used to match modules names.
:type related_name_re: str
:param ignore_exceptions: Ignore exception whe... | [
"Autodiscover",
"function",
"follows",
"the",
"pattern",
"used",
"by",
"Celery",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/autodiscovery/__init__.py#L41-L73 | train | 56,906 |
inveniosoftware-attic/invenio-utils | invenio_utils/autodiscovery/__init__.py | find_related_modules | def find_related_modules(package, related_name_re='.+',
ignore_exceptions=False):
"""Find matching modules using a package and a module name pattern."""
warnings.warn('find_related_modules has been deprecated.',
DeprecationWarning)
package_elements = package.rsplit... | python | def find_related_modules(package, related_name_re='.+',
ignore_exceptions=False):
"""Find matching modules using a package and a module name pattern."""
warnings.warn('find_related_modules has been deprecated.',
DeprecationWarning)
package_elements = package.rsplit... | [
"def",
"find_related_modules",
"(",
"package",
",",
"related_name_re",
"=",
"'.+'",
",",
"ignore_exceptions",
"=",
"False",
")",
":",
"warnings",
".",
"warn",
"(",
"'find_related_modules has been deprecated.'",
",",
"DeprecationWarning",
")",
"package_elements",
"=",
... | Find matching modules using a package and a module name pattern. | [
"Find",
"matching",
"modules",
"using",
"a",
"package",
"and",
"a",
"module",
"name",
"pattern",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/autodiscovery/__init__.py#L76-L105 | train | 56,907 |
inveniosoftware-attic/invenio-utils | invenio_utils/autodiscovery/__init__.py | import_related_module | def import_related_module(package, pkg_path, related_name,
ignore_exceptions=False):
"""Import module from given path."""
try:
imp.find_module(related_name, pkg_path)
except ImportError:
return
try:
return getattr(
__import__('%s' % (package... | python | def import_related_module(package, pkg_path, related_name,
ignore_exceptions=False):
"""Import module from given path."""
try:
imp.find_module(related_name, pkg_path)
except ImportError:
return
try:
return getattr(
__import__('%s' % (package... | [
"def",
"import_related_module",
"(",
"package",
",",
"pkg_path",
",",
"related_name",
",",
"ignore_exceptions",
"=",
"False",
")",
":",
"try",
":",
"imp",
".",
"find_module",
"(",
"related_name",
",",
"pkg_path",
")",
"except",
"ImportError",
":",
"return",
"t... | Import module from given path. | [
"Import",
"module",
"from",
"given",
"path",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/autodiscovery/__init__.py#L108-L127 | train | 56,908 |
alexcepoi/cake | cake/color.py | ansi | def ansi(string, *args):
""" Convenience function to chain multiple ColorWrappers to a string """
ansi = ''
for arg in args:
arg = str(arg)
if not re.match(ANSI_PATTERN, arg):
raise ValueError('Additional arguments must be ansi strings')
ansi += arg
return ansi + string + colorama.Style.RESET_ALL | python | def ansi(string, *args):
""" Convenience function to chain multiple ColorWrappers to a string """
ansi = ''
for arg in args:
arg = str(arg)
if not re.match(ANSI_PATTERN, arg):
raise ValueError('Additional arguments must be ansi strings')
ansi += arg
return ansi + string + colorama.Style.RESET_ALL | [
"def",
"ansi",
"(",
"string",
",",
"*",
"args",
")",
":",
"ansi",
"=",
"''",
"for",
"arg",
"in",
"args",
":",
"arg",
"=",
"str",
"(",
"arg",
")",
"if",
"not",
"re",
".",
"match",
"(",
"ANSI_PATTERN",
",",
"arg",
")",
":",
"raise",
"ValueError",
... | Convenience function to chain multiple ColorWrappers to a string | [
"Convenience",
"function",
"to",
"chain",
"multiple",
"ColorWrappers",
"to",
"a",
"string"
] | 0fde58dfea1fdbfd632816d5850b47cb0f9ece64 | https://github.com/alexcepoi/cake/blob/0fde58dfea1fdbfd632816d5850b47cb0f9ece64/cake/color.py#L52-L64 | train | 56,909 |
alexcepoi/cake | cake/color.py | puts | def puts(*args, **kwargs):
"""
Full feature printing function featuring
trimming and padding for both files and ttys
"""
# parse kwargs
trim = kwargs.pop('trim', False)
padding = kwargs.pop('padding', None)
stream = kwargs.pop('stream', sys.stdout)
# HACK: check if stream is IndentedFile
indent = getatt... | python | def puts(*args, **kwargs):
"""
Full feature printing function featuring
trimming and padding for both files and ttys
"""
# parse kwargs
trim = kwargs.pop('trim', False)
padding = kwargs.pop('padding', None)
stream = kwargs.pop('stream', sys.stdout)
# HACK: check if stream is IndentedFile
indent = getatt... | [
"def",
"puts",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# parse kwargs",
"trim",
"=",
"kwargs",
".",
"pop",
"(",
"'trim'",
",",
"False",
")",
"padding",
"=",
"kwargs",
".",
"pop",
"(",
"'padding'",
",",
"None",
")",
"stream",
"=",
"kwa... | Full feature printing function featuring
trimming and padding for both files and ttys | [
"Full",
"feature",
"printing",
"function",
"featuring",
"trimming",
"and",
"padding",
"for",
"both",
"files",
"and",
"ttys"
] | 0fde58dfea1fdbfd632816d5850b47cb0f9ece64 | https://github.com/alexcepoi/cake/blob/0fde58dfea1fdbfd632816d5850b47cb0f9ece64/cake/color.py#L67-L133 | train | 56,910 |
chaosim/dao | dao/builtins/terminal.py | char_between | def char_between(lower, upper, func_name):
'''return current char and step if char is between lower and upper, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function'''
function = register_function(func_na... | python | def char_between(lower, upper, func_name):
'''return current char and step if char is between lower and upper, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function'''
function = register_function(func_na... | [
"def",
"char_between",
"(",
"lower",
",",
"upper",
",",
"func_name",
")",
":",
"function",
"=",
"register_function",
"(",
"func_name",
",",
"lambda",
"char",
":",
"lower",
"<=",
"char",
"<=",
"upper",
")",
"return",
"char_on_predicate",
"(",
"function",
")"
... | return current char and step if char is between lower and upper, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function | [
"return",
"current",
"char",
"and",
"step",
"if",
"char",
"is",
"between",
"lower",
"and",
"upper",
"where"
] | d7ba65c98ee063aefd1ff4eabb192d1536fdbaaa | https://github.com/chaosim/dao/blob/d7ba65c98ee063aefd1ff4eabb192d1536fdbaaa/dao/builtins/terminal.py#L82-L88 | train | 56,911 |
chaosim/dao | dao/builtins/terminal.py | char_in | def char_in(string, func_name):
'''return current char and step if char is in string, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function'''
function = register_function(func_name,
... | python | def char_in(string, func_name):
'''return current char and step if char is in string, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function'''
function = register_function(func_name,
... | [
"def",
"char_in",
"(",
"string",
",",
"func_name",
")",
":",
"function",
"=",
"register_function",
"(",
"func_name",
",",
"lambda",
"char",
":",
"char",
"in",
"string",
")",
"return",
"char_on_predicate",
"(",
"function",
")"
] | return current char and step if char is in string, where
@test: a python function with one argument, which tests on one char and return True or False
@test must be registered with register_function | [
"return",
"current",
"char",
"and",
"step",
"if",
"char",
"is",
"in",
"string",
"where"
] | d7ba65c98ee063aefd1ff4eabb192d1536fdbaaa | https://github.com/chaosim/dao/blob/d7ba65c98ee063aefd1ff4eabb192d1536fdbaaa/dao/builtins/terminal.py#L90-L96 | train | 56,912 |
devopsconsulting/vdt.version | vdt/version/repo.py | GitRepository.update_version | def update_version(self, version, step=1):
"Compute an new version and write it as a tag"
# update the version based on the flags passed.
if self.config.patch:
version.patch += step
if self.config.minor:
version.minor += step
if self.config.major:
... | python | def update_version(self, version, step=1):
"Compute an new version and write it as a tag"
# update the version based on the flags passed.
if self.config.patch:
version.patch += step
if self.config.minor:
version.minor += step
if self.config.major:
... | [
"def",
"update_version",
"(",
"self",
",",
"version",
",",
"step",
"=",
"1",
")",
":",
"# update the version based on the flags passed.",
"if",
"self",
".",
"config",
".",
"patch",
":",
"version",
".",
"patch",
"+=",
"step",
"if",
"self",
".",
"config",
".",... | Compute an new version and write it as a tag | [
"Compute",
"an",
"new",
"version",
"and",
"write",
"it",
"as",
"a",
"tag"
] | 25854ac9e1a26f1c7d31c26fd012781f05570574 | https://github.com/devopsconsulting/vdt.version/blob/25854ac9e1a26f1c7d31c26fd012781f05570574/vdt/version/repo.py#L32-L53 | train | 56,913 |
trevisanj/a99 | a99/gui/a_WDBRegistry.py | WDBRegistry._get_id | def _get_id(self):
"""Getter because using the id property from within was not working"""
ret = None
row = self.row
if row:
ret = row["id"]
return ret | python | def _get_id(self):
"""Getter because using the id property from within was not working"""
ret = None
row = self.row
if row:
ret = row["id"]
return ret | [
"def",
"_get_id",
"(",
"self",
")",
":",
"ret",
"=",
"None",
"row",
"=",
"self",
".",
"row",
"if",
"row",
":",
"ret",
"=",
"row",
"[",
"\"id\"",
"]",
"return",
"ret"
] | Getter because using the id property from within was not working | [
"Getter",
"because",
"using",
"the",
"id",
"property",
"from",
"within",
"was",
"not",
"working"
] | 193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539 | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/gui/a_WDBRegistry.py#L195-L201 | train | 56,914 |
CodyKochmann/generators | generators/performance_tools.py | time_pipeline | def time_pipeline(iterable, *steps):
'''
This times the steps in a pipeline. Give it an iterable to test against
followed by the steps of the pipeline seperated in individual functions.
Example Usage:
```
from random import choice, randint
l = [randint(0,50) for i in range(100)]
step1 = lambda iterab... | python | def time_pipeline(iterable, *steps):
'''
This times the steps in a pipeline. Give it an iterable to test against
followed by the steps of the pipeline seperated in individual functions.
Example Usage:
```
from random import choice, randint
l = [randint(0,50) for i in range(100)]
step1 = lambda iterab... | [
"def",
"time_pipeline",
"(",
"iterable",
",",
"*",
"steps",
")",
":",
"if",
"callable",
"(",
"iterable",
")",
":",
"try",
":",
"iter",
"(",
"iterable",
"(",
")",
")",
"callable_base",
"=",
"True",
"except",
":",
"raise",
"TypeError",
"(",
"'time_pipeline... | This times the steps in a pipeline. Give it an iterable to test against
followed by the steps of the pipeline seperated in individual functions.
Example Usage:
```
from random import choice, randint
l = [randint(0,50) for i in range(100)]
step1 = lambda iterable:(i for i in iterable if i%5==0)
step2 ... | [
"This",
"times",
"the",
"steps",
"in",
"a",
"pipeline",
".",
"Give",
"it",
"an",
"iterable",
"to",
"test",
"against",
"followed",
"by",
"the",
"steps",
"of",
"the",
"pipeline",
"seperated",
"in",
"individual",
"functions",
"."
] | e4ca4dd25d5023a94b0349c69d6224070cc2526f | https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/performance_tools.py#L48-L141 | train | 56,915 |
CodyKochmann/generators | generators/performance_tools.py | runs_per_second | def runs_per_second(generator, seconds=3):
'''
use this function as a profiler for both functions and generators
to see how many iterations or cycles they can run per second
Example usage for timing simple operations/functions:
```
print(runs_per_second(lambda:1+2))
# 2074558
print(runs_per_second(... | python | def runs_per_second(generator, seconds=3):
'''
use this function as a profiler for both functions and generators
to see how many iterations or cycles they can run per second
Example usage for timing simple operations/functions:
```
print(runs_per_second(lambda:1+2))
# 2074558
print(runs_per_second(... | [
"def",
"runs_per_second",
"(",
"generator",
",",
"seconds",
"=",
"3",
")",
":",
"assert",
"isinstance",
"(",
"seconds",
",",
"int",
")",
",",
"'runs_per_second needs seconds to be an int, not {}'",
".",
"format",
"(",
"repr",
"(",
"seconds",
")",
")",
"assert",
... | use this function as a profiler for both functions and generators
to see how many iterations or cycles they can run per second
Example usage for timing simple operations/functions:
```
print(runs_per_second(lambda:1+2))
# 2074558
print(runs_per_second(lambda:1-2))
# 2048523
print(runs_per_second... | [
"use",
"this",
"function",
"as",
"a",
"profiler",
"for",
"both",
"functions",
"and",
"generators",
"to",
"see",
"how",
"many",
"iterations",
"or",
"cycles",
"they",
"can",
"run",
"per",
"second"
] | e4ca4dd25d5023a94b0349c69d6224070cc2526f | https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/performance_tools.py#L145-L206 | train | 56,916 |
Titan-C/slaveparticles | slaveparticles/spins.py | fermion_avg | def fermion_avg(efermi, norm_hopping, func):
"""calcules for every slave it's average over the desired observable"""
if func == 'ekin':
func = bethe_ekin_zeroT
elif func == 'ocupation':
func = bethe_filling_zeroT
return np.asarray([func(ef, tz) for ef, tz in zip(efermi, norm_hopping)]) | python | def fermion_avg(efermi, norm_hopping, func):
"""calcules for every slave it's average over the desired observable"""
if func == 'ekin':
func = bethe_ekin_zeroT
elif func == 'ocupation':
func = bethe_filling_zeroT
return np.asarray([func(ef, tz) for ef, tz in zip(efermi, norm_hopping)]) | [
"def",
"fermion_avg",
"(",
"efermi",
",",
"norm_hopping",
",",
"func",
")",
":",
"if",
"func",
"==",
"'ekin'",
":",
"func",
"=",
"bethe_ekin_zeroT",
"elif",
"func",
"==",
"'ocupation'",
":",
"func",
"=",
"bethe_filling_zeroT",
"return",
"np",
".",
"asarray",... | calcules for every slave it's average over the desired observable | [
"calcules",
"for",
"every",
"slave",
"it",
"s",
"average",
"over",
"the",
"desired",
"observable"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L25-L32 | train | 56,917 |
Titan-C/slaveparticles | slaveparticles/spins.py | spinflipandhop | def spinflipandhop(slaves):
"""Calculates the interaction term of a spin flip and pair hopping"""
Sdw = [csr_matrix(spin_gen(slaves, i, 0)) for i in range(slaves)]
Sup = [mat.T for mat in Sdw]
sfh = np.zeros_like(Sup[0])
orbitals = slaves//2
for n in range(orbitals):
for m in range(n+1... | python | def spinflipandhop(slaves):
"""Calculates the interaction term of a spin flip and pair hopping"""
Sdw = [csr_matrix(spin_gen(slaves, i, 0)) for i in range(slaves)]
Sup = [mat.T for mat in Sdw]
sfh = np.zeros_like(Sup[0])
orbitals = slaves//2
for n in range(orbitals):
for m in range(n+1... | [
"def",
"spinflipandhop",
"(",
"slaves",
")",
":",
"Sdw",
"=",
"[",
"csr_matrix",
"(",
"spin_gen",
"(",
"slaves",
",",
"i",
",",
"0",
")",
")",
"for",
"i",
"in",
"range",
"(",
"slaves",
")",
"]",
"Sup",
"=",
"[",
"mat",
".",
"T",
"for",
"mat",
"... | Calculates the interaction term of a spin flip and pair hopping | [
"Calculates",
"the",
"interaction",
"term",
"of",
"a",
"spin",
"flip",
"and",
"pair",
"hopping"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L42-L58 | train | 56,918 |
Titan-C/slaveparticles | slaveparticles/spins.py | spin_z_op | def spin_z_op(param, oper):
"""Generates the required Sz operators, given the system parameter setup
and the operator dictionary"""
slaves = param['slaves']
oper['Sz'] = np.array([spin_z(slaves, spin) for spin in range(slaves)])
oper['Sz+1/2'] = oper['Sz'] + 0.5*np.eye(2**slaves)
oper['sumSz2... | python | def spin_z_op(param, oper):
"""Generates the required Sz operators, given the system parameter setup
and the operator dictionary"""
slaves = param['slaves']
oper['Sz'] = np.array([spin_z(slaves, spin) for spin in range(slaves)])
oper['Sz+1/2'] = oper['Sz'] + 0.5*np.eye(2**slaves)
oper['sumSz2... | [
"def",
"spin_z_op",
"(",
"param",
",",
"oper",
")",
":",
"slaves",
"=",
"param",
"[",
"'slaves'",
"]",
"oper",
"[",
"'Sz'",
"]",
"=",
"np",
".",
"array",
"(",
"[",
"spin_z",
"(",
"slaves",
",",
"spin",
")",
"for",
"spin",
"in",
"range",
"(",
"sla... | Generates the required Sz operators, given the system parameter setup
and the operator dictionary | [
"Generates",
"the",
"required",
"Sz",
"operators",
"given",
"the",
"system",
"parameter",
"setup",
"and",
"the",
"operator",
"dictionary"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L61-L70 | train | 56,919 |
Titan-C/slaveparticles | slaveparticles/spins.py | spin_gen_op | def spin_gen_op(oper, gauge):
"""Generates the generic spin matrices for the system"""
slaves = len(gauge)
oper['O'] = np.array([spin_gen(slaves, i, c) for i, c in enumerate(gauge)])
oper['O_d'] = np.transpose(oper['O'], (0, 2, 1))
oper['O_dO'] = np.einsum('...ij,...jk->...ik', oper['O_d'], oper['O'... | python | def spin_gen_op(oper, gauge):
"""Generates the generic spin matrices for the system"""
slaves = len(gauge)
oper['O'] = np.array([spin_gen(slaves, i, c) for i, c in enumerate(gauge)])
oper['O_d'] = np.transpose(oper['O'], (0, 2, 1))
oper['O_dO'] = np.einsum('...ij,...jk->...ik', oper['O_d'], oper['O'... | [
"def",
"spin_gen_op",
"(",
"oper",
",",
"gauge",
")",
":",
"slaves",
"=",
"len",
"(",
"gauge",
")",
"oper",
"[",
"'O'",
"]",
"=",
"np",
".",
"array",
"(",
"[",
"spin_gen",
"(",
"slaves",
",",
"i",
",",
"c",
")",
"for",
"i",
",",
"c",
"in",
"e... | Generates the generic spin matrices for the system | [
"Generates",
"the",
"generic",
"spin",
"matrices",
"for",
"the",
"system"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L73-L79 | train | 56,920 |
Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.set_filling | def set_filling(self, populations):
"""Sets the orbital enenergies for on the reference of the free case.
By setting the desired local populations on every orbital.
Then generate the necesary operators to respect such configuraion"""
populations = np.asarray(populations)
#
# s... | python | def set_filling(self, populations):
"""Sets the orbital enenergies for on the reference of the free case.
By setting the desired local populations on every orbital.
Then generate the necesary operators to respect such configuraion"""
populations = np.asarray(populations)
#
# s... | [
"def",
"set_filling",
"(",
"self",
",",
"populations",
")",
":",
"populations",
"=",
"np",
".",
"asarray",
"(",
"populations",
")",
"#",
"# self.param['orbital_e'] -= bethe_findfill_zeroT( \\",
"# self.param['avg_particles'],",
"# ... | Sets the orbital enenergies for on the reference of the free case.
By setting the desired local populations on every orbital.
Then generate the necesary operators to respect such configuraion | [
"Sets",
"the",
"orbital",
"enenergies",
"for",
"on",
"the",
"reference",
"of",
"the",
"free",
"case",
".",
"By",
"setting",
"the",
"desired",
"local",
"populations",
"on",
"every",
"orbital",
".",
"Then",
"generate",
"the",
"necesary",
"operators",
"to",
"re... | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L127-L143 | train | 56,921 |
Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.reset | def reset(self, populations, lag, mu, u_int, j_coup, mean_f):
"""Resets the system into the last known state as given by the input
values"""
self.set_filling(populations)
self.param['lambda'] = lag
self.param['orbital_e'] = mu
self.selfconsistency(u_int, j_coup, mean_... | python | def reset(self, populations, lag, mu, u_int, j_coup, mean_f):
"""Resets the system into the last known state as given by the input
values"""
self.set_filling(populations)
self.param['lambda'] = lag
self.param['orbital_e'] = mu
self.selfconsistency(u_int, j_coup, mean_... | [
"def",
"reset",
"(",
"self",
",",
"populations",
",",
"lag",
",",
"mu",
",",
"u_int",
",",
"j_coup",
",",
"mean_f",
")",
":",
"self",
".",
"set_filling",
"(",
"populations",
")",
"self",
".",
"param",
"[",
"'lambda'",
"]",
"=",
"lag",
"self",
".",
... | Resets the system into the last known state as given by the input
values | [
"Resets",
"the",
"system",
"into",
"the",
"last",
"known",
"state",
"as",
"given",
"by",
"the",
"input",
"values"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L145-L152 | train | 56,922 |
Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.update_H | def update_H(self, mean_field, l):
"""Updates the spin hamiltonian and recalculates its eigenbasis"""
self.H_s = self.spin_hamiltonian(mean_field, l)
try:
self.eig_energies, self.eig_states = diagonalize(self.H_s)
except np.linalg.linalg.LinAlgError:
np.savez('er... | python | def update_H(self, mean_field, l):
"""Updates the spin hamiltonian and recalculates its eigenbasis"""
self.H_s = self.spin_hamiltonian(mean_field, l)
try:
self.eig_energies, self.eig_states = diagonalize(self.H_s)
except np.linalg.linalg.LinAlgError:
np.savez('er... | [
"def",
"update_H",
"(",
"self",
",",
"mean_field",
",",
"l",
")",
":",
"self",
".",
"H_s",
"=",
"self",
".",
"spin_hamiltonian",
"(",
"mean_field",
",",
"l",
")",
"try",
":",
"self",
".",
"eig_energies",
",",
"self",
".",
"eig_states",
"=",
"diagonaliz... | Updates the spin hamiltonian and recalculates its eigenbasis | [
"Updates",
"the",
"spin",
"hamiltonian",
"and",
"recalculates",
"its",
"eigenbasis"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L154-L166 | train | 56,923 |
Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.spin_hamiltonian | def spin_hamiltonian(self, h, l):
"""Constructs the single site spin Hamiltonian"""
h_spin = np.einsum('i,ijk', h[1], self.oper['O'])
h_spin += np.einsum('i,ijk', h[0], self.oper['O_d'])
h_spin += np.einsum('i,ijk', l, self.oper['Sz+1/2'])
h_spin += self.oper['Hint']
re... | python | def spin_hamiltonian(self, h, l):
"""Constructs the single site spin Hamiltonian"""
h_spin = np.einsum('i,ijk', h[1], self.oper['O'])
h_spin += np.einsum('i,ijk', h[0], self.oper['O_d'])
h_spin += np.einsum('i,ijk', l, self.oper['Sz+1/2'])
h_spin += self.oper['Hint']
re... | [
"def",
"spin_hamiltonian",
"(",
"self",
",",
"h",
",",
"l",
")",
":",
"h_spin",
"=",
"np",
".",
"einsum",
"(",
"'i,ijk'",
",",
"h",
"[",
"1",
"]",
",",
"self",
".",
"oper",
"[",
"'O'",
"]",
")",
"h_spin",
"+=",
"np",
".",
"einsum",
"(",
"'i,ijk... | Constructs the single site spin Hamiltonian | [
"Constructs",
"the",
"single",
"site",
"spin",
"Hamiltonian"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L168-L175 | train | 56,924 |
Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.inter_spin_hamiltonian | def inter_spin_hamiltonian(self, u_int, J_coup):
"""Calculates the interaction Hamiltonian. The Hund coupling is a
fraction of the coulom interaction"""
J_coup *= u_int
h_int = (u_int - 2*J_coup)/2.*self.oper['sumSz2']
h_int += J_coup*self.oper['sumSz-sp2']
h_int -= J... | python | def inter_spin_hamiltonian(self, u_int, J_coup):
"""Calculates the interaction Hamiltonian. The Hund coupling is a
fraction of the coulom interaction"""
J_coup *= u_int
h_int = (u_int - 2*J_coup)/2.*self.oper['sumSz2']
h_int += J_coup*self.oper['sumSz-sp2']
h_int -= J... | [
"def",
"inter_spin_hamiltonian",
"(",
"self",
",",
"u_int",
",",
"J_coup",
")",
":",
"J_coup",
"*=",
"u_int",
"h_int",
"=",
"(",
"u_int",
"-",
"2",
"*",
"J_coup",
")",
"/",
"2.",
"*",
"self",
".",
"oper",
"[",
"'sumSz2'",
"]",
"h_int",
"+=",
"J_coup"... | Calculates the interaction Hamiltonian. The Hund coupling is a
fraction of the coulom interaction | [
"Calculates",
"the",
"interaction",
"Hamiltonian",
".",
"The",
"Hund",
"coupling",
"is",
"a",
"fraction",
"of",
"the",
"coulom",
"interaction"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L177-L186 | train | 56,925 |
Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.expected | def expected(self, observable, beta=1e5):
"""Wrapper to the expected_value function to fix the eigenbasis"""
return expected_value(observable,
self.eig_energies,
self.eig_states,
beta) | python | def expected(self, observable, beta=1e5):
"""Wrapper to the expected_value function to fix the eigenbasis"""
return expected_value(observable,
self.eig_energies,
self.eig_states,
beta) | [
"def",
"expected",
"(",
"self",
",",
"observable",
",",
"beta",
"=",
"1e5",
")",
":",
"return",
"expected_value",
"(",
"observable",
",",
"self",
".",
"eig_energies",
",",
"self",
".",
"eig_states",
",",
"beta",
")"
] | Wrapper to the expected_value function to fix the eigenbasis | [
"Wrapper",
"to",
"the",
"expected_value",
"function",
"to",
"fix",
"the",
"eigenbasis"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L188-L193 | train | 56,926 |
Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.quasiparticle_weight | def quasiparticle_weight(self):
"""Calculates quasiparticle weight"""
return np.array([self.expected(op)**2 for op in self.oper['O']]) | python | def quasiparticle_weight(self):
"""Calculates quasiparticle weight"""
return np.array([self.expected(op)**2 for op in self.oper['O']]) | [
"def",
"quasiparticle_weight",
"(",
"self",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"self",
".",
"expected",
"(",
"op",
")",
"**",
"2",
"for",
"op",
"in",
"self",
".",
"oper",
"[",
"'O'",
"]",
"]",
")"
] | Calculates quasiparticle weight | [
"Calculates",
"quasiparticle",
"weight"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L195-L197 | train | 56,927 |
Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.mean_field | def mean_field(self):
"""Calculates mean field"""
mean_field = []
for sp_oper in [self.oper['O'], self.oper['O_d']]:
avgO = np.array([self.expected(op) for op in sp_oper])
avgO[abs(avgO) < 1e-10] = 0.
mean_field.append(avgO*self.param['ekin'])
return ... | python | def mean_field(self):
"""Calculates mean field"""
mean_field = []
for sp_oper in [self.oper['O'], self.oper['O_d']]:
avgO = np.array([self.expected(op) for op in sp_oper])
avgO[abs(avgO) < 1e-10] = 0.
mean_field.append(avgO*self.param['ekin'])
return ... | [
"def",
"mean_field",
"(",
"self",
")",
":",
"mean_field",
"=",
"[",
"]",
"for",
"sp_oper",
"in",
"[",
"self",
".",
"oper",
"[",
"'O'",
"]",
",",
"self",
".",
"oper",
"[",
"'O_d'",
"]",
"]",
":",
"avgO",
"=",
"np",
".",
"array",
"(",
"[",
"self"... | Calculates mean field | [
"Calculates",
"mean",
"field"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L199-L207 | train | 56,928 |
Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.selfconsistency | def selfconsistency(self, u_int, J_coup, mean_field_prev=None):
"""Iterates over the hamiltonian to get the stable selfcosistent one"""
if mean_field_prev is None:
mean_field_prev = np.array([self.param['ekin']]*2)
hlog = [mean_field_prev]
self.oper['Hint'] = self.inter_spin... | python | def selfconsistency(self, u_int, J_coup, mean_field_prev=None):
"""Iterates over the hamiltonian to get the stable selfcosistent one"""
if mean_field_prev is None:
mean_field_prev = np.array([self.param['ekin']]*2)
hlog = [mean_field_prev]
self.oper['Hint'] = self.inter_spin... | [
"def",
"selfconsistency",
"(",
"self",
",",
"u_int",
",",
"J_coup",
",",
"mean_field_prev",
"=",
"None",
")",
":",
"if",
"mean_field_prev",
"is",
"None",
":",
"mean_field_prev",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"param",
"[",
"'ekin'",
"]",... | Iterates over the hamiltonian to get the stable selfcosistent one | [
"Iterates",
"over",
"the",
"hamiltonian",
"to",
"get",
"the",
"stable",
"selfcosistent",
"one"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L209-L235 | train | 56,929 |
Titan-C/slaveparticles | slaveparticles/spins.py | Spinon.restriction | def restriction(self, lam, mean_field):
"""Lagrange multiplier in lattice slave spin"""
self.update_H(mean_field, lam)
restric = np.array([self.expected(op) - n for op, n in zip(self.oper['Sz+1/2'], self.param['populations'])])
return restric | python | def restriction(self, lam, mean_field):
"""Lagrange multiplier in lattice slave spin"""
self.update_H(mean_field, lam)
restric = np.array([self.expected(op) - n for op, n in zip(self.oper['Sz+1/2'], self.param['populations'])])
return restric | [
"def",
"restriction",
"(",
"self",
",",
"lam",
",",
"mean_field",
")",
":",
"self",
".",
"update_H",
"(",
"mean_field",
",",
"lam",
")",
"restric",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"expected",
"(",
"op",
")",
"-",
"n",
"for",
"op",
... | Lagrange multiplier in lattice slave spin | [
"Lagrange",
"multiplier",
"in",
"lattice",
"slave",
"spin"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L237-L241 | train | 56,930 |
evocell/rabifier | rabifier/utils.py | run_cmd | def run_cmd(cmd, out=os.path.devnull, err=os.path.devnull):
"""Runs an external command
:param list cmd: Command to run.
:param str out: Output file
:param str err: Error file
:raises: RuntimeError
"""
logger.debug(' '.join(cmd))
with open(out, 'w') as hout:
proc = subprocess.P... | python | def run_cmd(cmd, out=os.path.devnull, err=os.path.devnull):
"""Runs an external command
:param list cmd: Command to run.
:param str out: Output file
:param str err: Error file
:raises: RuntimeError
"""
logger.debug(' '.join(cmd))
with open(out, 'w') as hout:
proc = subprocess.P... | [
"def",
"run_cmd",
"(",
"cmd",
",",
"out",
"=",
"os",
".",
"path",
".",
"devnull",
",",
"err",
"=",
"os",
".",
"path",
".",
"devnull",
")",
":",
"logger",
".",
"debug",
"(",
"' '",
".",
"join",
"(",
"cmd",
")",
")",
"with",
"open",
"(",
"out",
... | Runs an external command
:param list cmd: Command to run.
:param str out: Output file
:param str err: Error file
:raises: RuntimeError | [
"Runs",
"an",
"external",
"command"
] | a5be3d516517e555bde463b94f06aeed106d19b8 | https://github.com/evocell/rabifier/blob/a5be3d516517e555bde463b94f06aeed106d19b8/rabifier/utils.py#L85-L103 | train | 56,931 |
evocell/rabifier | rabifier/utils.py | run_cmd_if_file_missing | def run_cmd_if_file_missing(cmd, fname, out=os.path.devnull, err=os.path.devnull):
"""Runs an external command if file is absent.
:param list cmd: Command to run.
:param str fname: Path to the file, which existence is being checked.
:param str out: Output file
:param str err: Error file
:return... | python | def run_cmd_if_file_missing(cmd, fname, out=os.path.devnull, err=os.path.devnull):
"""Runs an external command if file is absent.
:param list cmd: Command to run.
:param str fname: Path to the file, which existence is being checked.
:param str out: Output file
:param str err: Error file
:return... | [
"def",
"run_cmd_if_file_missing",
"(",
"cmd",
",",
"fname",
",",
"out",
"=",
"os",
".",
"path",
".",
"devnull",
",",
"err",
"=",
"os",
".",
"path",
".",
"devnull",
")",
":",
"if",
"fname",
"is",
"None",
"or",
"not",
"os",
".",
"path",
".",
"exists"... | Runs an external command if file is absent.
:param list cmd: Command to run.
:param str fname: Path to the file, which existence is being checked.
:param str out: Output file
:param str err: Error file
:return: True if cmd was executed, False otherwise
:rtype: boolean | [
"Runs",
"an",
"external",
"command",
"if",
"file",
"is",
"absent",
"."
] | a5be3d516517e555bde463b94f06aeed106d19b8 | https://github.com/evocell/rabifier/blob/a5be3d516517e555bde463b94f06aeed106d19b8/rabifier/utils.py#L106-L121 | train | 56,932 |
evocell/rabifier | rabifier/utils.py | merge_files | def merge_files(sources, destination):
"""Copy content of multiple files into a single file.
:param list(str) sources: source file names (paths)
:param str destination: destination file name (path)
:return:
"""
with open(destination, 'w') as hout:
for f in sources:
if os.pa... | python | def merge_files(sources, destination):
"""Copy content of multiple files into a single file.
:param list(str) sources: source file names (paths)
:param str destination: destination file name (path)
:return:
"""
with open(destination, 'w') as hout:
for f in sources:
if os.pa... | [
"def",
"merge_files",
"(",
"sources",
",",
"destination",
")",
":",
"with",
"open",
"(",
"destination",
",",
"'w'",
")",
"as",
"hout",
":",
"for",
"f",
"in",
"sources",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"f",
")",
":",
"with",
"open"... | Copy content of multiple files into a single file.
:param list(str) sources: source file names (paths)
:param str destination: destination file name (path)
:return: | [
"Copy",
"content",
"of",
"multiple",
"files",
"into",
"a",
"single",
"file",
"."
] | a5be3d516517e555bde463b94f06aeed106d19b8 | https://github.com/evocell/rabifier/blob/a5be3d516517e555bde463b94f06aeed106d19b8/rabifier/utils.py#L124-L138 | train | 56,933 |
evocell/rabifier | rabifier/utils.py | Pathfinder.add_path | def add_path(self, path):
""" Adds a new path to the list of searchable paths
:param path: new path
"""
if os.path.exists(path):
self.paths.add(path)
return path
else:
#logger.debug('Path {} doesn\'t exist'.format(path))
return No... | python | def add_path(self, path):
""" Adds a new path to the list of searchable paths
:param path: new path
"""
if os.path.exists(path):
self.paths.add(path)
return path
else:
#logger.debug('Path {} doesn\'t exist'.format(path))
return No... | [
"def",
"add_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"self",
".",
"paths",
".",
"add",
"(",
"path",
")",
"return",
"path",
"else",
":",
"#logger.debug('Path {} doesn\\'t exist'.format(path))"... | Adds a new path to the list of searchable paths
:param path: new path | [
"Adds",
"a",
"new",
"path",
"to",
"the",
"list",
"of",
"searchable",
"paths"
] | a5be3d516517e555bde463b94f06aeed106d19b8 | https://github.com/evocell/rabifier/blob/a5be3d516517e555bde463b94f06aeed106d19b8/rabifier/utils.py#L46-L57 | train | 56,934 |
evocell/rabifier | rabifier/utils.py | Pathfinder.get | def get(self, name):
""" Looks for a name in the path.
:param name: file name
:return: path to the file
"""
for d in self.paths:
if os.path.exists(d) and name in os.listdir(d):
return os.path.join(d, name)
logger.debug('File not found {}'.for... | python | def get(self, name):
""" Looks for a name in the path.
:param name: file name
:return: path to the file
"""
for d in self.paths:
if os.path.exists(d) and name in os.listdir(d):
return os.path.join(d, name)
logger.debug('File not found {}'.for... | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"for",
"d",
"in",
"self",
".",
"paths",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"d",
")",
"and",
"name",
"in",
"os",
".",
"listdir",
"(",
"d",
")",
":",
"return",
"os",
".",
"path",
... | Looks for a name in the path.
:param name: file name
:return: path to the file | [
"Looks",
"for",
"a",
"name",
"in",
"the",
"path",
"."
] | a5be3d516517e555bde463b94f06aeed106d19b8 | https://github.com/evocell/rabifier/blob/a5be3d516517e555bde463b94f06aeed106d19b8/rabifier/utils.py#L62-L73 | train | 56,935 |
wuher/devil | devil/resource.py | Resource.__handle_request | def __handle_request(self, request, *args, **kw):
""" Intercept the request and response.
This function lets `HttpStatusCodeError`s fall through. They
are caught and transformed into HTTP responses by the caller.
:return: ``HttpResponse``
"""
self._authenticate(request... | python | def __handle_request(self, request, *args, **kw):
""" Intercept the request and response.
This function lets `HttpStatusCodeError`s fall through. They
are caught and transformed into HTTP responses by the caller.
:return: ``HttpResponse``
"""
self._authenticate(request... | [
"def",
"__handle_request",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"_authenticate",
"(",
"request",
")",
"self",
".",
"_check_permission",
"(",
"request",
")",
"method",
"=",
"self",
".",
"_get_method",
... | Intercept the request and response.
This function lets `HttpStatusCodeError`s fall through. They
are caught and transformed into HTTP responses by the caller.
:return: ``HttpResponse`` | [
"Intercept",
"the",
"request",
"and",
"response",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L111-L126 | train | 56,936 |
wuher/devil | devil/resource.py | Resource._exec_method | def _exec_method(self, method, request, data, *args, **kw):
""" Execute appropriate request handler. """
if self._is_data_method(request):
return method(data, request, *args, **kw)
else:
return method(request, *args, **kw) | python | def _exec_method(self, method, request, data, *args, **kw):
""" Execute appropriate request handler. """
if self._is_data_method(request):
return method(data, request, *args, **kw)
else:
return method(request, *args, **kw) | [
"def",
"_exec_method",
"(",
"self",
",",
"method",
",",
"request",
",",
"data",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"self",
".",
"_is_data_method",
"(",
"request",
")",
":",
"return",
"method",
"(",
"data",
",",
"request",
",",
"... | Execute appropriate request handler. | [
"Execute",
"appropriate",
"request",
"handler",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L128-L133 | train | 56,937 |
wuher/devil | devil/resource.py | Resource._format_response | def _format_response(self, request, response):
""" Format response using appropriate datamapper.
Take the devil response and turn it into django response, ready to
be returned to the client.
"""
res = datamapper.format(request, response, self)
# data is now formatted, l... | python | def _format_response(self, request, response):
""" Format response using appropriate datamapper.
Take the devil response and turn it into django response, ready to
be returned to the client.
"""
res = datamapper.format(request, response, self)
# data is now formatted, l... | [
"def",
"_format_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"res",
"=",
"datamapper",
".",
"format",
"(",
"request",
",",
"response",
",",
"self",
")",
"# data is now formatted, let's check if the status_code is set",
"if",
"res",
".",
"stat... | Format response using appropriate datamapper.
Take the devil response and turn it into django response, ready to
be returned to the client. | [
"Format",
"response",
"using",
"appropriate",
"datamapper",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L173-L186 | train | 56,938 |
wuher/devil | devil/resource.py | Resource._add_resposne_headers | def _add_resposne_headers(self, django_response, devil_response):
""" Add response headers.
Add HTTP headers from devil's response to django's response.
"""
try:
headers = devil_response.headers
except AttributeError:
# ok, there was no devil_response
... | python | def _add_resposne_headers(self, django_response, devil_response):
""" Add response headers.
Add HTTP headers from devil's response to django's response.
"""
try:
headers = devil_response.headers
except AttributeError:
# ok, there was no devil_response
... | [
"def",
"_add_resposne_headers",
"(",
"self",
",",
"django_response",
",",
"devil_response",
")",
":",
"try",
":",
"headers",
"=",
"devil_response",
".",
"headers",
"except",
"AttributeError",
":",
"# ok, there was no devil_response",
"pass",
"else",
":",
"for",
"k",... | Add response headers.
Add HTTP headers from devil's response to django's response. | [
"Add",
"response",
"headers",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L188-L202 | train | 56,939 |
wuher/devil | devil/resource.py | Resource._get_input_data | def _get_input_data(self, request):
""" If there is data, parse it, otherwise return None. """
# only PUT and POST should provide data
if not self._is_data_method(request):
return None
content = [row for row in request.read()]
content = ''.join(content) if content el... | python | def _get_input_data(self, request):
""" If there is data, parse it, otherwise return None. """
# only PUT and POST should provide data
if not self._is_data_method(request):
return None
content = [row for row in request.read()]
content = ''.join(content) if content el... | [
"def",
"_get_input_data",
"(",
"self",
",",
"request",
")",
":",
"# only PUT and POST should provide data",
"if",
"not",
"self",
".",
"_is_data_method",
"(",
"request",
")",
":",
"return",
"None",
"content",
"=",
"[",
"row",
"for",
"row",
"in",
"request",
".",... | If there is data, parse it, otherwise return None. | [
"If",
"there",
"is",
"data",
"parse",
"it",
"otherwise",
"return",
"None",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L204-L212 | train | 56,940 |
wuher/devil | devil/resource.py | Resource._clean_input_data | def _clean_input_data(self, data, request):
""" Clean input data. """
# sanity check
if not self._is_data_method(request):
# this is not PUT or POST -> return
return data
# do cleaning
try:
if self.representation:
# representa... | python | def _clean_input_data(self, data, request):
""" Clean input data. """
# sanity check
if not self._is_data_method(request):
# this is not PUT or POST -> return
return data
# do cleaning
try:
if self.representation:
# representa... | [
"def",
"_clean_input_data",
"(",
"self",
",",
"data",
",",
"request",
")",
":",
"# sanity check",
"if",
"not",
"self",
".",
"_is_data_method",
"(",
"request",
")",
":",
"# this is not PUT or POST -> return",
"return",
"data",
"# do cleaning",
"try",
":",
"if",
"... | Clean input data. | [
"Clean",
"input",
"data",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L218-L238 | train | 56,941 |
wuher/devil | devil/resource.py | Resource._get_input_validator | def _get_input_validator(self, request):
""" Return appropriate input validator.
For POST requests, ``self.post_representation`` is returned
if it is present, ``self.representation`` otherwise.
"""
method = request.method.upper()
if method != 'POST':
return ... | python | def _get_input_validator(self, request):
""" Return appropriate input validator.
For POST requests, ``self.post_representation`` is returned
if it is present, ``self.representation`` otherwise.
"""
method = request.method.upper()
if method != 'POST':
return ... | [
"def",
"_get_input_validator",
"(",
"self",
",",
"request",
")",
":",
"method",
"=",
"request",
".",
"method",
".",
"upper",
"(",
")",
"if",
"method",
"!=",
"'POST'",
":",
"return",
"self",
".",
"representation",
"elif",
"self",
".",
"post_representation",
... | Return appropriate input validator.
For POST requests, ``self.post_representation`` is returned
if it is present, ``self.representation`` otherwise. | [
"Return",
"appropriate",
"input",
"validator",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L240-L253 | train | 56,942 |
wuher/devil | devil/resource.py | Resource._validate_input_data | def _validate_input_data(self, data, request):
""" Validate input data.
:param request: the HTTP request
:param data: the parsed data
:return: if validation is performed and succeeds the data is converted
into whatever format the validation uses (by default Django's
... | python | def _validate_input_data(self, data, request):
""" Validate input data.
:param request: the HTTP request
:param data: the parsed data
:return: if validation is performed and succeeds the data is converted
into whatever format the validation uses (by default Django's
... | [
"def",
"_validate_input_data",
"(",
"self",
",",
"data",
",",
"request",
")",
":",
"validator",
"=",
"self",
".",
"_get_input_validator",
"(",
"request",
")",
"if",
"isinstance",
"(",
"data",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"map"... | Validate input data.
:param request: the HTTP request
:param data: the parsed data
:return: if validation is performed and succeeds the data is converted
into whatever format the validation uses (by default Django's
Forms) If not, the data is returned unchanged... | [
"Validate",
"input",
"data",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L255-L270 | train | 56,943 |
wuher/devil | devil/resource.py | Resource._validate_output_data | def _validate_output_data(
self, original_res, serialized_res, formatted_res, request):
""" Validate the response data.
:param response: ``HttpResponse``
:param data: payload data. This implementation assumes
dict or list of dicts.
:raises: `HttpStatusCodeEr... | python | def _validate_output_data(
self, original_res, serialized_res, formatted_res, request):
""" Validate the response data.
:param response: ``HttpResponse``
:param data: payload data. This implementation assumes
dict or list of dicts.
:raises: `HttpStatusCodeEr... | [
"def",
"_validate_output_data",
"(",
"self",
",",
"original_res",
",",
"serialized_res",
",",
"formatted_res",
",",
"request",
")",
":",
"validator",
"=",
"self",
".",
"representation",
"# when not to validate...",
"if",
"not",
"validator",
":",
"return",
"try",
"... | Validate the response data.
:param response: ``HttpResponse``
:param data: payload data. This implementation assumes
dict or list of dicts.
:raises: `HttpStatusCodeError` if data is not valid | [
"Validate",
"the",
"response",
"data",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L272-L294 | train | 56,944 |
wuher/devil | devil/resource.py | Resource._create_object | def _create_object(self, data, request):
""" Create a python object from the given data.
This will use ``self.factory`` object's ``create()`` function to
create the data.
If no factory is defined, this will simply return the same data
that was given.
"""
if req... | python | def _create_object(self, data, request):
""" Create a python object from the given data.
This will use ``self.factory`` object's ``create()`` function to
create the data.
If no factory is defined, this will simply return the same data
that was given.
"""
if req... | [
"def",
"_create_object",
"(",
"self",
",",
"data",
",",
"request",
")",
":",
"if",
"request",
".",
"method",
".",
"upper",
"(",
")",
"==",
"'POST'",
"and",
"self",
".",
"post_factory",
":",
"fac_func",
"=",
"self",
".",
"post_factory",
".",
"create",
"... | Create a python object from the given data.
This will use ``self.factory`` object's ``create()`` function to
create the data.
If no factory is defined, this will simply return the same data
that was given. | [
"Create",
"a",
"python",
"object",
"from",
"the",
"given",
"data",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L316-L334 | train | 56,945 |
wuher/devil | devil/resource.py | Resource._serialize_object | def _serialize_object(self, response_data, request):
""" Create a python datatype from the given python object.
This will use ``self.factory`` object's ``serialize()`` function
to convert the object into dictionary.
If no factory is defined, this will simply return the same data
... | python | def _serialize_object(self, response_data, request):
""" Create a python datatype from the given python object.
This will use ``self.factory`` object's ``serialize()`` function
to convert the object into dictionary.
If no factory is defined, this will simply return the same data
... | [
"def",
"_serialize_object",
"(",
"self",
",",
"response_data",
",",
"request",
")",
":",
"if",
"not",
"self",
".",
"factory",
":",
"return",
"response_data",
"if",
"isinstance",
"(",
"response_data",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",... | Create a python datatype from the given python object.
This will use ``self.factory`` object's ``serialize()`` function
to convert the object into dictionary.
If no factory is defined, this will simply return the same data
that was given.
:param response_data: data returned by... | [
"Create",
"a",
"python",
"datatype",
"from",
"the",
"given",
"python",
"object",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L336-L355 | train | 56,946 |
wuher/devil | devil/resource.py | Resource._get_unknown_error_response | def _get_unknown_error_response(self, request, exc):
""" Generate HttpResponse for unknown exceptions.
todo: this should be more informative..
"""
logging.getLogger('devil').error(
'while doing %s on %s with [%s], devil caught: %s' % (
request.method, reques... | python | def _get_unknown_error_response(self, request, exc):
""" Generate HttpResponse for unknown exceptions.
todo: this should be more informative..
"""
logging.getLogger('devil').error(
'while doing %s on %s with [%s], devil caught: %s' % (
request.method, reques... | [
"def",
"_get_unknown_error_response",
"(",
"self",
",",
"request",
",",
"exc",
")",
":",
"logging",
".",
"getLogger",
"(",
"'devil'",
")",
".",
"error",
"(",
"'while doing %s on %s with [%s], devil caught: %s'",
"%",
"(",
"request",
".",
"method",
",",
"request",
... | Generate HttpResponse for unknown exceptions.
todo: this should be more informative.. | [
"Generate",
"HttpResponse",
"for",
"unknown",
"exceptions",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L357-L370 | train | 56,947 |
wuher/devil | devil/resource.py | Resource._get_error_response | def _get_error_response(self, exc):
""" Generate HttpResponse based on the HttpStatusCodeError. """
if exc.has_code(codes.UNAUTHORIZED):
return self._get_auth_challenge(exc)
else:
if exc.has_code(codes.INTERNAL_SERVER_ERROR):
logging.getLogger('devil').err... | python | def _get_error_response(self, exc):
""" Generate HttpResponse based on the HttpStatusCodeError. """
if exc.has_code(codes.UNAUTHORIZED):
return self._get_auth_challenge(exc)
else:
if exc.has_code(codes.INTERNAL_SERVER_ERROR):
logging.getLogger('devil').err... | [
"def",
"_get_error_response",
"(",
"self",
",",
"exc",
")",
":",
"if",
"exc",
".",
"has_code",
"(",
"codes",
".",
"UNAUTHORIZED",
")",
":",
"return",
"self",
".",
"_get_auth_challenge",
"(",
"exc",
")",
"else",
":",
"if",
"exc",
".",
"has_code",
"(",
"... | Generate HttpResponse based on the HttpStatusCodeError. | [
"Generate",
"HttpResponse",
"based",
"on",
"the",
"HttpStatusCodeError",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L372-L382 | train | 56,948 |
wuher/devil | devil/resource.py | Resource._get_auth_challenge | def _get_auth_challenge(self, exc):
""" Returns HttpResponse for the client. """
response = HttpResponse(content=exc.content, status=exc.get_code_num())
response['WWW-Authenticate'] = 'Basic realm="%s"' % REALM
return response | python | def _get_auth_challenge(self, exc):
""" Returns HttpResponse for the client. """
response = HttpResponse(content=exc.content, status=exc.get_code_num())
response['WWW-Authenticate'] = 'Basic realm="%s"' % REALM
return response | [
"def",
"_get_auth_challenge",
"(",
"self",
",",
"exc",
")",
":",
"response",
"=",
"HttpResponse",
"(",
"content",
"=",
"exc",
".",
"content",
",",
"status",
"=",
"exc",
".",
"get_code_num",
"(",
")",
")",
"response",
"[",
"'WWW-Authenticate'",
"]",
"=",
... | Returns HttpResponse for the client. | [
"Returns",
"HttpResponse",
"for",
"the",
"client",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L384-L388 | train | 56,949 |
wuher/devil | devil/resource.py | Resource._get_method | def _get_method(self, request):
""" Figure out the requested method and return the callable. """
methodname = request.method.lower()
method = getattr(self, methodname, None)
if not method or not callable(method):
raise errors.MethodNotAllowed()
return method | python | def _get_method(self, request):
""" Figure out the requested method and return the callable. """
methodname = request.method.lower()
method = getattr(self, methodname, None)
if not method or not callable(method):
raise errors.MethodNotAllowed()
return method | [
"def",
"_get_method",
"(",
"self",
",",
"request",
")",
":",
"methodname",
"=",
"request",
".",
"method",
".",
"lower",
"(",
")",
"method",
"=",
"getattr",
"(",
"self",
",",
"methodname",
",",
"None",
")",
"if",
"not",
"method",
"or",
"not",
"callable"... | Figure out the requested method and return the callable. | [
"Figure",
"out",
"the",
"requested",
"method",
"and",
"return",
"the",
"callable",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L390-L396 | train | 56,950 |
wuher/devil | devil/resource.py | Resource._authenticate | def _authenticate(self, request):
""" Perform authentication. """
def ensure_user_obj():
""" Make sure that request object has user property.
If `request.user` is not present or is `None`, it is
created and initialized with `AnonymousUser`.
"""
... | python | def _authenticate(self, request):
""" Perform authentication. """
def ensure_user_obj():
""" Make sure that request object has user property.
If `request.user` is not present or is `None`, it is
created and initialized with `AnonymousUser`.
"""
... | [
"def",
"_authenticate",
"(",
"self",
",",
"request",
")",
":",
"def",
"ensure_user_obj",
"(",
")",
":",
"\"\"\" Make sure that request object has user property.\n\n If `request.user` is not present or is `None`, it is\n created and initialized with `AnonymousUser`.\n ... | Perform authentication. | [
"Perform",
"authentication",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/resource.py#L402-L449 | train | 56,951 |
kellerza/pyqwikswitch | example.py | print_item_callback | def print_item_callback(item):
"""Print an item callback, used by &listen."""
print('&listen [{}, {}={}]'.format(
item.get('cmd', ''),
item.get('id', ''),
item.get('data', ''))) | python | def print_item_callback(item):
"""Print an item callback, used by &listen."""
print('&listen [{}, {}={}]'.format(
item.get('cmd', ''),
item.get('id', ''),
item.get('data', ''))) | [
"def",
"print_item_callback",
"(",
"item",
")",
":",
"print",
"(",
"'&listen [{}, {}={}]'",
".",
"format",
"(",
"item",
".",
"get",
"(",
"'cmd'",
",",
"''",
")",
",",
"item",
".",
"get",
"(",
"'id'",
",",
"''",
")",
",",
"item",
".",
"get",
"(",
"'... | Print an item callback, used by &listen. | [
"Print",
"an",
"item",
"callback",
"used",
"by",
"&listen",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/example.py#L31-L36 | train | 56,952 |
kellerza/pyqwikswitch | example.py | main | def main():
"""Quick test for QSUsb class."""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--url', help='QSUSB URL [http://127.0.0.1:2020]',
default='http://127.0.0.1:2020')
parser.add_argument('--file', help='a test file from /&devices')
parser... | python | def main():
"""Quick test for QSUsb class."""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--url', help='QSUSB URL [http://127.0.0.1:2020]',
default='http://127.0.0.1:2020')
parser.add_argument('--file', help='a test file from /&devices')
parser... | [
"def",
"main",
"(",
")",
":",
"import",
"argparse",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--url'",
",",
"help",
"=",
"'QSUSB URL [http://127.0.0.1:2020]'",
",",
"default",
"=",
"'http://127.0.0.1:2020'",
... | Quick test for QSUsb class. | [
"Quick",
"test",
"for",
"QSUsb",
"class",
"."
] | 9d4f080048221eaee93e3eefcf641919ff1af586 | https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/example.py#L54-L96 | train | 56,953 |
stevepeak/dictime | dictime/moment.py | moment.get | def get(self):
"""Called to get the asset values and if it is valid
"""
with self._lock:
now = datetime.now()
active = []
for i, vef in enumerate(self.futures):
# has expired
if (vef[1] or datetime.max) <= now:
... | python | def get(self):
"""Called to get the asset values and if it is valid
"""
with self._lock:
now = datetime.now()
active = []
for i, vef in enumerate(self.futures):
# has expired
if (vef[1] or datetime.max) <= now:
... | [
"def",
"get",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"active",
"=",
"[",
"]",
"for",
"i",
",",
"vef",
"in",
"enumerate",
"(",
"self",
".",
"futures",
")",
":",
"# has expired",
"if"... | Called to get the asset values and if it is valid | [
"Called",
"to",
"get",
"the",
"asset",
"values",
"and",
"if",
"it",
"is",
"valid"
] | 6d8724bed5a7844e47a9c16a233f8db494c98c61 | https://github.com/stevepeak/dictime/blob/6d8724bed5a7844e47a9c16a233f8db494c98c61/dictime/moment.py#L14-L39 | train | 56,954 |
ThomasChiroux/attowiki | src/attowiki/rst_directives.py | add_node | def add_node(node, **kwds):
"""add_node from Sphinx
"""
nodes._add_node_class_names([node.__name__])
for key, val in kwds.iteritems():
try:
visit, depart = val
except ValueError:
raise ValueError('Value for key %r must be a '
'(vis... | python | def add_node(node, **kwds):
"""add_node from Sphinx
"""
nodes._add_node_class_names([node.__name__])
for key, val in kwds.iteritems():
try:
visit, depart = val
except ValueError:
raise ValueError('Value for key %r must be a '
'(vis... | [
"def",
"add_node",
"(",
"node",
",",
"*",
"*",
"kwds",
")",
":",
"nodes",
".",
"_add_node_class_names",
"(",
"[",
"node",
".",
"__name__",
"]",
")",
"for",
"key",
",",
"val",
"in",
"kwds",
".",
"iteritems",
"(",
")",
":",
"try",
":",
"visit",
",",
... | add_node from Sphinx | [
"add_node",
"from",
"Sphinx"
] | 6c93c420305490d324fdc95a7b40b2283a222183 | https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/rst_directives.py#L30-L49 | train | 56,955 |
concordusapps/python-shield | shield/_registry.py | Registry.retrieve | def retrieve(self, *args, **kwargs):
"""Retrieve the permsission function for the provided things.
"""
lookup, key = self._lookup(*args, **kwargs)
return lookup[key] | python | def retrieve(self, *args, **kwargs):
"""Retrieve the permsission function for the provided things.
"""
lookup, key = self._lookup(*args, **kwargs)
return lookup[key] | [
"def",
"retrieve",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lookup",
",",
"key",
"=",
"self",
".",
"_lookup",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"lookup",
"[",
"key",
"]"
] | Retrieve the permsission function for the provided things. | [
"Retrieve",
"the",
"permsission",
"function",
"for",
"the",
"provided",
"things",
"."
] | 3c08d483eaec1ebaa814e31c7de5daf82234b8f7 | https://github.com/concordusapps/python-shield/blob/3c08d483eaec1ebaa814e31c7de5daf82234b8f7/shield/_registry.py#L129-L135 | train | 56,956 |
evocell/rabifier | rabifier/rabmyfire.py | Gprotein.has_rabf_motif | def has_rabf_motif(self):
"""Checks if the sequence has enough RabF motifs within the G domain
If there exists more than one G domain in the sequence enough RabF motifs is required in at least one
of those domains to classify the sequence as a Rab.
"""
if self.rabf_motifs:
... | python | def has_rabf_motif(self):
"""Checks if the sequence has enough RabF motifs within the G domain
If there exists more than one G domain in the sequence enough RabF motifs is required in at least one
of those domains to classify the sequence as a Rab.
"""
if self.rabf_motifs:
... | [
"def",
"has_rabf_motif",
"(",
"self",
")",
":",
"if",
"self",
".",
"rabf_motifs",
":",
"for",
"gdomain",
"in",
"self",
".",
"gdomain_regions",
":",
"beg",
",",
"end",
"=",
"map",
"(",
"int",
",",
"gdomain",
".",
"split",
"(",
"'-'",
")",
")",
"motifs... | Checks if the sequence has enough RabF motifs within the G domain
If there exists more than one G domain in the sequence enough RabF motifs is required in at least one
of those domains to classify the sequence as a Rab. | [
"Checks",
"if",
"the",
"sequence",
"has",
"enough",
"RabF",
"motifs",
"within",
"the",
"G",
"domain"
] | a5be3d516517e555bde463b94f06aeed106d19b8 | https://github.com/evocell/rabifier/blob/a5be3d516517e555bde463b94f06aeed106d19b8/rabifier/rabmyfire.py#L73-L88 | train | 56,957 |
evocell/rabifier | rabifier/rabmyfire.py | Gprotein.summarize | def summarize(self):
""" G protein annotation summary in a text format
:return: A string summary of the annotation
:rtype: str
"""
data = [
['Sequence ID', self.seqrecord.id],
['G domain', ' '.join(self.gdomain_regions) if self.gdomain_regions else None],... | python | def summarize(self):
""" G protein annotation summary in a text format
:return: A string summary of the annotation
:rtype: str
"""
data = [
['Sequence ID', self.seqrecord.id],
['G domain', ' '.join(self.gdomain_regions) if self.gdomain_regions else None],... | [
"def",
"summarize",
"(",
"self",
")",
":",
"data",
"=",
"[",
"[",
"'Sequence ID'",
",",
"self",
".",
"seqrecord",
".",
"id",
"]",
",",
"[",
"'G domain'",
",",
"' '",
".",
"join",
"(",
"self",
".",
"gdomain_regions",
")",
"if",
"self",
".",
"gdomain_r... | G protein annotation summary in a text format
:return: A string summary of the annotation
:rtype: str | [
"G",
"protein",
"annotation",
"summary",
"in",
"a",
"text",
"format"
] | a5be3d516517e555bde463b94f06aeed106d19b8 | https://github.com/evocell/rabifier/blob/a5be3d516517e555bde463b94f06aeed106d19b8/rabifier/rabmyfire.py#L120-L141 | train | 56,958 |
evocell/rabifier | rabifier/rabmyfire.py | Phase1.write | def write(self):
"""Write sequences predicted to be Rabs as a fasta file.
:return: Number of written sequences
:rtype: int
"""
rabs = [x.seqrecord for x in self.gproteins.values() if x.is_rab()]
return SeqIO.write(rabs, self.tmpfname + '.phase2', 'fasta') | python | def write(self):
"""Write sequences predicted to be Rabs as a fasta file.
:return: Number of written sequences
:rtype: int
"""
rabs = [x.seqrecord for x in self.gproteins.values() if x.is_rab()]
return SeqIO.write(rabs, self.tmpfname + '.phase2', 'fasta') | [
"def",
"write",
"(",
"self",
")",
":",
"rabs",
"=",
"[",
"x",
".",
"seqrecord",
"for",
"x",
"in",
"self",
".",
"gproteins",
".",
"values",
"(",
")",
"if",
"x",
".",
"is_rab",
"(",
")",
"]",
"return",
"SeqIO",
".",
"write",
"(",
"rabs",
",",
"se... | Write sequences predicted to be Rabs as a fasta file.
:return: Number of written sequences
:rtype: int | [
"Write",
"sequences",
"predicted",
"to",
"be",
"Rabs",
"as",
"a",
"fasta",
"file",
"."
] | a5be3d516517e555bde463b94f06aeed106d19b8 | https://github.com/evocell/rabifier/blob/a5be3d516517e555bde463b94f06aeed106d19b8/rabifier/rabmyfire.py#L300-L308 | train | 56,959 |
evocell/rabifier | rabifier/rabmyfire.py | Rabmyfire.check | def check(self):
""" Check if data and third party tools, necessary to run the classification, are available
:raises: RuntimeError
"""
pathfinder = Pathfinder(True)
if pathfinder.add_path(pathfinder['superfamily']) is None:
raise RuntimeError("'superfamily' data dir... | python | def check(self):
""" Check if data and third party tools, necessary to run the classification, are available
:raises: RuntimeError
"""
pathfinder = Pathfinder(True)
if pathfinder.add_path(pathfinder['superfamily']) is None:
raise RuntimeError("'superfamily' data dir... | [
"def",
"check",
"(",
"self",
")",
":",
"pathfinder",
"=",
"Pathfinder",
"(",
"True",
")",
"if",
"pathfinder",
".",
"add_path",
"(",
"pathfinder",
"[",
"'superfamily'",
"]",
")",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"'superfamily' data directory i... | Check if data and third party tools, necessary to run the classification, are available
:raises: RuntimeError | [
"Check",
"if",
"data",
"and",
"third",
"party",
"tools",
"necessary",
"to",
"run",
"the",
"classification",
"are",
"available"
] | a5be3d516517e555bde463b94f06aeed106d19b8 | https://github.com/evocell/rabifier/blob/a5be3d516517e555bde463b94f06aeed106d19b8/rabifier/rabmyfire.py#L474-L486 | train | 56,960 |
concordusapps/python-shield | shield/utils.py | filter_ | def filter_(*permissions, **kwargs):
"""
Constructs a clause to filter all bearers or targets for a given
berarer or target.
"""
bearer = kwargs['bearer']
target = kwargs.get('target')
bearer_cls = type_for(bearer)
# We need a query object. There are many ways to get one, Either we ca... | python | def filter_(*permissions, **kwargs):
"""
Constructs a clause to filter all bearers or targets for a given
berarer or target.
"""
bearer = kwargs['bearer']
target = kwargs.get('target')
bearer_cls = type_for(bearer)
# We need a query object. There are many ways to get one, Either we ca... | [
"def",
"filter_",
"(",
"*",
"permissions",
",",
"*",
"*",
"kwargs",
")",
":",
"bearer",
"=",
"kwargs",
"[",
"'bearer'",
"]",
"target",
"=",
"kwargs",
".",
"get",
"(",
"'target'",
")",
"bearer_cls",
"=",
"type_for",
"(",
"bearer",
")",
"# We need a query ... | Constructs a clause to filter all bearers or targets for a given
berarer or target. | [
"Constructs",
"a",
"clause",
"to",
"filter",
"all",
"bearers",
"or",
"targets",
"for",
"a",
"given",
"berarer",
"or",
"target",
"."
] | 3c08d483eaec1ebaa814e31c7de5daf82234b8f7 | https://github.com/concordusapps/python-shield/blob/3c08d483eaec1ebaa814e31c7de5daf82234b8f7/shield/utils.py#L15-L61 | train | 56,961 |
Julian/Minion | minion/wsgi.py | create_app | def create_app(application, request_class=Request):
"""
Create a WSGI application out of the given Minion app.
Arguments:
application (Application):
a minion app
request_class (callable):
a class to use for constructing incoming requests out of the WSGI
... | python | def create_app(application, request_class=Request):
"""
Create a WSGI application out of the given Minion app.
Arguments:
application (Application):
a minion app
request_class (callable):
a class to use for constructing incoming requests out of the WSGI
... | [
"def",
"create_app",
"(",
"application",
",",
"request_class",
"=",
"Request",
")",
":",
"def",
"wsgi",
"(",
"environ",
",",
"start_response",
")",
":",
"response",
"=",
"application",
".",
"serve",
"(",
"request",
"=",
"request_class",
"(",
"environ",
")",
... | Create a WSGI application out of the given Minion app.
Arguments:
application (Application):
a minion app
request_class (callable):
a class to use for constructing incoming requests out of the WSGI
environment. It will be passed a single arg, the environ.
... | [
"Create",
"a",
"WSGI",
"application",
"out",
"of",
"the",
"given",
"Minion",
"app",
"."
] | 518d06f9ffd38dcacc0de4d94e72d1f8452157a8 | https://github.com/Julian/Minion/blob/518d06f9ffd38dcacc0de4d94e72d1f8452157a8/minion/wsgi.py#L59-L90 | train | 56,962 |
wuher/devil | devil/docs/resource.py | DocumentedResource.get_documentation | def get_documentation(self, request, *args, **kw):
""" Generate the documentation. """
ret = dict()
ret['resource'] = self.name()
ret['urls'] = self._get_url_doc()
ret['description'] = self.__doc__
ret['representation'] = self._get_representation_doc()
ret['method... | python | def get_documentation(self, request, *args, **kw):
""" Generate the documentation. """
ret = dict()
ret['resource'] = self.name()
ret['urls'] = self._get_url_doc()
ret['description'] = self.__doc__
ret['representation'] = self._get_representation_doc()
ret['method... | [
"def",
"get_documentation",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"ret",
"[",
"'resource'",
"]",
"=",
"self",
".",
"name",
"(",
")",
"ret",
"[",
"'urls'",
"]",
"=",
"self",
"... | Generate the documentation. | [
"Generate",
"the",
"documentation",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/docs/resource.py#L35-L43 | train | 56,963 |
wuher/devil | devil/docs/resource.py | DocumentedResource._serialize_object | def _serialize_object(self, response_data, request):
""" Override to not serialize doc responses. """
if self._is_doc_request(request):
return response_data
else:
return super(DocumentedResource, self)._serialize_object(
response_data, request) | python | def _serialize_object(self, response_data, request):
""" Override to not serialize doc responses. """
if self._is_doc_request(request):
return response_data
else:
return super(DocumentedResource, self)._serialize_object(
response_data, request) | [
"def",
"_serialize_object",
"(",
"self",
",",
"response_data",
",",
"request",
")",
":",
"if",
"self",
".",
"_is_doc_request",
"(",
"request",
")",
":",
"return",
"response_data",
"else",
":",
"return",
"super",
"(",
"DocumentedResource",
",",
"self",
")",
"... | Override to not serialize doc responses. | [
"Override",
"to",
"not",
"serialize",
"doc",
"responses",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/docs/resource.py#L45-L51 | train | 56,964 |
wuher/devil | devil/docs/resource.py | DocumentedResource._validate_output_data | def _validate_output_data(
self, original_res, serialized_res, formatted_res, request):
""" Override to not validate doc output. """
if self._is_doc_request(request):
return
else:
return super(DocumentedResource, self)._validate_output_data(
origin... | python | def _validate_output_data(
self, original_res, serialized_res, formatted_res, request):
""" Override to not validate doc output. """
if self._is_doc_request(request):
return
else:
return super(DocumentedResource, self)._validate_output_data(
origin... | [
"def",
"_validate_output_data",
"(",
"self",
",",
"original_res",
",",
"serialized_res",
",",
"formatted_res",
",",
"request",
")",
":",
"if",
"self",
".",
"_is_doc_request",
"(",
"request",
")",
":",
"return",
"else",
":",
"return",
"super",
"(",
"DocumentedR... | Override to not validate doc output. | [
"Override",
"to",
"not",
"validate",
"doc",
"output",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/docs/resource.py#L53-L60 | train | 56,965 |
wuher/devil | devil/docs/resource.py | DocumentedResource._get_method | def _get_method(self, request):
""" Override to check if this is a documentation request. """
if self._is_doc_request(request):
return self.get_documentation
else:
return super(DocumentedResource, self)._get_method(request) | python | def _get_method(self, request):
""" Override to check if this is a documentation request. """
if self._is_doc_request(request):
return self.get_documentation
else:
return super(DocumentedResource, self)._get_method(request) | [
"def",
"_get_method",
"(",
"self",
",",
"request",
")",
":",
"if",
"self",
".",
"_is_doc_request",
"(",
"request",
")",
":",
"return",
"self",
".",
"get_documentation",
"else",
":",
"return",
"super",
"(",
"DocumentedResource",
",",
"self",
")",
".",
"_get... | Override to check if this is a documentation request. | [
"Override",
"to",
"check",
"if",
"this",
"is",
"a",
"documentation",
"request",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/docs/resource.py#L62-L67 | train | 56,966 |
wuher/devil | devil/docs/resource.py | DocumentedResource._get_representation_doc | def _get_representation_doc(self):
""" Return documentation for the representation of the resource. """
if not self.representation:
return 'N/A'
fields = {}
for name, field in self.representation.fields.items():
fields[name] = self._get_field_doc(field)
re... | python | def _get_representation_doc(self):
""" Return documentation for the representation of the resource. """
if not self.representation:
return 'N/A'
fields = {}
for name, field in self.representation.fields.items():
fields[name] = self._get_field_doc(field)
re... | [
"def",
"_get_representation_doc",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"representation",
":",
"return",
"'N/A'",
"fields",
"=",
"{",
"}",
"for",
"name",
",",
"field",
"in",
"self",
".",
"representation",
".",
"fields",
".",
"items",
"(",
")",... | Return documentation for the representation of the resource. | [
"Return",
"documentation",
"for",
"the",
"representation",
"of",
"the",
"resource",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/docs/resource.py#L73-L80 | train | 56,967 |
wuher/devil | devil/docs/resource.py | DocumentedResource._get_field_doc | def _get_field_doc(self, field):
""" Return documentation for a field in the representation. """
fieldspec = dict()
fieldspec['type'] = field.__class__.__name__
fieldspec['required'] = field.required
fieldspec['validators'] = [{validator.__class__.__name__: validator.__dict__} fo... | python | def _get_field_doc(self, field):
""" Return documentation for a field in the representation. """
fieldspec = dict()
fieldspec['type'] = field.__class__.__name__
fieldspec['required'] = field.required
fieldspec['validators'] = [{validator.__class__.__name__: validator.__dict__} fo... | [
"def",
"_get_field_doc",
"(",
"self",
",",
"field",
")",
":",
"fieldspec",
"=",
"dict",
"(",
")",
"fieldspec",
"[",
"'type'",
"]",
"=",
"field",
".",
"__class__",
".",
"__name__",
"fieldspec",
"[",
"'required'",
"]",
"=",
"field",
".",
"required",
"field... | Return documentation for a field in the representation. | [
"Return",
"documentation",
"for",
"a",
"field",
"in",
"the",
"representation",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/docs/resource.py#L82-L88 | train | 56,968 |
wuher/devil | devil/docs/resource.py | DocumentedResource._get_url_doc | def _get_url_doc(self):
""" Return a list of URLs that map to this resource. """
resolver = get_resolver(None)
possibilities = resolver.reverse_dict.getlist(self)
urls = [possibility[0] for possibility in possibilities]
return urls | python | def _get_url_doc(self):
""" Return a list of URLs that map to this resource. """
resolver = get_resolver(None)
possibilities = resolver.reverse_dict.getlist(self)
urls = [possibility[0] for possibility in possibilities]
return urls | [
"def",
"_get_url_doc",
"(",
"self",
")",
":",
"resolver",
"=",
"get_resolver",
"(",
"None",
")",
"possibilities",
"=",
"resolver",
".",
"reverse_dict",
".",
"getlist",
"(",
"self",
")",
"urls",
"=",
"[",
"possibility",
"[",
"0",
"]",
"for",
"possibility",
... | Return a list of URLs that map to this resource. | [
"Return",
"a",
"list",
"of",
"URLs",
"that",
"map",
"to",
"this",
"resource",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/docs/resource.py#L90-L95 | train | 56,969 |
wuher/devil | devil/docs/resource.py | DocumentedResource._get_method_doc | def _get_method_doc(self):
""" Return method documentations. """
ret = {}
for method_name in self.methods:
method = getattr(self, method_name, None)
if method:
ret[method_name] = method.__doc__
return ret | python | def _get_method_doc(self):
""" Return method documentations. """
ret = {}
for method_name in self.methods:
method = getattr(self, method_name, None)
if method:
ret[method_name] = method.__doc__
return ret | [
"def",
"_get_method_doc",
"(",
"self",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"method_name",
"in",
"self",
".",
"methods",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"method_name",
",",
"None",
")",
"if",
"method",
":",
"ret",
"[",
"method_name",... | Return method documentations. | [
"Return",
"method",
"documentations",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/docs/resource.py#L97-L104 | train | 56,970 |
ten10solutions/Geist | geist/backends/_x11_common.py | GeistXBase.create_process | def create_process(self, command, shell=True, stdout=None, stderr=None,
env=None):
"""
Execute a process using subprocess.Popen, setting the backend's DISPLAY
"""
env = env if env is not None else dict(os.environ)
env['DISPLAY'] = self.display
retur... | python | def create_process(self, command, shell=True, stdout=None, stderr=None,
env=None):
"""
Execute a process using subprocess.Popen, setting the backend's DISPLAY
"""
env = env if env is not None else dict(os.environ)
env['DISPLAY'] = self.display
retur... | [
"def",
"create_process",
"(",
"self",
",",
"command",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"env",
"=",
"env",
"if",
"env",
"is",
"not",
"None",
"else",
"dict",
"(",
... | Execute a process using subprocess.Popen, setting the backend's DISPLAY | [
"Execute",
"a",
"process",
"using",
"subprocess",
".",
"Popen",
"setting",
"the",
"backend",
"s",
"DISPLAY"
] | a1ef16d8b4c3777735008b671a50acfde3ce7bf1 | https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/backends/_x11_common.py#L54-L63 | train | 56,971 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/providers/azure_provider.py | AzureVM.pause | def pause(self, instance_id, keep_provisioned=True):
"""shuts down the instance without destroying it.
The AbstractCloudProvider class uses 'stop' to refer to destroying
a VM, so use 'pause' to mean powering it down while leaving it
allocated.
:param str instance_id: instance i... | python | def pause(self, instance_id, keep_provisioned=True):
"""shuts down the instance without destroying it.
The AbstractCloudProvider class uses 'stop' to refer to destroying
a VM, so use 'pause' to mean powering it down while leaving it
allocated.
:param str instance_id: instance i... | [
"def",
"pause",
"(",
"self",
",",
"instance_id",
",",
"keep_provisioned",
"=",
"True",
")",
":",
"try",
":",
"if",
"self",
".",
"_paused",
":",
"log",
".",
"debug",
"(",
"\"node %s is already paused\"",
",",
"instance_id",
")",
"return",
"self",
".",
"_pau... | shuts down the instance without destroying it.
The AbstractCloudProvider class uses 'stop' to refer to destroying
a VM, so use 'pause' to mean powering it down while leaving it
allocated.
:param str instance_id: instance identifier
:return: None | [
"shuts",
"down",
"the",
"instance",
"without",
"destroying",
"it",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/providers/azure_provider.py#L1198-L1225 | train | 56,972 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/providers/azure_provider.py | AzureVM.restart | def restart(self, instance_id):
"""restarts a paused instance.
:param str instance_id: instance identifier
:return: None
"""
try:
if not self._paused:
log.debug("node %s is not paused, can't restart", instance_id)
return
s... | python | def restart(self, instance_id):
"""restarts a paused instance.
:param str instance_id: instance identifier
:return: None
"""
try:
if not self._paused:
log.debug("node %s is not paused, can't restart", instance_id)
return
s... | [
"def",
"restart",
"(",
"self",
",",
"instance_id",
")",
":",
"try",
":",
"if",
"not",
"self",
".",
"_paused",
":",
"log",
".",
"debug",
"(",
"\"node %s is not paused, can't restart\"",
",",
"instance_id",
")",
"return",
"self",
".",
"_paused",
"=",
"False",
... | restarts a paused instance.
:param str instance_id: instance identifier
:return: None | [
"restarts",
"a",
"paused",
"instance",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/providers/azure_provider.py#L1227-L1247 | train | 56,973 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/providers/azure_provider.py | AzureCloudProvider._save_or_update | def _save_or_update(self):
"""Save or update the private state needed by the cloud provider.
"""
with self._resource_lock:
if not self._config or not self._config._storage_path:
raise Exception("self._config._storage path is undefined")
if not self._config... | python | def _save_or_update(self):
"""Save or update the private state needed by the cloud provider.
"""
with self._resource_lock:
if not self._config or not self._config._storage_path:
raise Exception("self._config._storage path is undefined")
if not self._config... | [
"def",
"_save_or_update",
"(",
"self",
")",
":",
"with",
"self",
".",
"_resource_lock",
":",
"if",
"not",
"self",
".",
"_config",
"or",
"not",
"self",
".",
"_config",
".",
"_storage_path",
":",
"raise",
"Exception",
"(",
"\"self._config._storage path is undefine... | Save or update the private state needed by the cloud provider. | [
"Save",
"or",
"update",
"the",
"private",
"state",
"needed",
"by",
"the",
"cloud",
"provider",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/providers/azure_provider.py#L1711-L1725 | train | 56,974 |
flashashen/flange | flange/iterutils.py | get_path | def get_path(root, path, default=_UNSET):
"""Retrieve a value from a nested object via a tuple representing the
lookup path.
>>> root = {'a': {'b': {'c': [[1], [2], [3]]}}}
>>> get_path(root, ('a', 'b', 'c', 2, 0))
3
The path format is intentionally consistent with that of
:func:`remap`.
... | python | def get_path(root, path, default=_UNSET):
"""Retrieve a value from a nested object via a tuple representing the
lookup path.
>>> root = {'a': {'b': {'c': [[1], [2], [3]]}}}
>>> get_path(root, ('a', 'b', 'c', 2, 0))
3
The path format is intentionally consistent with that of
:func:`remap`.
... | [
"def",
"get_path",
"(",
"root",
",",
"path",
",",
"default",
"=",
"_UNSET",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"basestring",
")",
":",
"path",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"cur",
"=",
"root",
"try",
":",
"for",
"seg",
... | Retrieve a value from a nested object via a tuple representing the
lookup path.
>>> root = {'a': {'b': {'c': [[1], [2], [3]]}}}
>>> get_path(root, ('a', 'b', 'c', 2, 0))
3
The path format is intentionally consistent with that of
:func:`remap`.
One of get_path's chief aims is improved erro... | [
"Retrieve",
"a",
"value",
"from",
"a",
"nested",
"object",
"via",
"a",
"tuple",
"representing",
"the",
"lookup",
"path",
"."
] | 67ebaf70e39887f65ce1163168d182a8e4c2774a | https://github.com/flashashen/flange/blob/67ebaf70e39887f65ce1163168d182a8e4c2774a/flange/iterutils.py#L967-L1024 | train | 56,975 |
flashashen/flange | flange/iterutils.py | __query | def __query(p, k, v, accepted_keys=None, required_values=None, path=None, exact=True):
"""
Query function given to visit method
:param p: visited path in tuple form
:param k: visited key
:param v: visited value
:param accepted_keys: list of keys where one must match k to satisfy query.
:par... | python | def __query(p, k, v, accepted_keys=None, required_values=None, path=None, exact=True):
"""
Query function given to visit method
:param p: visited path in tuple form
:param k: visited key
:param v: visited value
:param accepted_keys: list of keys where one must match k to satisfy query.
:par... | [
"def",
"__query",
"(",
"p",
",",
"k",
",",
"v",
",",
"accepted_keys",
"=",
"None",
",",
"required_values",
"=",
"None",
",",
"path",
"=",
"None",
",",
"exact",
"=",
"True",
")",
":",
"# if not k:",
"# print '__query p k:', p, k",
"# print p, k, accepted_ke... | Query function given to visit method
:param p: visited path in tuple form
:param k: visited key
:param v: visited value
:param accepted_keys: list of keys where one must match k to satisfy query.
:param required_values: list of values where one must match v to satisfy query
:param path: exact p... | [
"Query",
"function",
"given",
"to",
"visit",
"method"
] | 67ebaf70e39887f65ce1163168d182a8e4c2774a | https://github.com/flashashen/flange/blob/67ebaf70e39887f65ce1163168d182a8e4c2774a/flange/iterutils.py#L1298-L1341 | train | 56,976 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/providers/gce.py | GoogleCloudProvider._get_image_url | def _get_image_url(self, image_id):
"""Gets the url for the specified image. Unfortunatly this only works
for images uploaded by the user. The images provided by google will
not be found.
:param str image_id: image identifier
:return: str - api url of the image
"""
... | python | def _get_image_url(self, image_id):
"""Gets the url for the specified image. Unfortunatly this only works
for images uploaded by the user. The images provided by google will
not be found.
:param str image_id: image identifier
:return: str - api url of the image
"""
... | [
"def",
"_get_image_url",
"(",
"self",
",",
"image_id",
")",
":",
"gce",
"=",
"self",
".",
"_connect",
"(",
")",
"filter",
"=",
"\"name eq %s\"",
"%",
"image_id",
"request",
"=",
"gce",
".",
"images",
"(",
")",
".",
"list",
"(",
"project",
"=",
"self",
... | Gets the url for the specified image. Unfortunatly this only works
for images uploaded by the user. The images provided by google will
not be found.
:param str image_id: image identifier
:return: str - api url of the image | [
"Gets",
"the",
"url",
"for",
"the",
"specified",
"image",
".",
"Unfortunatly",
"this",
"only",
"works",
"for",
"images",
"uploaded",
"by",
"the",
"user",
".",
"The",
"images",
"provided",
"by",
"google",
"will",
"not",
"be",
"found",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/providers/gce.py#L476-L497 | train | 56,977 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/subcommands.py | GC3PieConfig.execute | def execute(self):
"""
Load the cluster and build a GC3Pie configuration snippet.
"""
creator = make_creator(self.params.config,
storage_path=self.params.storage)
cluster_name = self.params.cluster
try:
cluster = creator.load_clu... | python | def execute(self):
"""
Load the cluster and build a GC3Pie configuration snippet.
"""
creator = make_creator(self.params.config,
storage_path=self.params.storage)
cluster_name = self.params.cluster
try:
cluster = creator.load_clu... | [
"def",
"execute",
"(",
"self",
")",
":",
"creator",
"=",
"make_creator",
"(",
"self",
".",
"params",
".",
"config",
",",
"storage_path",
"=",
"self",
".",
"params",
".",
"storage",
")",
"cluster_name",
"=",
"self",
".",
"params",
".",
"cluster",
"try",
... | Load the cluster and build a GC3Pie configuration snippet. | [
"Load",
"the",
"cluster",
"and",
"build",
"a",
"GC3Pie",
"configuration",
"snippet",
"."
] | f891b4ffb21431988bc4a063ae871da3bf284a45 | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/subcommands.py#L778-L804 | train | 56,978 |
wedi/PyMediaRSS2Gen | PyMediaRSS2Gen.py | MediaRSS2.write_xml | def write_xml(self, outfile, encoding="UTF-8"):
"""Write the Media RSS Feed's XML representation to the given file."""
# we add the media namespace if we see any media items
if any([key for item in self.items for key in vars(item) if
key.startswith('media_') and getattr(item, key... | python | def write_xml(self, outfile, encoding="UTF-8"):
"""Write the Media RSS Feed's XML representation to the given file."""
# we add the media namespace if we see any media items
if any([key for item in self.items for key in vars(item) if
key.startswith('media_') and getattr(item, key... | [
"def",
"write_xml",
"(",
"self",
",",
"outfile",
",",
"encoding",
"=",
"\"UTF-8\"",
")",
":",
"# we add the media namespace if we see any media items",
"if",
"any",
"(",
"[",
"key",
"for",
"item",
"in",
"self",
".",
"items",
"for",
"key",
"in",
"vars",
"(",
... | Write the Media RSS Feed's XML representation to the given file. | [
"Write",
"the",
"Media",
"RSS",
"Feed",
"s",
"XML",
"representation",
"to",
"the",
"given",
"file",
"."
] | 11c3d0f57386906394e303cb31f2e02be2c4fadf | https://github.com/wedi/PyMediaRSS2Gen/blob/11c3d0f57386906394e303cb31f2e02be2c4fadf/PyMediaRSS2Gen.py#L46-L53 | train | 56,979 |
wedi/PyMediaRSS2Gen | PyMediaRSS2Gen.py | MediaContent._add_attribute | def _add_attribute(self, name, value, allowed_values=None):
"""Add an attribute to the MediaContent element."""
if value and value != 'none':
if isinstance(value, (int, bool)):
value = str(value)
if allowed_values and value not in allowed_values:
... | python | def _add_attribute(self, name, value, allowed_values=None):
"""Add an attribute to the MediaContent element."""
if value and value != 'none':
if isinstance(value, (int, bool)):
value = str(value)
if allowed_values and value not in allowed_values:
... | [
"def",
"_add_attribute",
"(",
"self",
",",
"name",
",",
"value",
",",
"allowed_values",
"=",
"None",
")",
":",
"if",
"value",
"and",
"value",
"!=",
"'none'",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"bool",
")",
")",
":",
"value",... | Add an attribute to the MediaContent element. | [
"Add",
"an",
"attribute",
"to",
"the",
"MediaContent",
"element",
"."
] | 11c3d0f57386906394e303cb31f2e02be2c4fadf | https://github.com/wedi/PyMediaRSS2Gen/blob/11c3d0f57386906394e303cb31f2e02be2c4fadf/PyMediaRSS2Gen.py#L100-L112 | train | 56,980 |
wedi/PyMediaRSS2Gen | PyMediaRSS2Gen.py | MediaRSSItem.check_complicance | def check_complicance(self):
"""Check compliance with Media RSS Specification, Version 1.5.1.
see http://www.rssboard.org/media-rss
Raises AttributeError on error.
"""
# check Media RSS requirement: one of the following elements is
# required: media_group | media_content... | python | def check_complicance(self):
"""Check compliance with Media RSS Specification, Version 1.5.1.
see http://www.rssboard.org/media-rss
Raises AttributeError on error.
"""
# check Media RSS requirement: one of the following elements is
# required: media_group | media_content... | [
"def",
"check_complicance",
"(",
"self",
")",
":",
"# check Media RSS requirement: one of the following elements is",
"# required: media_group | media_content | media_player | media_peerLink",
"# | media_location. We do the check only if any media_... element is",
"# set to allow non media feeds",... | Check compliance with Media RSS Specification, Version 1.5.1.
see http://www.rssboard.org/media-rss
Raises AttributeError on error. | [
"Check",
"compliance",
"with",
"Media",
"RSS",
"Specification",
"Version",
"1",
".",
"5",
".",
"1",
"."
] | 11c3d0f57386906394e303cb31f2e02be2c4fadf | https://github.com/wedi/PyMediaRSS2Gen/blob/11c3d0f57386906394e303cb31f2e02be2c4fadf/PyMediaRSS2Gen.py#L185-L230 | train | 56,981 |
wedi/PyMediaRSS2Gen | PyMediaRSS2Gen.py | MediaRSSItem.publish_extensions | def publish_extensions(self, handler):
"""Publish the Media RSS Feed elements as XML."""
if isinstance(self.media_content, list):
[PyRSS2Gen._opt_element(handler, "media:content", mc_element) for
mc_element in self.media_content]
else:
PyRSS2Gen._opt_element(... | python | def publish_extensions(self, handler):
"""Publish the Media RSS Feed elements as XML."""
if isinstance(self.media_content, list):
[PyRSS2Gen._opt_element(handler, "media:content", mc_element) for
mc_element in self.media_content]
else:
PyRSS2Gen._opt_element(... | [
"def",
"publish_extensions",
"(",
"self",
",",
"handler",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"media_content",
",",
"list",
")",
":",
"[",
"PyRSS2Gen",
".",
"_opt_element",
"(",
"handler",
",",
"\"media:content\"",
",",
"mc_element",
")",
"for",
... | Publish the Media RSS Feed elements as XML. | [
"Publish",
"the",
"Media",
"RSS",
"Feed",
"elements",
"as",
"XML",
"."
] | 11c3d0f57386906394e303cb31f2e02be2c4fadf | https://github.com/wedi/PyMediaRSS2Gen/blob/11c3d0f57386906394e303cb31f2e02be2c4fadf/PyMediaRSS2Gen.py#L232-L245 | train | 56,982 |
fantastic001/pyfb | pyfacebook/inbox.py | Inbox.get_conversations | def get_conversations(self):
"""
Returns list of Conversation objects
"""
cs = self.data["data"]
res = []
for c in cs:
res.append(Conversation(c))
return res | python | def get_conversations(self):
"""
Returns list of Conversation objects
"""
cs = self.data["data"]
res = []
for c in cs:
res.append(Conversation(c))
return res | [
"def",
"get_conversations",
"(",
"self",
")",
":",
"cs",
"=",
"self",
".",
"data",
"[",
"\"data\"",
"]",
"res",
"=",
"[",
"]",
"for",
"c",
"in",
"cs",
":",
"res",
".",
"append",
"(",
"Conversation",
"(",
"c",
")",
")",
"return",
"res"
] | Returns list of Conversation objects | [
"Returns",
"list",
"of",
"Conversation",
"objects"
] | 385a620e8c825fea5c859aec8c309ea59ef06713 | https://github.com/fantastic001/pyfb/blob/385a620e8c825fea5c859aec8c309ea59ef06713/pyfacebook/inbox.py#L35-L43 | train | 56,983 |
CodyKochmann/generators | generators/Generator.py | _accumulate | def _accumulate(iterable, func=(lambda a,b:a+b)): # this was from the itertools documentation
'Return running totals'
# accumulate([1,2,3,4,5]) --> 1 3 6 10 15
# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
it = iter(iterable)
try:
total = next(it)
except StopIteration:
... | python | def _accumulate(iterable, func=(lambda a,b:a+b)): # this was from the itertools documentation
'Return running totals'
# accumulate([1,2,3,4,5]) --> 1 3 6 10 15
# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
it = iter(iterable)
try:
total = next(it)
except StopIteration:
... | [
"def",
"_accumulate",
"(",
"iterable",
",",
"func",
"=",
"(",
"lambda",
"a",
",",
"b",
":",
"a",
"+",
"b",
")",
")",
":",
"# this was from the itertools documentation",
"# accumulate([1,2,3,4,5]) --> 1 3 6 10 15",
"# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120",
... | Return running totals | [
"Return",
"running",
"totals"
] | e4ca4dd25d5023a94b0349c69d6224070cc2526f | https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/Generator.py#L264-L276 | train | 56,984 |
CodyKochmann/generators | generators/Generator.py | Generator.add_methods | def add_methods(methods_to_add):
''' use this to bulk add new methods to Generator '''
for i in methods_to_add:
try:
Generator.add_method(*i)
except Exception as ex:
raise Exception('issue adding {} - {}'.format(repr(i), ex)) | python | def add_methods(methods_to_add):
''' use this to bulk add new methods to Generator '''
for i in methods_to_add:
try:
Generator.add_method(*i)
except Exception as ex:
raise Exception('issue adding {} - {}'.format(repr(i), ex)) | [
"def",
"add_methods",
"(",
"methods_to_add",
")",
":",
"for",
"i",
"in",
"methods_to_add",
":",
"try",
":",
"Generator",
".",
"add_method",
"(",
"*",
"i",
")",
"except",
"Exception",
"as",
"ex",
":",
"raise",
"Exception",
"(",
"'issue adding {} - {}'",
".",
... | use this to bulk add new methods to Generator | [
"use",
"this",
"to",
"bulk",
"add",
"new",
"methods",
"to",
"Generator"
] | e4ca4dd25d5023a94b0349c69d6224070cc2526f | https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/Generator.py#L145-L151 | train | 56,985 |
FNNDSC/pftree | pftree/pftree.py | pftree.dirsize_get | def dirsize_get(l_filesWithoutPath, **kwargs):
"""
Sample callback that determines a directory size.
"""
str_path = ""
for k,v in kwargs.items():
if k == 'path': str_path = v
d_ret = {}
l_size = []
size = 0
for f in l_filesWi... | python | def dirsize_get(l_filesWithoutPath, **kwargs):
"""
Sample callback that determines a directory size.
"""
str_path = ""
for k,v in kwargs.items():
if k == 'path': str_path = v
d_ret = {}
l_size = []
size = 0
for f in l_filesWi... | [
"def",
"dirsize_get",
"(",
"l_filesWithoutPath",
",",
"*",
"*",
"kwargs",
")",
":",
"str_path",
"=",
"\"\"",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'path'",
":",
"str_path",
"=",
"v",
"d_ret",
"=",
"{",... | Sample callback that determines a directory size. | [
"Sample",
"callback",
"that",
"determines",
"a",
"directory",
"size",
"."
] | b841e337c976bce151735f9d5dd95eded62aa094 | https://github.com/FNNDSC/pftree/blob/b841e337c976bce151735f9d5dd95eded62aa094/pftree/pftree.py#L284-L309 | train | 56,986 |
FNNDSC/pftree | pftree/pftree.py | pftree.inputReadCallback | def inputReadCallback(self, *args, **kwargs):
"""
Test for inputReadCallback
This method does not actually "read" the input files,
but simply returns the passed file list back to
caller
"""
b_status = True
filesRead = 0
for k, v in kwargs.i... | python | def inputReadCallback(self, *args, **kwargs):
"""
Test for inputReadCallback
This method does not actually "read" the input files,
but simply returns the passed file list back to
caller
"""
b_status = True
filesRead = 0
for k, v in kwargs.i... | [
"def",
"inputReadCallback",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"b_status",
"=",
"True",
"filesRead",
"=",
"0",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'l_file'",
":",
"l_... | Test for inputReadCallback
This method does not actually "read" the input files,
but simply returns the passed file list back to
caller | [
"Test",
"for",
"inputReadCallback"
] | b841e337c976bce151735f9d5dd95eded62aa094 | https://github.com/FNNDSC/pftree/blob/b841e337c976bce151735f9d5dd95eded62aa094/pftree/pftree.py#L771-L804 | train | 56,987 |
FNNDSC/pftree | pftree/pftree.py | pftree.inputAnalyzeCallback | def inputAnalyzeCallback(self, *args, **kwargs):
"""
Test method for inputAnalzeCallback
This method loops over the passed number of files,
and optionally "delays" in each loop to simulate
some analysis. The delay length is specified by
the '--test <delay>' flag.
... | python | def inputAnalyzeCallback(self, *args, **kwargs):
"""
Test method for inputAnalzeCallback
This method loops over the passed number of files,
and optionally "delays" in each loop to simulate
some analysis. The delay length is specified by
the '--test <delay>' flag.
... | [
"def",
"inputAnalyzeCallback",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"b_status",
"=",
"False",
"filesRead",
"=",
"0",
"filesAnalyzed",
"=",
"0",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k... | Test method for inputAnalzeCallback
This method loops over the passed number of files,
and optionally "delays" in each loop to simulate
some analysis. The delay length is specified by
the '--test <delay>' flag. | [
"Test",
"method",
"for",
"inputAnalzeCallback"
] | b841e337c976bce151735f9d5dd95eded62aa094 | https://github.com/FNNDSC/pftree/blob/b841e337c976bce151735f9d5dd95eded62aa094/pftree/pftree.py#L806-L842 | train | 56,988 |
FNNDSC/pftree | pftree/pftree.py | pftree.outputSaveCallback | def outputSaveCallback(self, at_data, **kwargs):
"""
Test method for outputSaveCallback
Simply writes a file in the output tree corresponding
to the number of files in the input tree.
"""
path = at_data[0]
d_outputInfo = at_data[1]
o... | python | def outputSaveCallback(self, at_data, **kwargs):
"""
Test method for outputSaveCallback
Simply writes a file in the output tree corresponding
to the number of files in the input tree.
"""
path = at_data[0]
d_outputInfo = at_data[1]
o... | [
"def",
"outputSaveCallback",
"(",
"self",
",",
"at_data",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"at_data",
"[",
"0",
"]",
"d_outputInfo",
"=",
"at_data",
"[",
"1",
"]",
"other",
".",
"mkdir",
"(",
"self",
".",
"str_outputDir",
")",
"filesSave... | Test method for outputSaveCallback
Simply writes a file in the output tree corresponding
to the number of files in the input tree. | [
"Test",
"method",
"for",
"outputSaveCallback"
] | b841e337c976bce151735f9d5dd95eded62aa094 | https://github.com/FNNDSC/pftree/blob/b841e337c976bce151735f9d5dd95eded62aa094/pftree/pftree.py#L844-L873 | train | 56,989 |
FNNDSC/pftree | pftree/pftree.py | pftree.run | def run(self, *args, **kwargs):
"""
Probe the input tree and print.
"""
b_status = True
d_probe = {}
d_tree = {}
d_stats = {}
str_error = ''
b_timerStart = False
d_test = {}
for k, ... | python | def run(self, *args, **kwargs):
"""
Probe the input tree and print.
"""
b_status = True
d_probe = {}
d_tree = {}
d_stats = {}
str_error = ''
b_timerStart = False
d_test = {}
for k, ... | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"b_status",
"=",
"True",
"d_probe",
"=",
"{",
"}",
"d_tree",
"=",
"{",
"}",
"d_stats",
"=",
"{",
"}",
"str_error",
"=",
"''",
"b_timerStart",
"=",
"False",
"d_test",
... | Probe the input tree and print. | [
"Probe",
"the",
"input",
"tree",
"and",
"print",
"."
] | b841e337c976bce151735f9d5dd95eded62aa094 | https://github.com/FNNDSC/pftree/blob/b841e337c976bce151735f9d5dd95eded62aa094/pftree/pftree.py#L891-L967 | train | 56,990 |
cdumay/kser | src/kser/sequencing/operation.py | Operation._set_status | def _set_status(self, status, result=None):
""" update operation status
:param str status: New status
:param cdumay_result.Result result: Execution result
"""
logger.info(
"{}.SetStatus: {}[{}] status update '{}' -> '{}'".format(
self.__class__.__name... | python | def _set_status(self, status, result=None):
""" update operation status
:param str status: New status
:param cdumay_result.Result result: Execution result
"""
logger.info(
"{}.SetStatus: {}[{}] status update '{}' -> '{}'".format(
self.__class__.__name... | [
"def",
"_set_status",
"(",
"self",
",",
"status",
",",
"result",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"\"{}.SetStatus: {}[{}] status update '{}' -> '{}'\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"__class... | update operation status
:param str status: New status
:param cdumay_result.Result result: Execution result | [
"update",
"operation",
"status"
] | fbd6fe9ab34b8b89d9937e5ff727614304af48c1 | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/sequencing/operation.py#L56-L74 | train | 56,991 |
cdumay/kser | src/kser/sequencing/operation.py | Operation._prerun | def _prerun(self):
""" To execute before running message
"""
self.check_required_params()
self._set_status("RUNNING")
logger.debug(
"{}.PreRun: {}[{}]: running...".format(
self.__class__.__name__, self.__class__.path, self.uuid
),
... | python | def _prerun(self):
""" To execute before running message
"""
self.check_required_params()
self._set_status("RUNNING")
logger.debug(
"{}.PreRun: {}[{}]: running...".format(
self.__class__.__name__, self.__class__.path, self.uuid
),
... | [
"def",
"_prerun",
"(",
"self",
")",
":",
"self",
".",
"check_required_params",
"(",
")",
"self",
".",
"_set_status",
"(",
"\"RUNNING\"",
")",
"logger",
".",
"debug",
"(",
"\"{}.PreRun: {}[{}]: running...\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
... | To execute before running message | [
"To",
"execute",
"before",
"running",
"message"
] | fbd6fe9ab34b8b89d9937e5ff727614304af48c1 | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/sequencing/operation.py#L113-L129 | train | 56,992 |
cdumay/kser | src/kser/sequencing/operation.py | Operation.next | def next(self, task):
""" Find the next task
:param kser.sequencing.task.Task task: previous task
:return: The next task
:rtype: kser.sequencing.task.Task or None
"""
uuid = str(task.uuid)
for idx, otask in enumerate(self.tasks[:-1]):
if otask.uuid ==... | python | def next(self, task):
""" Find the next task
:param kser.sequencing.task.Task task: previous task
:return: The next task
:rtype: kser.sequencing.task.Task or None
"""
uuid = str(task.uuid)
for idx, otask in enumerate(self.tasks[:-1]):
if otask.uuid ==... | [
"def",
"next",
"(",
"self",
",",
"task",
")",
":",
"uuid",
"=",
"str",
"(",
"task",
".",
"uuid",
")",
"for",
"idx",
",",
"otask",
"in",
"enumerate",
"(",
"self",
".",
"tasks",
"[",
":",
"-",
"1",
"]",
")",
":",
"if",
"otask",
".",
"uuid",
"==... | Find the next task
:param kser.sequencing.task.Task task: previous task
:return: The next task
:rtype: kser.sequencing.task.Task or None | [
"Find",
"the",
"next",
"task"
] | fbd6fe9ab34b8b89d9937e5ff727614304af48c1 | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/sequencing/operation.py#L194-L207 | train | 56,993 |
cdumay/kser | src/kser/sequencing/operation.py | Operation.launch_next | def launch_next(self, task=None, result=None):
""" Launch next task or finish operation
:param kser.sequencing.task.Task task: previous task
:param cdumay_result.Result result: previous task result
:return: Execution result
:rtype: cdumay_result.Result
"""
if ta... | python | def launch_next(self, task=None, result=None):
""" Launch next task or finish operation
:param kser.sequencing.task.Task task: previous task
:param cdumay_result.Result result: previous task result
:return: Execution result
:rtype: cdumay_result.Result
"""
if ta... | [
"def",
"launch_next",
"(",
"self",
",",
"task",
"=",
"None",
",",
"result",
"=",
"None",
")",
":",
"if",
"task",
":",
"next_task",
"=",
"self",
".",
"next",
"(",
"task",
")",
"if",
"next_task",
":",
"return",
"next_task",
".",
"send",
"(",
"result",
... | Launch next task or finish operation
:param kser.sequencing.task.Task task: previous task
:param cdumay_result.Result result: previous task result
:return: Execution result
:rtype: cdumay_result.Result | [
"Launch",
"next",
"task",
"or",
"finish",
"operation"
] | fbd6fe9ab34b8b89d9937e5ff727614304af48c1 | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/sequencing/operation.py#L209-L227 | train | 56,994 |
cdumay/kser | src/kser/sequencing/operation.py | Operation.compute_tasks | def compute_tasks(self, **kwargs):
""" perfrom checks and build tasks
:return: list of tasks
:rtype: list(kser.sequencing.operation.Operation)
"""
params = self._prebuild(**kwargs)
if not params:
params = dict(kwargs)
return self._build_tasks(**param... | python | def compute_tasks(self, **kwargs):
""" perfrom checks and build tasks
:return: list of tasks
:rtype: list(kser.sequencing.operation.Operation)
"""
params = self._prebuild(**kwargs)
if not params:
params = dict(kwargs)
return self._build_tasks(**param... | [
"def",
"compute_tasks",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"self",
".",
"_prebuild",
"(",
"*",
"*",
"kwargs",
")",
"if",
"not",
"params",
":",
"params",
"=",
"dict",
"(",
"kwargs",
")",
"return",
"self",
".",
"_build_tasks... | perfrom checks and build tasks
:return: list of tasks
:rtype: list(kser.sequencing.operation.Operation) | [
"perfrom",
"checks",
"and",
"build",
"tasks"
] | fbd6fe9ab34b8b89d9937e5ff727614304af48c1 | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/sequencing/operation.py#L277-L287 | train | 56,995 |
cdumay/kser | src/kser/sequencing/operation.py | Operation.build | def build(self, **kwargs):
""" create the operation and associate tasks
:param dict kwargs: operation data
:return: the controller
:rtype: kser.sequencing.controller.OperationController
"""
self.tasks += self.compute_tasks(**kwargs)
return self.finalize() | python | def build(self, **kwargs):
""" create the operation and associate tasks
:param dict kwargs: operation data
:return: the controller
:rtype: kser.sequencing.controller.OperationController
"""
self.tasks += self.compute_tasks(**kwargs)
return self.finalize() | [
"def",
"build",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"tasks",
"+=",
"self",
".",
"compute_tasks",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"finalize",
"(",
")"
] | create the operation and associate tasks
:param dict kwargs: operation data
:return: the controller
:rtype: kser.sequencing.controller.OperationController | [
"create",
"the",
"operation",
"and",
"associate",
"tasks"
] | fbd6fe9ab34b8b89d9937e5ff727614304af48c1 | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/sequencing/operation.py#L289-L297 | train | 56,996 |
jic-dtool/dtool-http | dtool_http/server.py | serve_dtool_directory | def serve_dtool_directory(directory, port):
"""Serve the datasets in a directory over HTTP."""
os.chdir(directory)
server_address = ("localhost", port)
httpd = DtoolHTTPServer(server_address, DtoolHTTPRequestHandler)
httpd.serve_forever() | python | def serve_dtool_directory(directory, port):
"""Serve the datasets in a directory over HTTP."""
os.chdir(directory)
server_address = ("localhost", port)
httpd = DtoolHTTPServer(server_address, DtoolHTTPRequestHandler)
httpd.serve_forever() | [
"def",
"serve_dtool_directory",
"(",
"directory",
",",
"port",
")",
":",
"os",
".",
"chdir",
"(",
"directory",
")",
"server_address",
"=",
"(",
"\"localhost\"",
",",
"port",
")",
"httpd",
"=",
"DtoolHTTPServer",
"(",
"server_address",
",",
"DtoolHTTPRequestHandl... | Serve the datasets in a directory over HTTP. | [
"Serve",
"the",
"datasets",
"in",
"a",
"directory",
"over",
"HTTP",
"."
] | 7572221b07d5294aa9ead5097a4f16478837e742 | https://github.com/jic-dtool/dtool-http/blob/7572221b07d5294aa9ead5097a4f16478837e742/dtool_http/server.py#L90-L95 | train | 56,997 |
jic-dtool/dtool-http | dtool_http/server.py | cli | def cli():
"""Command line utility for serving datasets in a directory over HTTP."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"dataset_directory",
help="Directory with datasets to be served"
)
parser.add_argument(
"-p",
"--port",
... | python | def cli():
"""Command line utility for serving datasets in a directory over HTTP."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"dataset_directory",
help="Directory with datasets to be served"
)
parser.add_argument(
"-p",
"--port",
... | [
"def",
"cli",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"\"dataset_directory\"",
",",
"help",
"=",
"\"Directory with datasets to be served\"",
")",
"parser",
".",
... | Command line utility for serving datasets in a directory over HTTP. | [
"Command",
"line",
"utility",
"for",
"serving",
"datasets",
"in",
"a",
"directory",
"over",
"HTTP",
"."
] | 7572221b07d5294aa9ead5097a4f16478837e742 | https://github.com/jic-dtool/dtool-http/blob/7572221b07d5294aa9ead5097a4f16478837e742/dtool_http/server.py#L98-L116 | train | 56,998 |
jic-dtool/dtool-http | dtool_http/server.py | DtoolHTTPRequestHandler.generate_url | def generate_url(self, suffix):
"""Return URL by combining server details with a path suffix."""
url_base_path = os.path.dirname(self.path)
netloc = "{}:{}".format(*self.server.server_address)
return urlunparse((
"http",
netloc,
url_base_path + "/" + s... | python | def generate_url(self, suffix):
"""Return URL by combining server details with a path suffix."""
url_base_path = os.path.dirname(self.path)
netloc = "{}:{}".format(*self.server.server_address)
return urlunparse((
"http",
netloc,
url_base_path + "/" + s... | [
"def",
"generate_url",
"(",
"self",
",",
"suffix",
")",
":",
"url_base_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"path",
")",
"netloc",
"=",
"\"{}:{}\"",
".",
"format",
"(",
"*",
"self",
".",
"server",
".",
"server_address",
")",... | Return URL by combining server details with a path suffix. | [
"Return",
"URL",
"by",
"combining",
"server",
"details",
"with",
"a",
"path",
"suffix",
"."
] | 7572221b07d5294aa9ead5097a4f16478837e742 | https://github.com/jic-dtool/dtool-http/blob/7572221b07d5294aa9ead5097a4f16478837e742/dtool_http/server.py#L16-L24 | train | 56,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.