repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
oubiwann/carapace | carapace/config.py | Configurator.updateConfig | def updateConfig(self):
"""
If the configfile doesn't exist, this method will (indirectly) create
it and exit.
If it does exist, it will load the config values from the file (which
may be different from those defined be default in this module), and
update the in-memory c... | python | def updateConfig(self):
"""
If the configfile doesn't exist, this method will (indirectly) create
it and exit.
If it does exist, it will load the config values from the file (which
may be different from those defined be default in this module), and
update the in-memory c... | [
"def",
"updateConfig",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"getConfig",
"(",
")",
"if",
"not",
"config",
":",
"return",
"self",
".",
"ssh",
".",
"servicename",
"=",
"config",
".",
"get",
"(",
"\"SSH\"",
",",
"\"servicename\"",
")",
"self... | If the configfile doesn't exist, this method will (indirectly) create
it and exit.
If it does exist, it will load the config values from the file (which
may be different from those defined be default in this module), and
update the in-memory config values with what it reads from the fil... | [
"If",
"the",
"configfile",
"doesn",
"t",
"exist",
"this",
"method",
"will",
"(",
"indirectly",
")",
"create",
"it",
"and",
"exit",
"."
] | train | https://github.com/oubiwann/carapace/blob/88470b12c198bea5067dcff1a26aa4400b73632c/carapace/config.py#L102-L127 |
testing-cabal/systemfixtures | systemfixtures/executable.py | allocate_port | def allocate_port():
"""Allocate an unused port.
There is a small race condition here (between the time we allocate the
port, and the time it actually gets used), but for the purposes for which
this function gets used it isn't a problem in practice.
"""
sock = socket.socket()
try:
s... | python | def allocate_port():
"""Allocate an unused port.
There is a small race condition here (between the time we allocate the
port, and the time it actually gets used), but for the purposes for which
this function gets used it isn't a problem in practice.
"""
sock = socket.socket()
try:
s... | [
"def",
"allocate_port",
"(",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
")",
"try",
":",
"sock",
".",
"bind",
"(",
"(",
"\"localhost\"",
",",
"0",
")",
")",
"return",
"get_port",
"(",
"sock",
")",
"finally",
":",
"sock",
".",
"close",
"("... | Allocate an unused port.
There is a small race condition here (between the time we allocate the
port, and the time it actually gets used), but for the purposes for which
this function gets used it isn't a problem in practice. | [
"Allocate",
"an",
"unused",
"port",
"."
] | train | https://github.com/testing-cabal/systemfixtures/blob/adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4/systemfixtures/executable.py#L115-L127 |
testing-cabal/systemfixtures | systemfixtures/executable.py | FakeExecutable.spawn | def spawn(self):
"""Spawn the fake executable using subprocess.Popen."""
self._process = subprocess.Popen(
[self.path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
self.addCleanup(self._process_kill) | python | def spawn(self):
"""Spawn the fake executable using subprocess.Popen."""
self._process = subprocess.Popen(
[self.path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
self.addCleanup(self._process_kill) | [
"def",
"spawn",
"(",
"self",
")",
":",
"self",
".",
"_process",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"self",
".",
"path",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"self",
".",
"... | Spawn the fake executable using subprocess.Popen. | [
"Spawn",
"the",
"fake",
"executable",
"using",
"subprocess",
".",
"Popen",
"."
] | train | https://github.com/testing-cabal/systemfixtures/blob/adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4/systemfixtures/executable.py#L34-L38 |
testing-cabal/systemfixtures | systemfixtures/executable.py | FakeExecutable.listen | def listen(self, port=None):
"""Make the fake executable listen to the specified port.
Possible values for 'port' are:
- None: Allocate immediately a free port and instruct the fake
executable to use it when it's invoked. This is subject to
a race condition, if that port th... | python | def listen(self, port=None):
"""Make the fake executable listen to the specified port.
Possible values for 'port' are:
- None: Allocate immediately a free port and instruct the fake
executable to use it when it's invoked. This is subject to
a race condition, if that port th... | [
"def",
"listen",
"(",
"self",
",",
"port",
"=",
"None",
")",
":",
"if",
"port",
"is",
"None",
":",
"port",
"=",
"allocate_port",
"(",
")",
"self",
".",
"port",
"=",
"port",
"self",
".",
"line",
"(",
"\"import socket\"",
")",
"self",
".",
"line",
"(... | Make the fake executable listen to the specified port.
Possible values for 'port' are:
- None: Allocate immediately a free port and instruct the fake
executable to use it when it's invoked. This is subject to
a race condition, if that port that was free when listen() was
... | [
"Make",
"the",
"fake",
"executable",
"listen",
"to",
"the",
"specified",
"port",
"."
] | train | https://github.com/testing-cabal/systemfixtures/blob/adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4/systemfixtures/executable.py#L59-L81 |
testing-cabal/systemfixtures | systemfixtures/executable.py | FakeExecutable._process_kill | def _process_kill(self):
"""Kill the fake executable process if it's still running."""
if self._process.poll() is None: # pragma: no cover
self._process.kill()
self._process.wait(timeout=5) | python | def _process_kill(self):
"""Kill the fake executable process if it's still running."""
if self._process.poll() is None: # pragma: no cover
self._process.kill()
self._process.wait(timeout=5) | [
"def",
"_process_kill",
"(",
"self",
")",
":",
"if",
"self",
".",
"_process",
".",
"poll",
"(",
")",
"is",
"None",
":",
"# pragma: no cover",
"self",
".",
"_process",
".",
"kill",
"(",
")",
"self",
".",
"_process",
".",
"wait",
"(",
"timeout",
"=",
"... | Kill the fake executable process if it's still running. | [
"Kill",
"the",
"fake",
"executable",
"process",
"if",
"it",
"s",
"still",
"running",
"."
] | train | https://github.com/testing-cabal/systemfixtures/blob/adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4/systemfixtures/executable.py#L87-L91 |
testing-cabal/systemfixtures | systemfixtures/executable.py | FakeExecutable._process_info | def _process_info(self):
"""Return details about the fake process."""
if not self._process:
return []
output, error = self._process.communicate(timeout=5)
if error is None:
error = b""
output = output.decode("utf-8").strip()
error = error.decode("... | python | def _process_info(self):
"""Return details about the fake process."""
if not self._process:
return []
output, error = self._process.communicate(timeout=5)
if error is None:
error = b""
output = output.decode("utf-8").strip()
error = error.decode("... | [
"def",
"_process_info",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_process",
":",
"return",
"[",
"]",
"output",
",",
"error",
"=",
"self",
".",
"_process",
".",
"communicate",
"(",
"timeout",
"=",
"5",
")",
"if",
"error",
"is",
"None",
":",
... | Return details about the fake process. | [
"Return",
"details",
"about",
"the",
"fake",
"process",
"."
] | train | https://github.com/testing-cabal/systemfixtures/blob/adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4/systemfixtures/executable.py#L93-L106 |
usc-isi-i2/dig-sparkutil | digSparkUtil/ESUtil.py | AddClusterId.addClusterId | def addClusterId(self,line):
"""
:param line:
reads all the ads in particular cluster, takes the hash of those uri's and appends that as cluster_id
"""
if isinstance(line,dict):
jsonObj = line
else:
jsonObj = json.loads(line)
concat_str=''... | python | def addClusterId(self,line):
"""
:param line:
reads all the ads in particular cluster, takes the hash of those uri's and appends that as cluster_id
"""
if isinstance(line,dict):
jsonObj = line
else:
jsonObj = json.loads(line)
concat_str=''... | [
"def",
"addClusterId",
"(",
"self",
",",
"line",
")",
":",
"if",
"isinstance",
"(",
"line",
",",
"dict",
")",
":",
"jsonObj",
"=",
"line",
"else",
":",
"jsonObj",
"=",
"json",
".",
"loads",
"(",
"line",
")",
"concat_str",
"=",
"''",
"for",
"item",
... | :param line:
reads all the ads in particular cluster, takes the hash of those uri's and appends that as cluster_id | [
":",
"param",
"line",
":",
"reads",
"all",
"the",
"ads",
"in",
"particular",
"cluster",
"takes",
"the",
"hash",
"of",
"those",
"uri",
"s",
"and",
"appends",
"that",
"as",
"cluster_id"
] | train | https://github.com/usc-isi-i2/dig-sparkutil/blob/d39c6cf957025c170753b0e02e477fea20ee3f2a/digSparkUtil/ESUtil.py#L23-L38 |
aganezov/gos | gos/tasks.py | TaskLoader.load_tasks_from_file | def load_tasks_from_file(self, file_path):
""" Imports specified python module and returns subclasses of BaseTask from it
:param file_path: a fully qualified file path for a python module to import CustomTasks from
:type file_path: `str`
:return: a dict of CustomTasks, where key is Cust... | python | def load_tasks_from_file(self, file_path):
""" Imports specified python module and returns subclasses of BaseTask from it
:param file_path: a fully qualified file path for a python module to import CustomTasks from
:type file_path: `str`
:return: a dict of CustomTasks, where key is Cust... | [
"def",
"load_tasks_from_file",
"(",
"self",
",",
"file_path",
")",
":",
"file_name",
",",
"module_path",
",",
"objects",
"=",
"Loader",
".",
"import_custom_python_file",
"(",
"file_path",
")",
"result",
"=",
"{",
"}",
"for",
"entry",
"in",
"objects",
":",
"t... | Imports specified python module and returns subclasses of BaseTask from it
:param file_path: a fully qualified file path for a python module to import CustomTasks from
:type file_path: `str`
:return: a dict of CustomTasks, where key is CustomTask.name, and value is a CustomClass task itself
... | [
"Imports",
"specified",
"python",
"module",
"and",
"returns",
"subclasses",
"of",
"BaseTask",
"from",
"it"
] | train | https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/tasks.py#L18-L38 |
aganezov/gos | gos/tasks.py | TaskLoader.load_tasks_from_dir | def load_tasks_from_dir(self, dir_path, propagate_exceptions=False):
""" Imports all python modules in specified directories and returns subclasses of BaseTask from them
:param propagate_exceptions: a flag that indicates if exceptions from single file import shall be raised during the
whole... | python | def load_tasks_from_dir(self, dir_path, propagate_exceptions=False):
""" Imports all python modules in specified directories and returns subclasses of BaseTask from them
:param propagate_exceptions: a flag that indicates if exceptions from single file import shall be raised during the
whole... | [
"def",
"load_tasks_from_dir",
"(",
"self",
",",
"dir_path",
",",
"propagate_exceptions",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dir_path",
")",
":",
"raise",
"GOSTaskException",
"(",
")",
"if",
"os",
".",
"path",
"."... | Imports all python modules in specified directories and returns subclasses of BaseTask from them
:param propagate_exceptions: a flag that indicates if exceptions from single file import shall be raised during the
whole directory lookup
:param dir_path: fully qualified directory path, where ... | [
"Imports",
"all",
"python",
"modules",
"in",
"specified",
"directories",
"and",
"returns",
"subclasses",
"of",
"BaseTask",
"from",
"them"
] | train | https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/tasks.py#L40-L62 |
aganezov/gos | gos/tasks.py | TaskLoader.load_tasks | def load_tasks(self, paths, propagate_exception=False):
""" Loads all subclasses of BaseTask from modules that are contained in supplied directory paths or direct module paths
:param propagate_exception: a flag that indicates if exceptions from single file import shall be raised during the
... | python | def load_tasks(self, paths, propagate_exception=False):
""" Loads all subclasses of BaseTask from modules that are contained in supplied directory paths or direct module paths
:param propagate_exception: a flag that indicates if exceptions from single file import shall be raised during the
... | [
"def",
"load_tasks",
"(",
"self",
",",
"paths",
",",
"propagate_exception",
"=",
"False",
")",
":",
"try",
":",
"result",
"=",
"{",
"}",
"for",
"path",
"in",
"paths",
":",
"try",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
... | Loads all subclasses of BaseTask from modules that are contained in supplied directory paths or direct module paths
:param propagate_exception: a flag that indicates if exceptions from single file import shall be raised during the
whole directory lookup
:param paths: an iterable of fully qu... | [
"Loads",
"all",
"subclasses",
"of",
"BaseTask",
"from",
"modules",
"that",
"are",
"contained",
"in",
"supplied",
"directory",
"paths",
"or",
"direct",
"module",
"paths"
] | train | https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/tasks.py#L64-L87 |
relekang/rmoq | rmoq/base.py | Mock.activate | def activate(self, prefix=None, backend=None):
"""
A decorator used to activate the mocker.
:param prefix:
:param backend: An instance of a storage backend.
"""
if isinstance(prefix, compat.string_types):
self.prefix = prefix
if isinstance(backend, R... | python | def activate(self, prefix=None, backend=None):
"""
A decorator used to activate the mocker.
:param prefix:
:param backend: An instance of a storage backend.
"""
if isinstance(prefix, compat.string_types):
self.prefix = prefix
if isinstance(backend, R... | [
"def",
"activate",
"(",
"self",
",",
"prefix",
"=",
"None",
",",
"backend",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"prefix",
",",
"compat",
".",
"string_types",
")",
":",
"self",
".",
"prefix",
"=",
"prefix",
"if",
"isinstance",
"(",
"backend"... | A decorator used to activate the mocker.
:param prefix:
:param backend: An instance of a storage backend. | [
"A",
"decorator",
"used",
"to",
"activate",
"the",
"mocker",
"."
] | train | https://github.com/relekang/rmoq/blob/61fd2a221e247b7aca87492f10c3bc3894536260/rmoq/base.py#L38-L61 |
roaet/wafflehaus.neutron | wafflehaus/neutron/nova_interaction/__init__.py | NovaInteraction._process_call | def _process_call(self, req, resource):
"""This is were all callbacks are made and the req is processed."""
if resource == "ports":
if req.method.upper() in ('PUT', 'POST'):
# Pass the request back to be processed by other filters
# and Neutron first
... | python | def _process_call(self, req, resource):
"""This is were all callbacks are made and the req is processed."""
if resource == "ports":
if req.method.upper() in ('PUT', 'POST'):
# Pass the request back to be processed by other filters
# and Neutron first
... | [
"def",
"_process_call",
"(",
"self",
",",
"req",
",",
"resource",
")",
":",
"if",
"resource",
"==",
"\"ports\"",
":",
"if",
"req",
".",
"method",
".",
"upper",
"(",
")",
"in",
"(",
"'PUT'",
",",
"'POST'",
")",
":",
"# Pass the request back to be processed ... | This is were all callbacks are made and the req is processed. | [
"This",
"is",
"were",
"all",
"callbacks",
"are",
"made",
"and",
"the",
"req",
"is",
"processed",
"."
] | train | https://github.com/roaet/wafflehaus.neutron/blob/01f6d69ae759ec2f24f2f7cf9dcfa4a4734f7e1c/wafflehaus/neutron/nova_interaction/__init__.py#L42-L130 |
kalekundert/nonstdlib | nonstdlib/io.py | keep_on_one_line | def keep_on_one_line():
"""
Keep all the output generated within a with-block on one line. Whenever a
new line would be printed, instead reset the cursor to the beginning of the
line and print the new line without a line break.
"""
class CondensedStream:
def __init__(self):
... | python | def keep_on_one_line():
"""
Keep all the output generated within a with-block on one line. Whenever a
new line would be printed, instead reset the cursor to the beginning of the
line and print the new line without a line break.
"""
class CondensedStream:
def __init__(self):
... | [
"def",
"keep_on_one_line",
"(",
")",
":",
"class",
"CondensedStream",
":",
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"sys_stdout",
"=",
"sys",
".",
"stdout",
"def",
"write",
"(",
"self",
",",
"string",
")",
":",
"with",
"swap_streams",
"(",
... | Keep all the output generated within a with-block on one line. Whenever a
new line would be printed, instead reset the cursor to the beginning of the
line and print the new line without a line break. | [
"Keep",
"all",
"the",
"output",
"generated",
"within",
"a",
"with",
"-",
"block",
"on",
"one",
"line",
".",
"Whenever",
"a",
"new",
"line",
"would",
"be",
"printed",
"instead",
"reset",
"the",
"cursor",
"to",
"the",
"beginning",
"of",
"the",
"line",
"and... | train | https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/io.py#L113-L138 |
kalekundert/nonstdlib | nonstdlib/io.py | write_color | def write_color(string, name, style='normal', when='auto'):
""" Write the given colored string to standard out. """
write(color(string, name, style, when)) | python | def write_color(string, name, style='normal', when='auto'):
""" Write the given colored string to standard out. """
write(color(string, name, style, when)) | [
"def",
"write_color",
"(",
"string",
",",
"name",
",",
"style",
"=",
"'normal'",
",",
"when",
"=",
"'auto'",
")",
":",
"write",
"(",
"color",
"(",
"string",
",",
"name",
",",
"style",
",",
"when",
")",
")"
] | Write the given colored string to standard out. | [
"Write",
"the",
"given",
"colored",
"string",
"to",
"standard",
"out",
"."
] | train | https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/io.py#L149-L151 |
kalekundert/nonstdlib | nonstdlib/io.py | update_color | def update_color(string, name, style='normal', when='auto'):
""" Replace the existing line with the given colored string. """
clear()
write_color(string, name, style, when) | python | def update_color(string, name, style='normal', when='auto'):
""" Replace the existing line with the given colored string. """
clear()
write_color(string, name, style, when) | [
"def",
"update_color",
"(",
"string",
",",
"name",
",",
"style",
"=",
"'normal'",
",",
"when",
"=",
"'auto'",
")",
":",
"clear",
"(",
")",
"write_color",
"(",
"string",
",",
"name",
",",
"style",
",",
"when",
")"
] | Replace the existing line with the given colored string. | [
"Replace",
"the",
"existing",
"line",
"with",
"the",
"given",
"colored",
"string",
"."
] | train | https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/io.py#L158-L161 |
kalekundert/nonstdlib | nonstdlib/io.py | progress_color | def progress_color(current, total, name, style='normal', when='auto'):
""" Display a simple, colored progress report. """
update_color('[%d/%d] ' % (current, total), name, style, when) | python | def progress_color(current, total, name, style='normal', when='auto'):
""" Display a simple, colored progress report. """
update_color('[%d/%d] ' % (current, total), name, style, when) | [
"def",
"progress_color",
"(",
"current",
",",
"total",
",",
"name",
",",
"style",
"=",
"'normal'",
",",
"when",
"=",
"'auto'",
")",
":",
"update_color",
"(",
"'[%d/%d] '",
"%",
"(",
"current",
",",
"total",
")",
",",
"name",
",",
"style",
",",
"when",
... | Display a simple, colored progress report. | [
"Display",
"a",
"simple",
"colored",
"progress",
"report",
"."
] | train | https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/io.py#L167-L169 |
kalekundert/nonstdlib | nonstdlib/io.py | color | def color(string, name, style='normal', when='auto'):
""" Change the color of the given string. """
if name not in colors:
from .text import oxford_comma
raise ValueError("unknown color '{}'.\nknown colors are: {}".format(
name, oxford_comma(["'{}'".format(x) for x in sorted(colors)]... | python | def color(string, name, style='normal', when='auto'):
""" Change the color of the given string. """
if name not in colors:
from .text import oxford_comma
raise ValueError("unknown color '{}'.\nknown colors are: {}".format(
name, oxford_comma(["'{}'".format(x) for x in sorted(colors)]... | [
"def",
"color",
"(",
"string",
",",
"name",
",",
"style",
"=",
"'normal'",
",",
"when",
"=",
"'auto'",
")",
":",
"if",
"name",
"not",
"in",
"colors",
":",
"from",
".",
"text",
"import",
"oxford_comma",
"raise",
"ValueError",
"(",
"\"unknown color '{}'.\\nk... | Change the color of the given string. | [
"Change",
"the",
"color",
"of",
"the",
"given",
"string",
"."
] | train | https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/io.py#L171-L194 |
fstab50/metal | metal/chkrootkit.py | compile_binary | def compile_binary(source):
"""
Prepare chkrootkit binary
$ tar xzvf chkrootkit.tar.gz
$ cd chkrootkit-0.52
$ make sense
sudo mv chkrootkit-0.52 /usr/local/chkrootkit
sudo ln -s
"""
cmd = 'make sense'
slink = '/usr/local/bin/chkrootkit'
target = '/usr/local/chkrootkit/chkroot... | python | def compile_binary(source):
"""
Prepare chkrootkit binary
$ tar xzvf chkrootkit.tar.gz
$ cd chkrootkit-0.52
$ make sense
sudo mv chkrootkit-0.52 /usr/local/chkrootkit
sudo ln -s
"""
cmd = 'make sense'
slink = '/usr/local/bin/chkrootkit'
target = '/usr/local/chkrootkit/chkroot... | [
"def",
"compile_binary",
"(",
"source",
")",
":",
"cmd",
"=",
"'make sense'",
"slink",
"=",
"'/usr/local/bin/chkrootkit'",
"target",
"=",
"'/usr/local/chkrootkit/chkrootkit'",
"# Tar Extraction",
"t",
"=",
"tarfile",
".",
"open",
"(",
"source",
",",
"'r'",
")",
"t... | Prepare chkrootkit binary
$ tar xzvf chkrootkit.tar.gz
$ cd chkrootkit-0.52
$ make sense
sudo mv chkrootkit-0.52 /usr/local/chkrootkit
sudo ln -s | [
"Prepare",
"chkrootkit",
"binary",
"$",
"tar",
"xzvf",
"chkrootkit",
".",
"tar",
".",
"gz",
"$",
"cd",
"chkrootkit",
"-",
"0",
".",
"52",
"$",
"make",
"sense",
"sudo",
"mv",
"chkrootkit",
"-",
"0",
".",
"52",
"/",
"usr",
"/",
"local",
"/",
"chkrootki... | train | https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/chkrootkit.py#L46-L70 |
fstab50/metal | metal/chkrootkit.py | download | def download(objects):
"""
Retrieve remote file object
"""
def exists(object):
if os.path.exists(TMPDIR + '/' + filename):
return True
else:
msg = 'File object %s failed to download to %s. Exit' % (filename, TMPDIR)
logger.warning(msg)
stdo... | python | def download(objects):
"""
Retrieve remote file object
"""
def exists(object):
if os.path.exists(TMPDIR + '/' + filename):
return True
else:
msg = 'File object %s failed to download to %s. Exit' % (filename, TMPDIR)
logger.warning(msg)
stdo... | [
"def",
"download",
"(",
"objects",
")",
":",
"def",
"exists",
"(",
"object",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"TMPDIR",
"+",
"'/'",
"+",
"filename",
")",
":",
"return",
"True",
"else",
":",
"msg",
"=",
"'File object %s failed to d... | Retrieve remote file object | [
"Retrieve",
"remote",
"file",
"object"
] | train | https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/chkrootkit.py#L73-L96 |
fstab50/metal | metal/chkrootkit.py | valid_checksum | def valid_checksum(file, hash_file):
"""
Summary:
Validate file checksum using md5 hash
Args:
file: file object to verify integrity
hash_file: md5 reference checksum file
Returns:
Valid (True) | False, TYPE: bool
"""
bits = 4096
# calc md5 hash
hash_md5 =... | python | def valid_checksum(file, hash_file):
"""
Summary:
Validate file checksum using md5 hash
Args:
file: file object to verify integrity
hash_file: md5 reference checksum file
Returns:
Valid (True) | False, TYPE: bool
"""
bits = 4096
# calc md5 hash
hash_md5 =... | [
"def",
"valid_checksum",
"(",
"file",
",",
"hash_file",
")",
":",
"bits",
"=",
"4096",
"# calc md5 hash",
"hash_md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"file",
",",
"\"rb\"",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"iter",
... | Summary:
Validate file checksum using md5 hash
Args:
file: file object to verify integrity
hash_file: md5 reference checksum file
Returns:
Valid (True) | False, TYPE: bool | [
"Summary",
":",
"Validate",
"file",
"checksum",
"using",
"md5",
"hash",
"Args",
":",
"file",
":",
"file",
"object",
"to",
"verify",
"integrity",
"hash_file",
":",
"md5",
"reference",
"checksum",
"file",
"Returns",
":",
"Valid",
"(",
"True",
")",
"|",
"Fals... | train | https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/chkrootkit.py#L99-L123 |
fstab50/metal | metal/chkrootkit.py | precheck | def precheck():
"""
Pre-run dependency check
"""
binaries = ['make']
for bin in binaries:
if not which(bin):
msg = 'Dependency fail -- Unable to locate rquired binary: '
stdout_message('%s: %s' % (msg, ACCENT + bin + RESET))
return False
elif not r... | python | def precheck():
"""
Pre-run dependency check
"""
binaries = ['make']
for bin in binaries:
if not which(bin):
msg = 'Dependency fail -- Unable to locate rquired binary: '
stdout_message('%s: %s' % (msg, ACCENT + bin + RESET))
return False
elif not r... | [
"def",
"precheck",
"(",
")",
":",
"binaries",
"=",
"[",
"'make'",
"]",
"for",
"bin",
"in",
"binaries",
":",
"if",
"not",
"which",
"(",
"bin",
")",
":",
"msg",
"=",
"'Dependency fail -- Unable to locate rquired binary: '",
"stdout_message",
"(",
"'%s: %s'",
"%"... | Pre-run dependency check | [
"Pre",
"-",
"run",
"dependency",
"check"
] | train | https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/chkrootkit.py#L189-L201 |
knagra/farnsworth | workshift/views.py | add_workshift_context | def add_workshift_context(request):
""" Add workshift variables to all dictionaries passed to templates. """
if not request.user.is_authenticated():
return {}
if Semester.objects.count() < 1:
return {
"WORKSHIFT_ENABLED": False,
}
# Current semester is for navbar no... | python | def add_workshift_context(request):
""" Add workshift variables to all dictionaries passed to templates. """
if not request.user.is_authenticated():
return {}
if Semester.objects.count() < 1:
return {
"WORKSHIFT_ENABLED": False,
}
# Current semester is for navbar no... | [
"def",
"add_workshift_context",
"(",
"request",
")",
":",
"if",
"not",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"return",
"{",
"}",
"if",
"Semester",
".",
"objects",
".",
"count",
"(",
")",
"<",
"1",
":",
"return",
"{",
"\"WORKSH... | Add workshift variables to all dictionaries passed to templates. | [
"Add",
"workshift",
"variables",
"to",
"all",
"dictionaries",
"passed",
"to",
"templates",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L62-L192 |
knagra/farnsworth | workshift/views.py | start_semester_view | def start_semester_view(request):
"""
Initiates a semester"s worth of workshift, with the option to copy
workshift types from the previous semester.
"""
page_name = "Start Semester"
year, season = utils.get_year_season()
start_date, end_date = utils.get_semester_start_end(year, season)
... | python | def start_semester_view(request):
"""
Initiates a semester"s worth of workshift, with the option to copy
workshift types from the previous semester.
"""
page_name = "Start Semester"
year, season = utils.get_year_season()
start_date, end_date = utils.get_semester_start_end(year, season)
... | [
"def",
"start_semester_view",
"(",
"request",
")",
":",
"page_name",
"=",
"\"Start Semester\"",
"year",
",",
"season",
"=",
"utils",
".",
"get_year_season",
"(",
")",
"start_date",
",",
"end_date",
"=",
"utils",
".",
"get_semester_start_end",
"(",
"year",
",",
... | Initiates a semester"s worth of workshift, with the option to copy
workshift types from the previous semester. | [
"Initiates",
"a",
"semester",
"s",
"worth",
"of",
"workshift",
"with",
"the",
"option",
"to",
"copy",
"workshift",
"types",
"from",
"the",
"previous",
"semester",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L196-L249 |
knagra/farnsworth | workshift/views.py | semester_view | def semester_view(request, semester, profile=None):
"""
Displays a table of the workshifts for the week, shift assignments,
accumulated statistics (Down hours), reminders for any upcoming shifts, and
links to sign off on shifts. Also links to the rest of the workshift pages.
"""
template_dict = ... | python | def semester_view(request, semester, profile=None):
"""
Displays a table of the workshifts for the week, shift assignments,
accumulated statistics (Down hours), reminders for any upcoming shifts, and
links to sign off on shifts. Also links to the rest of the workshift pages.
"""
template_dict = ... | [
"def",
"semester_view",
"(",
"request",
",",
"semester",
",",
"profile",
"=",
"None",
")",
":",
"template_dict",
"=",
"{",
"}",
"template_dict",
"[",
"\"page_name\"",
"]",
"=",
"\"Workshift for {} {}\"",
".",
"format",
"(",
"semester",
".",
"get_season_display",... | Displays a table of the workshifts for the week, shift assignments,
accumulated statistics (Down hours), reminders for any upcoming shifts, and
links to sign off on shifts. Also links to the rest of the workshift pages. | [
"Displays",
"a",
"table",
"of",
"the",
"workshifts",
"for",
"the",
"week",
"shift",
"assignments",
"accumulated",
"statistics",
"(",
"Down",
"hours",
")",
"reminders",
"for",
"any",
"upcoming",
"shifts",
"and",
"links",
"to",
"sign",
"off",
"on",
"shifts",
"... | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L276-L400 |
knagra/farnsworth | workshift/views.py | _get_forms | def _get_forms(profile, instance, request, undo=False, prefix=""):
"""
Gets the forms for profile interacting with an instance of a shift. This
includes verify shift, mark shift as blown, sign in, and sign out.
"""
anonymous = profile is None and request.user.username == ANONYMOUS_USERNAME
if n... | python | def _get_forms(profile, instance, request, undo=False, prefix=""):
"""
Gets the forms for profile interacting with an instance of a shift. This
includes verify shift, mark shift as blown, sign in, and sign out.
"""
anonymous = profile is None and request.user.username == ANONYMOUS_USERNAME
if n... | [
"def",
"_get_forms",
"(",
"profile",
",",
"instance",
",",
"request",
",",
"undo",
"=",
"False",
",",
"prefix",
"=",
"\"\"",
")",
":",
"anonymous",
"=",
"profile",
"is",
"None",
"and",
"request",
".",
"user",
".",
"username",
"==",
"ANONYMOUS_USERNAME",
... | Gets the forms for profile interacting with an instance of a shift. This
includes verify shift, mark shift as blown, sign in, and sign out. | [
"Gets",
"the",
"forms",
"for",
"profile",
"interacting",
"with",
"an",
"instance",
"of",
"a",
"shift",
".",
"This",
"includes",
"verify",
"shift",
"mark",
"shift",
"as",
"blown",
"sign",
"in",
"and",
"sign",
"out",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L424-L537 |
knagra/farnsworth | workshift/views.py | _is_preferred | def _is_preferred(instance, profile):
"""
Check if a user has marked an instance's workshift type as preferred.
"""
if not instance.weekly_workshift:
return False
if profile and profile.ratings.filter(
workshift_type=instance.weekly_workshift.workshift_type,
rating=Wo... | python | def _is_preferred(instance, profile):
"""
Check if a user has marked an instance's workshift type as preferred.
"""
if not instance.weekly_workshift:
return False
if profile and profile.ratings.filter(
workshift_type=instance.weekly_workshift.workshift_type,
rating=Wo... | [
"def",
"_is_preferred",
"(",
"instance",
",",
"profile",
")",
":",
"if",
"not",
"instance",
".",
"weekly_workshift",
":",
"return",
"False",
"if",
"profile",
"and",
"profile",
".",
"ratings",
".",
"filter",
"(",
"workshift_type",
"=",
"instance",
".",
"weekl... | Check if a user has marked an instance's workshift type as preferred. | [
"Check",
"if",
"a",
"user",
"has",
"marked",
"an",
"instance",
"s",
"workshift",
"type",
"as",
"preferred",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L540-L551 |
knagra/farnsworth | workshift/views.py | profile_view | def profile_view(request, semester, targetUsername, profile=None):
"""
Show the user their workshift history for the current semester as well as
upcoming shifts.
"""
wprofile = get_object_or_404(
WorkshiftProfile,
user__username=targetUsername,
semester=semester
)
if ... | python | def profile_view(request, semester, targetUsername, profile=None):
"""
Show the user their workshift history for the current semester as well as
upcoming shifts.
"""
wprofile = get_object_or_404(
WorkshiftProfile,
user__username=targetUsername,
semester=semester
)
if ... | [
"def",
"profile_view",
"(",
"request",
",",
"semester",
",",
"targetUsername",
",",
"profile",
"=",
"None",
")",
":",
"wprofile",
"=",
"get_object_or_404",
"(",
"WorkshiftProfile",
",",
"user__username",
"=",
"targetUsername",
",",
"semester",
"=",
"semester",
"... | Show the user their workshift history for the current semester as well as
upcoming shifts. | [
"Show",
"the",
"user",
"their",
"workshift",
"history",
"for",
"the",
"current",
"semester",
"as",
"well",
"as",
"upcoming",
"shifts",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L651-L703 |
knagra/farnsworth | workshift/views.py | preferences_view | def preferences_view(request, semester, targetUsername, profile=None):
"""
Show the user their preferences for the given semester.
"""
# TODO: Change template to show descriptions in tooltip / ajax show box?
wprofile = get_object_or_404(
WorkshiftProfile,
user__username=targetUsernam... | python | def preferences_view(request, semester, targetUsername, profile=None):
"""
Show the user their preferences for the given semester.
"""
# TODO: Change template to show descriptions in tooltip / ajax show box?
wprofile = get_object_or_404(
WorkshiftProfile,
user__username=targetUsernam... | [
"def",
"preferences_view",
"(",
"request",
",",
"semester",
",",
"targetUsername",
",",
"profile",
"=",
"None",
")",
":",
"# TODO: Change template to show descriptions in tooltip / ajax show box?",
"wprofile",
"=",
"get_object_or_404",
"(",
"WorkshiftProfile",
",",
"user__u... | Show the user their preferences for the given semester. | [
"Show",
"the",
"user",
"their",
"preferences",
"for",
"the",
"given",
"semester",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L707-L784 |
knagra/farnsworth | workshift/views.py | manage_view | def manage_view(request, semester, profile=None):
"""
View all members' preferences. This view also includes forms to create an
entire semester's worth of weekly workshifts.
"""
page_name = "Manage Workshift"
pools = WorkshiftPool.objects.filter(semester=semester)
full_management = utils.can... | python | def manage_view(request, semester, profile=None):
"""
View all members' preferences. This view also includes forms to create an
entire semester's worth of weekly workshifts.
"""
page_name = "Manage Workshift"
pools = WorkshiftPool.objects.filter(semester=semester)
full_management = utils.can... | [
"def",
"manage_view",
"(",
"request",
",",
"semester",
",",
"profile",
"=",
"None",
")",
":",
"page_name",
"=",
"\"Manage Workshift\"",
"pools",
"=",
"WorkshiftPool",
".",
"objects",
".",
"filter",
"(",
"semester",
"=",
"semester",
")",
"full_management",
"=",... | View all members' preferences. This view also includes forms to create an
entire semester's worth of weekly workshifts. | [
"View",
"all",
"members",
"preferences",
".",
"This",
"view",
"also",
"includes",
"forms",
"to",
"create",
"an",
"entire",
"semester",
"s",
"worth",
"of",
"weekly",
"workshifts",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L809-L889 |
knagra/farnsworth | workshift/views.py | assign_shifts_view | def assign_shifts_view(request, semester):
"""
View all members' preferences. This view also includes forms to create an
entire semester's worth of weekly workshifts.
"""
page_name = "Assign Shifts"
auto_assign_shifts_form = None
random_assign_instances_form = None
clear_assign_form = N... | python | def assign_shifts_view(request, semester):
"""
View all members' preferences. This view also includes forms to create an
entire semester's worth of weekly workshifts.
"""
page_name = "Assign Shifts"
auto_assign_shifts_form = None
random_assign_instances_form = None
clear_assign_form = N... | [
"def",
"assign_shifts_view",
"(",
"request",
",",
"semester",
")",
":",
"page_name",
"=",
"\"Assign Shifts\"",
"auto_assign_shifts_form",
"=",
"None",
"random_assign_instances_form",
"=",
"None",
"clear_assign_form",
"=",
"None",
"if",
"WorkshiftPool",
".",
"objects",
... | View all members' preferences. This view also includes forms to create an
entire semester's worth of weekly workshifts. | [
"View",
"all",
"members",
"preferences",
".",
"This",
"view",
"also",
"includes",
"forms",
"to",
"create",
"an",
"entire",
"semester",
"s",
"worth",
"of",
"weekly",
"workshifts",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L894-L1020 |
knagra/farnsworth | workshift/views.py | adjust_hours_view | def adjust_hours_view(request, semester):
"""
Adjust members' workshift hours requirements.
"""
page_name = "Adjust Hours"
pools = WorkshiftPool.objects.filter(semester=semester).order_by(
"-is_primary", "title",
)
workshifters = WorkshiftProfile.objects.filter(semester=semester)
... | python | def adjust_hours_view(request, semester):
"""
Adjust members' workshift hours requirements.
"""
page_name = "Adjust Hours"
pools = WorkshiftPool.objects.filter(semester=semester).order_by(
"-is_primary", "title",
)
workshifters = WorkshiftProfile.objects.filter(semester=semester)
... | [
"def",
"adjust_hours_view",
"(",
"request",
",",
"semester",
")",
":",
"page_name",
"=",
"\"Adjust Hours\"",
"pools",
"=",
"WorkshiftPool",
".",
"objects",
".",
"filter",
"(",
"semester",
"=",
"semester",
")",
".",
"order_by",
"(",
"\"-is_primary\"",
",",
"\"t... | Adjust members' workshift hours requirements. | [
"Adjust",
"members",
"workshift",
"hours",
"requirements",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1025-L1069 |
knagra/farnsworth | workshift/views.py | add_workshifter_view | def add_workshifter_view(request, semester):
"""
Add a new member workshift profile, for people who join mid-semester.
"""
page_name = "Add Workshifter"
existing = [
i.user.pk for i in WorkshiftProfile.objects.filter(semester=semester)
]
users = User.objects.exclude(
Q(pk__i... | python | def add_workshifter_view(request, semester):
"""
Add a new member workshift profile, for people who join mid-semester.
"""
page_name = "Add Workshifter"
existing = [
i.user.pk for i in WorkshiftProfile.objects.filter(semester=semester)
]
users = User.objects.exclude(
Q(pk__i... | [
"def",
"add_workshifter_view",
"(",
"request",
",",
"semester",
")",
":",
"page_name",
"=",
"\"Add Workshifter\"",
"existing",
"=",
"[",
"i",
".",
"user",
".",
"pk",
"for",
"i",
"in",
"WorkshiftProfile",
".",
"objects",
".",
"filter",
"(",
"semester",
"=",
... | Add a new member workshift profile, for people who join mid-semester. | [
"Add",
"a",
"new",
"member",
"workshift",
"profile",
"for",
"people",
"who",
"join",
"mid",
"-",
"semester",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1074-L1116 |
knagra/farnsworth | workshift/views.py | add_pool_view | def add_pool_view(request, semester):
"""
View for the workshift manager to create new workshift pools (i.e. HI
Hours).
"""
page_name = "Add Workshift Pool"
add_pool_form = PoolForm(
data=request.POST or None,
semester=semester,
full_management=True,
)
if add_pool... | python | def add_pool_view(request, semester):
"""
View for the workshift manager to create new workshift pools (i.e. HI
Hours).
"""
page_name = "Add Workshift Pool"
add_pool_form = PoolForm(
data=request.POST or None,
semester=semester,
full_management=True,
)
if add_pool... | [
"def",
"add_pool_view",
"(",
"request",
",",
"semester",
")",
":",
"page_name",
"=",
"\"Add Workshift Pool\"",
"add_pool_form",
"=",
"PoolForm",
"(",
"data",
"=",
"request",
".",
"POST",
"or",
"None",
",",
"semester",
"=",
"semester",
",",
"full_management",
"... | View for the workshift manager to create new workshift pools (i.e. HI
Hours). | [
"View",
"for",
"the",
"workshift",
"manager",
"to",
"create",
"new",
"workshift",
"pools",
"(",
"i",
".",
"e",
".",
"HI",
"Hours",
")",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1121-L1146 |
knagra/farnsworth | workshift/views.py | fill_shifts_view | def fill_shifts_view(request, semester):
"""
Allows managers to quickly fill in the default workshifts for a few given
workshift pools.
"""
page_name = "Fill Shifts"
fill_regular_shifts_form = None
fill_social_shifts_form = None
fill_humor_shifts_form = None
fill_bathroom_shifts_for... | python | def fill_shifts_view(request, semester):
"""
Allows managers to quickly fill in the default workshifts for a few given
workshift pools.
"""
page_name = "Fill Shifts"
fill_regular_shifts_form = None
fill_social_shifts_form = None
fill_humor_shifts_form = None
fill_bathroom_shifts_for... | [
"def",
"fill_shifts_view",
"(",
"request",
",",
"semester",
")",
":",
"page_name",
"=",
"\"Fill Shifts\"",
"fill_regular_shifts_form",
"=",
"None",
"fill_social_shifts_form",
"=",
"None",
"fill_humor_shifts_form",
"=",
"None",
"fill_bathroom_shifts_form",
"=",
"None",
"... | Allows managers to quickly fill in the default workshifts for a few given
workshift pools. | [
"Allows",
"managers",
"to",
"quickly",
"fill",
"in",
"the",
"default",
"workshifts",
"for",
"a",
"few",
"given",
"workshift",
"pools",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1151-L1228 |
knagra/farnsworth | workshift/views.py | add_shift_view | def add_shift_view(request, semester):
"""
View for the workshift manager to create new types of workshifts.
"""
page_name = "Add Workshift"
any_management = utils.can_manage(request.user, semester, any_pool=True)
if not any_management:
messages.add_message(
request,
... | python | def add_shift_view(request, semester):
"""
View for the workshift manager to create new types of workshifts.
"""
page_name = "Add Workshift"
any_management = utils.can_manage(request.user, semester, any_pool=True)
if not any_management:
messages.add_message(
request,
... | [
"def",
"add_shift_view",
"(",
"request",
",",
"semester",
")",
":",
"page_name",
"=",
"\"Add Workshift\"",
"any_management",
"=",
"utils",
".",
"can_manage",
"(",
"request",
".",
"user",
",",
"semester",
",",
"any_pool",
"=",
"True",
")",
"if",
"not",
"any_m... | View for the workshift manager to create new types of workshifts. | [
"View",
"for",
"the",
"workshift",
"manager",
"to",
"create",
"new",
"types",
"of",
"workshifts",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1233-L1292 |
knagra/farnsworth | workshift/views.py | shift_view | def shift_view(request, semester, pk, profile=None):
"""
View the details of a particular RegularWorkshift.
"""
shift = get_object_or_404(RegularWorkshift, pk=pk)
page_name = shift.workshift_type.title
if shift.is_manager_shift:
president = Manager.objects.filter(
incumbent_... | python | def shift_view(request, semester, pk, profile=None):
"""
View the details of a particular RegularWorkshift.
"""
shift = get_object_or_404(RegularWorkshift, pk=pk)
page_name = shift.workshift_type.title
if shift.is_manager_shift:
president = Manager.objects.filter(
incumbent_... | [
"def",
"shift_view",
"(",
"request",
",",
"semester",
",",
"pk",
",",
"profile",
"=",
"None",
")",
":",
"shift",
"=",
"get_object_or_404",
"(",
"RegularWorkshift",
",",
"pk",
"=",
"pk",
")",
"page_name",
"=",
"shift",
".",
"workshift_type",
".",
"title",
... | View the details of a particular RegularWorkshift. | [
"View",
"the",
"details",
"of",
"a",
"particular",
"RegularWorkshift",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1440-L1487 |
knagra/farnsworth | workshift/views.py | edit_shift_view | def edit_shift_view(request, semester, pk, profile=None):
"""
View for a manager to edit the details of a particular RegularWorkshift.
"""
shift = get_object_or_404(RegularWorkshift, pk=pk)
if shift.is_manager_shift:
# XXX: Bad way of doing this, we should make manager_shift point to
... | python | def edit_shift_view(request, semester, pk, profile=None):
"""
View for a manager to edit the details of a particular RegularWorkshift.
"""
shift = get_object_or_404(RegularWorkshift, pk=pk)
if shift.is_manager_shift:
# XXX: Bad way of doing this, we should make manager_shift point to
... | [
"def",
"edit_shift_view",
"(",
"request",
",",
"semester",
",",
"pk",
",",
"profile",
"=",
"None",
")",
":",
"shift",
"=",
"get_object_or_404",
"(",
"RegularWorkshift",
",",
"pk",
"=",
"pk",
")",
"if",
"shift",
".",
"is_manager_shift",
":",
"# XXX: Bad way o... | View for a manager to edit the details of a particular RegularWorkshift. | [
"View",
"for",
"a",
"manager",
"to",
"edit",
"the",
"details",
"of",
"a",
"particular",
"RegularWorkshift",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1491-L1538 |
knagra/farnsworth | workshift/views.py | instance_view | def instance_view(request, semester, pk, profile=None):
"""
View the details of a particular WorkshiftInstance.
"""
instance = get_object_or_404(WorkshiftInstance, pk=pk)
page_name = instance.title
management = utils.can_manage(
request.user,
semester=semester,
pool=insta... | python | def instance_view(request, semester, pk, profile=None):
"""
View the details of a particular WorkshiftInstance.
"""
instance = get_object_or_404(WorkshiftInstance, pk=pk)
page_name = instance.title
management = utils.can_manage(
request.user,
semester=semester,
pool=insta... | [
"def",
"instance_view",
"(",
"request",
",",
"semester",
",",
"pk",
",",
"profile",
"=",
"None",
")",
":",
"instance",
"=",
"get_object_or_404",
"(",
"WorkshiftInstance",
",",
"pk",
"=",
"pk",
")",
"page_name",
"=",
"instance",
".",
"title",
"management",
... | View the details of a particular WorkshiftInstance. | [
"View",
"the",
"details",
"of",
"a",
"particular",
"WorkshiftInstance",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1542-L1609 |
knagra/farnsworth | workshift/views.py | edit_instance_view | def edit_instance_view(request, semester, pk, profile=None):
"""
View for a manager to edit the details of a particular WorkshiftInstance.
"""
instance = get_object_or_404(WorkshiftInstance, pk=pk)
if instance.weekly_workshift and instance.weekly_workshift.is_manager_shift:
president = Mana... | python | def edit_instance_view(request, semester, pk, profile=None):
"""
View for a manager to edit the details of a particular WorkshiftInstance.
"""
instance = get_object_or_404(WorkshiftInstance, pk=pk)
if instance.weekly_workshift and instance.weekly_workshift.is_manager_shift:
president = Mana... | [
"def",
"edit_instance_view",
"(",
"request",
",",
"semester",
",",
"pk",
",",
"profile",
"=",
"None",
")",
":",
"instance",
"=",
"get_object_or_404",
"(",
"WorkshiftInstance",
",",
"pk",
"=",
"pk",
")",
"if",
"instance",
".",
"weekly_workshift",
"and",
"inst... | View for a manager to edit the details of a particular WorkshiftInstance. | [
"View",
"for",
"a",
"manager",
"to",
"edit",
"the",
"details",
"of",
"a",
"particular",
"WorkshiftInstance",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1613-L1659 |
knagra/farnsworth | workshift/views.py | list_types_view | def list_types_view(request, semester, profile=None):
"""
View the details of a particular WorkshiftType.
"""
page_name = "Workshift Types"
full_management = utils.can_manage(request.user, semester)
any_management = utils.can_manage(request.user, semester, any_pool=True)
types = WorkshiftTy... | python | def list_types_view(request, semester, profile=None):
"""
View the details of a particular WorkshiftType.
"""
page_name = "Workshift Types"
full_management = utils.can_manage(request.user, semester)
any_management = utils.can_manage(request.user, semester, any_pool=True)
types = WorkshiftTy... | [
"def",
"list_types_view",
"(",
"request",
",",
"semester",
",",
"profile",
"=",
"None",
")",
":",
"page_name",
"=",
"\"Workshift Types\"",
"full_management",
"=",
"utils",
".",
"can_manage",
"(",
"request",
".",
"user",
",",
"semester",
")",
"any_management",
... | View the details of a particular WorkshiftType. | [
"View",
"the",
"details",
"of",
"a",
"particular",
"WorkshiftType",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1663-L1695 |
knagra/farnsworth | workshift/views.py | type_view | def type_view(request, semester, pk, profile=None):
"""
View the details of a particular WorkshiftType.
"""
any_management = utils.can_manage(request.user, semester, any_pool=True)
wtype = get_object_or_404(WorkshiftType, pk=pk)
page_name = wtype.title
regular_shifts = RegularWorkshift.objec... | python | def type_view(request, semester, pk, profile=None):
"""
View the details of a particular WorkshiftType.
"""
any_management = utils.can_manage(request.user, semester, any_pool=True)
wtype = get_object_or_404(WorkshiftType, pk=pk)
page_name = wtype.title
regular_shifts = RegularWorkshift.objec... | [
"def",
"type_view",
"(",
"request",
",",
"semester",
",",
"pk",
",",
"profile",
"=",
"None",
")",
":",
"any_management",
"=",
"utils",
".",
"can_manage",
"(",
"request",
".",
"user",
",",
"semester",
",",
"any_pool",
"=",
"True",
")",
"wtype",
"=",
"ge... | View the details of a particular WorkshiftType. | [
"View",
"the",
"details",
"of",
"a",
"particular",
"WorkshiftType",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1699-L1715 |
knagra/farnsworth | workshift/views.py | edit_type_view | def edit_type_view(request, semester, pk, profile=None):
"""
View for a manager to edit the details of a particular WorkshiftType.
"""
wtype = get_object_or_404(WorkshiftType, pk=pk)
full_management = utils.can_manage(request.user, semester)
any_management = utils.can_manage(request.user, semest... | python | def edit_type_view(request, semester, pk, profile=None):
"""
View for a manager to edit the details of a particular WorkshiftType.
"""
wtype = get_object_or_404(WorkshiftType, pk=pk)
full_management = utils.can_manage(request.user, semester)
any_management = utils.can_manage(request.user, semest... | [
"def",
"edit_type_view",
"(",
"request",
",",
"semester",
",",
"pk",
",",
"profile",
"=",
"None",
")",
":",
"wtype",
"=",
"get_object_or_404",
"(",
"WorkshiftType",
",",
"pk",
"=",
"pk",
")",
"full_management",
"=",
"utils",
".",
"can_manage",
"(",
"reques... | View for a manager to edit the details of a particular WorkshiftType. | [
"View",
"for",
"a",
"manager",
"to",
"edit",
"the",
"details",
"of",
"a",
"particular",
"WorkshiftType",
"."
] | train | https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/workshift/views.py#L1719-L1783 |
xtrementl/focus | focus/environment/__init__.py | _import_modules | def _import_modules(dir_path):
""" Attempts to import modules in the specified directory path.
`dir_path`
Base directory path to attempt to import modules.
"""
def _import_module(module):
""" Imports the specified module.
"""
# already loaded, skip
... | python | def _import_modules(dir_path):
""" Attempts to import modules in the specified directory path.
`dir_path`
Base directory path to attempt to import modules.
"""
def _import_module(module):
""" Imports the specified module.
"""
# already loaded, skip
... | [
"def",
"_import_modules",
"(",
"dir_path",
")",
":",
"def",
"_import_module",
"(",
"module",
")",
":",
"\"\"\" Imports the specified module.\n \"\"\"",
"# already loaded, skip",
"if",
"module",
"in",
"mods_loaded",
":",
"return",
"False",
"__import__",
"(",
"... | Attempts to import modules in the specified directory path.
`dir_path`
Base directory path to attempt to import modules. | [
"Attempts",
"to",
"import",
"modules",
"in",
"the",
"specified",
"directory",
"path",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/__init__.py#L22-L62 |
xtrementl/focus | focus/environment/__init__.py | Environment._setup_directories | def _setup_directories(self):
""" Creates data directory structure.
* Raises a ``DirectorySetupFail`` exception if error occurs
while creating directories.
"""
dirs = [self._data_dir]
dirs += [os.path.join(self._data_dir, name) for name
in ... | python | def _setup_directories(self):
""" Creates data directory structure.
* Raises a ``DirectorySetupFail`` exception if error occurs
while creating directories.
"""
dirs = [self._data_dir]
dirs += [os.path.join(self._data_dir, name) for name
in ... | [
"def",
"_setup_directories",
"(",
"self",
")",
":",
"dirs",
"=",
"[",
"self",
".",
"_data_dir",
"]",
"dirs",
"+=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_data_dir",
",",
"name",
")",
"for",
"name",
"in",
"self",
".",
"DATA_SUBDIRS",... | Creates data directory structure.
* Raises a ``DirectorySetupFail`` exception if error occurs
while creating directories. | [
"Creates",
"data",
"directory",
"structure",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/__init__.py#L104-L123 |
xtrementl/focus | focus/environment/__init__.py | Environment._setup_task | def _setup_task(self, load):
""" Sets up the ``Task`` object and loads active file for task.
`load`
Set to ``True`` to load task after setup.
"""
if not self._task:
self._task = Task(self._data_dir)
if load:
self._task.load() | python | def _setup_task(self, load):
""" Sets up the ``Task`` object and loads active file for task.
`load`
Set to ``True`` to load task after setup.
"""
if not self._task:
self._task = Task(self._data_dir)
if load:
self._task.load() | [
"def",
"_setup_task",
"(",
"self",
",",
"load",
")",
":",
"if",
"not",
"self",
".",
"_task",
":",
"self",
".",
"_task",
"=",
"Task",
"(",
"self",
".",
"_data_dir",
")",
"if",
"load",
":",
"self",
".",
"_task",
".",
"load",
"(",
")"
] | Sets up the ``Task`` object and loads active file for task.
`load`
Set to ``True`` to load task after setup. | [
"Sets",
"up",
"the",
"Task",
"object",
"and",
"loads",
"active",
"file",
"for",
"task",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/__init__.py#L125-L136 |
xtrementl/focus | focus/environment/__init__.py | Environment._load_plugins | def _load_plugins(self):
""" Attempts to load plugin modules according to the order of available
plugin directories.
"""
# import base plugin modules
try:
__import__('focus.plugin.modules')
#import focus.plugin.modules
except ImportError a... | python | def _load_plugins(self):
""" Attempts to load plugin modules according to the order of available
plugin directories.
"""
# import base plugin modules
try:
__import__('focus.plugin.modules')
#import focus.plugin.modules
except ImportError a... | [
"def",
"_load_plugins",
"(",
"self",
")",
":",
"# import base plugin modules",
"try",
":",
"__import__",
"(",
"'focus.plugin.modules'",
")",
"#import focus.plugin.modules",
"except",
"ImportError",
"as",
"exc",
":",
"raise",
"errors",
".",
"PluginImport",
"(",
"unicod... | Attempts to load plugin modules according to the order of available
plugin directories. | [
"Attempts",
"to",
"load",
"plugin",
"modules",
"according",
"to",
"the",
"order",
"of",
"available",
"plugin",
"directories",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/__init__.py#L138-L156 |
xtrementl/focus | focus/environment/__init__.py | Environment.load | def load(self):
""" Loads in resources needed for this environment, including loading a
new or existing task, establishing directory structures, and
importing plugin modules.
"""
self._setup_directories()
self._load_plugins()
self._setup_task(load=Tru... | python | def load(self):
""" Loads in resources needed for this environment, including loading a
new or existing task, establishing directory structures, and
importing plugin modules.
"""
self._setup_directories()
self._load_plugins()
self._setup_task(load=Tru... | [
"def",
"load",
"(",
"self",
")",
":",
"self",
".",
"_setup_directories",
"(",
")",
"self",
".",
"_load_plugins",
"(",
")",
"self",
".",
"_setup_task",
"(",
"load",
"=",
"True",
")",
"self",
".",
"_loaded",
"=",
"True"
] | Loads in resources needed for this environment, including loading a
new or existing task, establishing directory structures, and
importing plugin modules. | [
"Loads",
"in",
"resources",
"needed",
"for",
"this",
"environment",
"including",
"loading",
"a",
"new",
"or",
"existing",
"task",
"establishing",
"directory",
"structures",
"and",
"importing",
"plugin",
"modules",
"."
] | train | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/__init__.py#L158-L167 |
zakdoek/django-simple-resizer | simple_resizer/templatetags/simple_resizer.py | resize | def resize(image, width=None, height=None, crop=False, namespace="resized"):
"""
Returns the url of the resized image
"""
return resize_lazy(image=image, width=width, height=height, crop=crop,
namespace=namespace, as_url=True) | python | def resize(image, width=None, height=None, crop=False, namespace="resized"):
"""
Returns the url of the resized image
"""
return resize_lazy(image=image, width=width, height=height, crop=crop,
namespace=namespace, as_url=True) | [
"def",
"resize",
"(",
"image",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"crop",
"=",
"False",
",",
"namespace",
"=",
"\"resized\"",
")",
":",
"return",
"resize_lazy",
"(",
"image",
"=",
"image",
",",
"width",
"=",
"width",
",",
"he... | Returns the url of the resized image | [
"Returns",
"the",
"url",
"of",
"the",
"resized",
"image"
] | train | https://github.com/zakdoek/django-simple-resizer/blob/5614eb1717948c65d179c3d1567439a8c90a4d44/simple_resizer/templatetags/simple_resizer.py#L13-L18 |
zakdoek/django-simple-resizer | simple_resizer/templatetags/simple_resizer.py | conditional_resize | def conditional_resize(image, ratio, width=None, height=None, upcrop=True,
namespace="resized"):
"""
Crop the image based on a ratio
If upcrop is true, crops the images that have a higher ratio than the given
ratio, if false crops the images that have a lower ratio
"""
as... | python | def conditional_resize(image, ratio, width=None, height=None, upcrop=True,
namespace="resized"):
"""
Crop the image based on a ratio
If upcrop is true, crops the images that have a higher ratio than the given
ratio, if false crops the images that have a lower ratio
"""
as... | [
"def",
"conditional_resize",
"(",
"image",
",",
"ratio",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"upcrop",
"=",
"True",
",",
"namespace",
"=",
"\"resized\"",
")",
":",
"aspect",
"=",
"float",
"(",
"image",
".",
"width",
")",
"/",
... | Crop the image based on a ratio
If upcrop is true, crops the images that have a higher ratio than the given
ratio, if false crops the images that have a lower ratio | [
"Crop",
"the",
"image",
"based",
"on",
"a",
"ratio"
] | train | https://github.com/zakdoek/django-simple-resizer/blob/5614eb1717948c65d179c3d1567439a8c90a4d44/simple_resizer/templatetags/simple_resizer.py#L23-L38 |
thomasballinger/trellocardupdate | trellocardupdate/cli.py | choose | def choose(s, possibilities, threshold=.6):
"""
Returns the closest match to string s if exceeds threshold, else returns None
"""
if not possibilities: return None
if s in possibilities: return s
if s == '': return None
startswith = [x for x in possibilities if x.lower().startswith(s.lower()... | python | def choose(s, possibilities, threshold=.6):
"""
Returns the closest match to string s if exceeds threshold, else returns None
"""
if not possibilities: return None
if s in possibilities: return s
if s == '': return None
startswith = [x for x in possibilities if x.lower().startswith(s.lower()... | [
"def",
"choose",
"(",
"s",
",",
"possibilities",
",",
"threshold",
"=",
".6",
")",
":",
"if",
"not",
"possibilities",
":",
"return",
"None",
"if",
"s",
"in",
"possibilities",
":",
"return",
"s",
"if",
"s",
"==",
"''",
":",
"return",
"None",
"startswith... | Returns the closest match to string s if exceeds threshold, else returns None | [
"Returns",
"the",
"closest",
"match",
"to",
"string",
"s",
"if",
"exceeds",
"threshold",
"else",
"returns",
"None"
] | train | https://github.com/thomasballinger/trellocardupdate/blob/16a648fa15efef144c07cd56fcdb1d8920fac889/trellocardupdate/cli.py#L17-L32 |
ryanjdillon/pyotelem | pyotelem/dsp.py | normalized | def normalized(a, axis=-1, order=2):
'''Return normalized vector for arbitrary axis
Args
----
a: ndarray (n,3)
Tri-axial vector data
axis: int
Axis index to overwhich to normalize
order: int
Order of nomalization to calculate
Notes
-----
This function was ad... | python | def normalized(a, axis=-1, order=2):
'''Return normalized vector for arbitrary axis
Args
----
a: ndarray (n,3)
Tri-axial vector data
axis: int
Axis index to overwhich to normalize
order: int
Order of nomalization to calculate
Notes
-----
This function was ad... | [
"def",
"normalized",
"(",
"a",
",",
"axis",
"=",
"-",
"1",
",",
"order",
"=",
"2",
")",
":",
"import",
"numpy",
"l2",
"=",
"numpy",
".",
"atleast_1d",
"(",
"numpy",
".",
"linalg",
".",
"norm",
"(",
"a",
",",
"order",
",",
"axis",
")",
")",
"l2"... | Return normalized vector for arbitrary axis
Args
----
a: ndarray (n,3)
Tri-axial vector data
axis: int
Axis index to overwhich to normalize
order: int
Order of nomalization to calculate
Notes
-----
This function was adapted from the following StackOverflow answe... | [
"Return",
"normalized",
"vector",
"for",
"arbitrary",
"axis"
] | train | https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/dsp.py#L2-L24 |
ryanjdillon/pyotelem | pyotelem/dsp.py | findzc | def findzc(x, thresh, t_max=None):
'''
Find cues to each zero-crossing in vector x.
To be accepted as a zero-crossing, the signal must pass from below
-thresh to above thresh, or vice versa, in no more than t_max samples.
Args
----
thresh: (float)
magnitude threshold for detecting ... | python | def findzc(x, thresh, t_max=None):
'''
Find cues to each zero-crossing in vector x.
To be accepted as a zero-crossing, the signal must pass from below
-thresh to above thresh, or vice versa, in no more than t_max samples.
Args
----
thresh: (float)
magnitude threshold for detecting ... | [
"def",
"findzc",
"(",
"x",
",",
"thresh",
",",
"t_max",
"=",
"None",
")",
":",
"import",
"numpy",
"# positive threshold: p (over) n (under)",
"pt_p",
"=",
"x",
">",
"thresh",
"pt_n",
"=",
"~",
"pt_p",
"# negative threshold: p (over) n (under)",
"nt_n",
"=",
"x",... | Find cues to each zero-crossing in vector x.
To be accepted as a zero-crossing, the signal must pass from below
-thresh to above thresh, or vice versa, in no more than t_max samples.
Args
----
thresh: (float)
magnitude threshold for detecting a zero-crossing.
t_max: (int)
maxim... | [
"Find",
"cues",
"to",
"each",
"zero",
"-",
"crossing",
"in",
"vector",
"x",
"."
] | train | https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/dsp.py#L27-L113 |
ryanjdillon/pyotelem | pyotelem/dsp.py | butter_filter | def butter_filter(cutoff, fs, order=5, btype='low'):
'''Create a digital butter fileter with cutoff frequency in Hz
Args
----
cutoff: float
Cutoff frequency where filter should separate signals
fs: float
sampling frequency
btype: str
Type of filter type to create. 'low' ... | python | def butter_filter(cutoff, fs, order=5, btype='low'):
'''Create a digital butter fileter with cutoff frequency in Hz
Args
----
cutoff: float
Cutoff frequency where filter should separate signals
fs: float
sampling frequency
btype: str
Type of filter type to create. 'low' ... | [
"def",
"butter_filter",
"(",
"cutoff",
",",
"fs",
",",
"order",
"=",
"5",
",",
"btype",
"=",
"'low'",
")",
":",
"import",
"scipy",
".",
"signal",
"nyq",
"=",
"0.5",
"*",
"fs",
"normal_cutoff",
"=",
"cutoff",
"/",
"nyq",
"b",
",",
"a",
"=",
"scipy",... | Create a digital butter fileter with cutoff frequency in Hz
Args
----
cutoff: float
Cutoff frequency where filter should separate signals
fs: float
sampling frequency
btype: str
Type of filter type to create. 'low' creates a low-frequency filter and
'high' creates a ... | [
"Create",
"a",
"digital",
"butter",
"fileter",
"with",
"cutoff",
"frequency",
"in",
"Hz"
] | train | https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/dsp.py#L116-L147 |
ryanjdillon/pyotelem | pyotelem/dsp.py | butter_apply | def butter_apply(b, a, data):
'''Apply filter with filtfilt to allign filtereted data with input
The filter is applied once forward and once backward to give it linear
phase, using Gustafsson's method to give the same length as the original
signal.
Args
----
b: ndarray
Numerator po... | python | def butter_apply(b, a, data):
'''Apply filter with filtfilt to allign filtereted data with input
The filter is applied once forward and once backward to give it linear
phase, using Gustafsson's method to give the same length as the original
signal.
Args
----
b: ndarray
Numerator po... | [
"def",
"butter_apply",
"(",
"b",
",",
"a",
",",
"data",
")",
":",
"import",
"scipy",
".",
"signal",
"return",
"scipy",
".",
"signal",
".",
"filtfilt",
"(",
"b",
",",
"a",
",",
"data",
",",
"method",
"=",
"'gust'",
")"
] | Apply filter with filtfilt to allign filtereted data with input
The filter is applied once forward and once backward to give it linear
phase, using Gustafsson's method to give the same length as the original
signal.
Args
----
b: ndarray
Numerator polynomials of the IIR butter filter
... | [
"Apply",
"filter",
"with",
"filtfilt",
"to",
"allign",
"filtereted",
"data",
"with",
"input"
] | train | https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/dsp.py#L150-L176 |
ryanjdillon/pyotelem | pyotelem/dsp.py | calc_PSD_welch | def calc_PSD_welch(x, fs, nperseg):
'''Caclulate power spectral density with Welch's method
Args
----
x: ndarray
sample array
fs: float
sampling frequency (1/dt)
Returns
-------
f_welch: ndarray
Discrete frequencies
S_xx_welch: ndarray
Estimated PSD ... | python | def calc_PSD_welch(x, fs, nperseg):
'''Caclulate power spectral density with Welch's method
Args
----
x: ndarray
sample array
fs: float
sampling frequency (1/dt)
Returns
-------
f_welch: ndarray
Discrete frequencies
S_xx_welch: ndarray
Estimated PSD ... | [
"def",
"calc_PSD_welch",
"(",
"x",
",",
"fs",
",",
"nperseg",
")",
":",
"import",
"numpy",
"import",
"scipy",
".",
"signal",
"# Code source and description of FFT, DFT, etc.",
"# http://stackoverflow.com/a/33251324/943773",
"dt",
"=",
"1",
"/",
"fs",
"N",
"=",
"len"... | Caclulate power spectral density with Welch's method
Args
----
x: ndarray
sample array
fs: float
sampling frequency (1/dt)
Returns
-------
f_welch: ndarray
Discrete frequencies
S_xx_welch: ndarray
Estimated PSD at discrete frequencies `f_welch`
P_wel... | [
"Caclulate",
"power",
"spectral",
"density",
"with",
"Welch",
"s",
"method"
] | train | https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/dsp.py#L179-L217 |
ryanjdillon/pyotelem | pyotelem/dsp.py | simple_peakfinder | def simple_peakfinder(x, y, delta):
'''Detect local maxima and minima in a vector
A point is considered a maximum peak if it has the maximal value, and was
preceded (to the left) by a value lower by `delta`.
Args
----
y: ndarray
array of values to find local maxima and minima in
de... | python | def simple_peakfinder(x, y, delta):
'''Detect local maxima and minima in a vector
A point is considered a maximum peak if it has the maximal value, and was
preceded (to the left) by a value lower by `delta`.
Args
----
y: ndarray
array of values to find local maxima and minima in
de... | [
"def",
"simple_peakfinder",
"(",
"x",
",",
"y",
",",
"delta",
")",
":",
"import",
"numpy",
"y",
"=",
"numpy",
".",
"asarray",
"(",
"y",
")",
"max_ind",
"=",
"list",
"(",
")",
"min_ind",
"=",
"list",
"(",
")",
"local_min",
"=",
"numpy",
".",
"inf",
... | Detect local maxima and minima in a vector
A point is considered a maximum peak if it has the maximal value, and was
preceded (to the left) by a value lower by `delta`.
Args
----
y: ndarray
array of values to find local maxima and minima in
delta: float
minimum change in `y` si... | [
"Detect",
"local",
"maxima",
"and",
"minima",
"in",
"a",
"vector"
] | train | https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/dsp.py#L220-L293 |
brews/carbonferret | carbonferret/core.py | find_near | def find_near(lat, lon, *, n=10, session=None):
"""Return n results for a given latitude and longitude"""
search_params = {'npoints': n, 'clat': lat, 'clon': lon,
'Columns[]': ['Subregion', 'Notes', 'CollectionYear',
'ReservoirAge', 'ReservoirErr', 'C14a... | python | def find_near(lat, lon, *, n=10, session=None):
"""Return n results for a given latitude and longitude"""
search_params = {'npoints': n, 'clat': lat, 'clon': lon,
'Columns[]': ['Subregion', 'Notes', 'CollectionYear',
'ReservoirAge', 'ReservoirErr', 'C14a... | [
"def",
"find_near",
"(",
"lat",
",",
"lon",
",",
"*",
",",
"n",
"=",
"10",
",",
"session",
"=",
"None",
")",
":",
"search_params",
"=",
"{",
"'npoints'",
":",
"n",
",",
"'clat'",
":",
"lat",
",",
"'clon'",
":",
"lon",
",",
"'Columns[]'",
":",
"["... | Return n results for a given latitude and longitude | [
"Return",
"n",
"results",
"for",
"a",
"given",
"latitude",
"and",
"longitude"
] | train | https://github.com/brews/carbonferret/blob/afbf901178b328bbc770129adc35c1403404b197/carbonferret/core.py#L5-L15 |
brews/carbonferret | carbonferret/core.py | _query_near | def _query_near(*, session=None, **kwargs):
"""Query marine database with given query string values and keys"""
url_endpoint = 'http://calib.org/marine/index.html'
if session is not None:
resp = session.get(url_endpoint, params=kwargs)
else:
with requests.Session() as s:
# Ne... | python | def _query_near(*, session=None, **kwargs):
"""Query marine database with given query string values and keys"""
url_endpoint = 'http://calib.org/marine/index.html'
if session is not None:
resp = session.get(url_endpoint, params=kwargs)
else:
with requests.Session() as s:
# Ne... | [
"def",
"_query_near",
"(",
"*",
",",
"session",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url_endpoint",
"=",
"'http://calib.org/marine/index.html'",
"if",
"session",
"is",
"not",
"None",
":",
"resp",
"=",
"session",
".",
"get",
"(",
"url_endpoint",
... | Query marine database with given query string values and keys | [
"Query",
"marine",
"database",
"with",
"given",
"query",
"string",
"values",
"and",
"keys"
] | train | https://github.com/brews/carbonferret/blob/afbf901178b328bbc770129adc35c1403404b197/carbonferret/core.py#L18-L28 |
klen/muffin-debugtoolbar | muffin_debugtoolbar/panels.py | DebugPanel.render_content | def render_content(self):
"""Render the panel's content."""
if not self.has_content:
return ""
template = self.template
if isinstance(self.template, str):
template = self.app.ps.jinja2.env.get_template(self.template)
context = self.render_vars()
co... | python | def render_content(self):
"""Render the panel's content."""
if not self.has_content:
return ""
template = self.template
if isinstance(self.template, str):
template = self.app.ps.jinja2.env.get_template(self.template)
context = self.render_vars()
co... | [
"def",
"render_content",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"has_content",
":",
"return",
"\"\"",
"template",
"=",
"self",
".",
"template",
"if",
"isinstance",
"(",
"self",
".",
"template",
",",
"str",
")",
":",
"template",
"=",
"self",
"... | Render the panel's content. | [
"Render",
"the",
"panel",
"s",
"content",
"."
] | train | https://github.com/klen/muffin-debugtoolbar/blob/b650b35fbe2035888f6bba5dac3073ef01c94dc6/muffin_debugtoolbar/panels.py#L57-L66 |
klen/muffin-debugtoolbar | muffin_debugtoolbar/panels.py | HeaderDebugPanel.process_response | def process_response(self, response):
"""Store response headers."""
self.response_headers = [(k, v) for k, v in sorted(response.headers.items())] | python | def process_response(self, response):
"""Store response headers."""
self.response_headers = [(k, v) for k, v in sorted(response.headers.items())] | [
"def",
"process_response",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"response_headers",
"=",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"response",
".",
"headers",
".",
"items",
"(",
")",
")",
"]"
] | Store response headers. | [
"Store",
"response",
"headers",
"."
] | train | https://github.com/klen/muffin-debugtoolbar/blob/b650b35fbe2035888f6bba5dac3073ef01c94dc6/muffin_debugtoolbar/panels.py#L88-L90 |
tbobm/devscripts | devscripts/devscripts.py | retry | def retry(exception_to_check, tries=5, delay=5, multiplier=2):
'''Tries to call the wrapped function again, after an incremental delay
:param exception_to_check: Exception(s) to check for, before retrying.
:type exception_to_check: Exception
:param tries: Number of time to retry before failling.
:t... | python | def retry(exception_to_check, tries=5, delay=5, multiplier=2):
'''Tries to call the wrapped function again, after an incremental delay
:param exception_to_check: Exception(s) to check for, before retrying.
:type exception_to_check: Exception
:param tries: Number of time to retry before failling.
:t... | [
"def",
"retry",
"(",
"exception_to_check",
",",
"tries",
"=",
"5",
",",
"delay",
"=",
"5",
",",
"multiplier",
"=",
"2",
")",
":",
"def",
"deco_retry",
"(",
"func",
")",
":",
"'''Creates the retry decorator'''",
"@",
"wraps",
"(",
"func",
")",
"def",
"fun... | Tries to call the wrapped function again, after an incremental delay
:param exception_to_check: Exception(s) to check for, before retrying.
:type exception_to_check: Exception
:param tries: Number of time to retry before failling.
:type tries: int
:param delay: time in second to sleep before retryi... | [
"Tries",
"to",
"call",
"the",
"wrapped",
"function",
"again",
"after",
"an",
"incremental",
"delay"
] | train | https://github.com/tbobm/devscripts/blob/beb23371ba80739afb5474766e8049ead3837925/devscripts/devscripts.py#L10-L49 |
eddiejessup/agaro | agaro/measure_utils.py | get_average_measure | def get_average_measure(dirname, measure_func, t_steady=None):
"""
Calculate a measure of a model in an output directory, averaged over
all times when the model is at steady-state.
Parameters
----------
dirname: str
Output directory
measure_func: function
Function which take... | python | def get_average_measure(dirname, measure_func, t_steady=None):
"""
Calculate a measure of a model in an output directory, averaged over
all times when the model is at steady-state.
Parameters
----------
dirname: str
Output directory
measure_func: function
Function which take... | [
"def",
"get_average_measure",
"(",
"dirname",
",",
"measure_func",
",",
"t_steady",
"=",
"None",
")",
":",
"if",
"t_steady",
"is",
"None",
":",
"meas",
",",
"meas_err",
"=",
"measure_func",
"(",
"get_recent_model",
"(",
"dirname",
")",
")",
"return",
"meas",... | Calculate a measure of a model in an output directory, averaged over
all times when the model is at steady-state.
Parameters
----------
dirname: str
Output directory
measure_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns the m... | [
"Calculate",
"a",
"measure",
"of",
"a",
"model",
"in",
"an",
"output",
"directory",
"averaged",
"over",
"all",
"times",
"when",
"the",
"model",
"is",
"at",
"steady",
"-",
"state",
"."
] | train | https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/measure_utils.py#L9-L42 |
eddiejessup/agaro | agaro/measure_utils.py | measures | def measures(dirnames, measure_func, t_steady=None):
"""Calculate a measure of a set of model output directories,
for a measure function which returns an associated uncertainty.
Parameters
----------
dirnames: list[str]
Model output directory paths.
measure_func: function
Functi... | python | def measures(dirnames, measure_func, t_steady=None):
"""Calculate a measure of a set of model output directories,
for a measure function which returns an associated uncertainty.
Parameters
----------
dirnames: list[str]
Model output directory paths.
measure_func: function
Functi... | [
"def",
"measures",
"(",
"dirnames",
",",
"measure_func",
",",
"t_steady",
"=",
"None",
")",
":",
"measures",
",",
"measure_errs",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"dirname",
"in",
"dirnames",
":",
"meas",
",",
"meas_err",
"=",
"get_average_measure",
... | Calculate a measure of a set of model output directories,
for a measure function which returns an associated uncertainty.
Parameters
----------
dirnames: list[str]
Model output directory paths.
measure_func: function
Function which takes a :class:`Model` instance as a single argumen... | [
"Calculate",
"a",
"measure",
"of",
"a",
"set",
"of",
"model",
"output",
"directories",
"for",
"a",
"measure",
"function",
"which",
"returns",
"an",
"associated",
"uncertainty",
"."
] | train | https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/measure_utils.py#L45-L73 |
eddiejessup/agaro | agaro/measure_utils.py | params | def params(dirnames, param_func, t_steady=None):
"""Calculate a parameter of a set of model output directories,
for a measure function which returns an associated uncertainty.
Parameters
----------
dirnames: list[str]
Model output directory paths.
param_func: function
Function w... | python | def params(dirnames, param_func, t_steady=None):
"""Calculate a parameter of a set of model output directories,
for a measure function which returns an associated uncertainty.
Parameters
----------
dirnames: list[str]
Model output directory paths.
param_func: function
Function w... | [
"def",
"params",
"(",
"dirnames",
",",
"param_func",
",",
"t_steady",
"=",
"None",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"param_func",
"(",
"get_recent_model",
"(",
"d",
")",
")",
"for",
"d",
"in",
"dirnames",
"]",
")"
] | Calculate a parameter of a set of model output directories,
for a measure function which returns an associated uncertainty.
Parameters
----------
dirnames: list[str]
Model output directory paths.
param_func: function
Function which takes a :class:`Model` instance as a single argumen... | [
"Calculate",
"a",
"parameter",
"of",
"a",
"set",
"of",
"model",
"output",
"directories",
"for",
"a",
"measure",
"function",
"which",
"returns",
"an",
"associated",
"uncertainty",
"."
] | train | https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/measure_utils.py#L76-L93 |
eddiejessup/agaro | agaro/measure_utils.py | t_measures | def t_measures(dirname, time_func, measure_func):
"""Calculate a measure over time for a single output directory,
and its uncertainty.
Parameters
----------
dirname: str
Path to a model output directory.
time_func: function
Function which takes a :class:`Model` instance as a sin... | python | def t_measures(dirname, time_func, measure_func):
"""Calculate a measure over time for a single output directory,
and its uncertainty.
Parameters
----------
dirname: str
Path to a model output directory.
time_func: function
Function which takes a :class:`Model` instance as a sin... | [
"def",
"t_measures",
"(",
"dirname",
",",
"time_func",
",",
"measure_func",
")",
":",
"ts",
",",
"measures",
",",
"measure_errs",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"for",
"fname",
"in",
"get_filenames",
"(",
"dirname",
")",
":",
"m",
"=",
... | Calculate a measure over time for a single output directory,
and its uncertainty.
Parameters
----------
dirname: str
Path to a model output directory.
time_func: function
Function which takes a :class:`Model` instance as a single argument,
and returns its time.
measure_f... | [
"Calculate",
"a",
"measure",
"over",
"time",
"for",
"a",
"single",
"output",
"directory",
"and",
"its",
"uncertainty",
"."
] | train | https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/measure_utils.py#L96-L127 |
eddiejessup/agaro | agaro/measure_utils.py | group_by_key | def group_by_key(dirnames, key):
"""Group a set of output directories according to a model parameter.
Parameters
----------
dirnames: list[str]
Output directories
key: various
A field of a :class:`Model` instance.
Returns
-------
groups: dict[various: list[str]]
... | python | def group_by_key(dirnames, key):
"""Group a set of output directories according to a model parameter.
Parameters
----------
dirnames: list[str]
Output directories
key: various
A field of a :class:`Model` instance.
Returns
-------
groups: dict[various: list[str]]
... | [
"def",
"group_by_key",
"(",
"dirnames",
",",
"key",
")",
":",
"groups",
"=",
"defaultdict",
"(",
"lambda",
":",
"[",
"]",
")",
"for",
"dirname",
"in",
"dirnames",
":",
"m",
"=",
"get_recent_model",
"(",
"dirname",
")",
"groups",
"[",
"m",
".",
"__dict_... | Group a set of output directories according to a model parameter.
Parameters
----------
dirnames: list[str]
Output directories
key: various
A field of a :class:`Model` instance.
Returns
-------
groups: dict[various: list[str]]
For each value of `key` that is found a... | [
"Group",
"a",
"set",
"of",
"output",
"directories",
"according",
"to",
"a",
"model",
"parameter",
"."
] | train | https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/measure_utils.py#L130-L150 |
ardydedase/pycouchbase | couchbase-python-cffi/couchbase_ffi/result.py | MultiResult._add_err | def _add_err(self, exinfo):
"""
Sets the error on this MultiResult. Will be ignored if an error is
already set.
:param exinfo: Return value from ``sys.exc_info()``
"""
if self._err:
return
self._err = exinfo
self.all_ok = False | python | def _add_err(self, exinfo):
"""
Sets the error on this MultiResult. Will be ignored if an error is
already set.
:param exinfo: Return value from ``sys.exc_info()``
"""
if self._err:
return
self._err = exinfo
self.all_ok = False | [
"def",
"_add_err",
"(",
"self",
",",
"exinfo",
")",
":",
"if",
"self",
".",
"_err",
":",
"return",
"self",
".",
"_err",
"=",
"exinfo",
"self",
".",
"all_ok",
"=",
"False"
] | Sets the error on this MultiResult. Will be ignored if an error is
already set.
:param exinfo: Return value from ``sys.exc_info()`` | [
"Sets",
"the",
"error",
"on",
"this",
"MultiResult",
".",
"Will",
"be",
"ignored",
"if",
"an",
"error",
"is",
"already",
"set",
".",
":",
"param",
"exinfo",
":",
"Return",
"value",
"from",
"sys",
".",
"exc_info",
"()"
] | train | https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/couchbase-python-cffi/couchbase_ffi/result.py#L121-L130 |
ardydedase/pycouchbase | couchbase-python-cffi/couchbase_ffi/result.py | MultiResult._add_bad_rc | def _add_bad_rc(self, rc, result):
"""
Sets an error with a bad return code. Handles 'quiet' logic
:param rc: The error code
"""
if not rc:
return
self.all_ok = False
if rc == C.LCB_KEY_ENOENT and self._quiet:
return
try:
... | python | def _add_bad_rc(self, rc, result):
"""
Sets an error with a bad return code. Handles 'quiet' logic
:param rc: The error code
"""
if not rc:
return
self.all_ok = False
if rc == C.LCB_KEY_ENOENT and self._quiet:
return
try:
... | [
"def",
"_add_bad_rc",
"(",
"self",
",",
"rc",
",",
"result",
")",
":",
"if",
"not",
"rc",
":",
"return",
"self",
".",
"all_ok",
"=",
"False",
"if",
"rc",
"==",
"C",
".",
"LCB_KEY_ENOENT",
"and",
"self",
".",
"_quiet",
":",
"return",
"try",
":",
"ra... | Sets an error with a bad return code. Handles 'quiet' logic
:param rc: The error code | [
"Sets",
"an",
"error",
"with",
"a",
"bad",
"return",
"code",
".",
"Handles",
"quiet",
"logic",
":",
"param",
"rc",
":",
"The",
"error",
"code"
] | train | https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/couchbase-python-cffi/couchbase_ffi/result.py#L132-L150 |
ardydedase/pycouchbase | couchbase-python-cffi/couchbase_ffi/result.py | MultiResult._decr_remaining | def _decr_remaining(self):
"""
Call when a result is received to decrement the remaining count
:return: True if there are no more items remaining
"""
assert self._remaining > 0
self._remaining -= 1
if not self._remaining:
self._cdata = None
... | python | def _decr_remaining(self):
"""
Call when a result is received to decrement the remaining count
:return: True if there are no more items remaining
"""
assert self._remaining > 0
self._remaining -= 1
if not self._remaining:
self._cdata = None
... | [
"def",
"_decr_remaining",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_remaining",
">",
"0",
"self",
".",
"_remaining",
"-=",
"1",
"if",
"not",
"self",
".",
"_remaining",
":",
"self",
".",
"_cdata",
"=",
"None",
"return",
"True"
] | Call when a result is received to decrement the remaining count
:return: True if there are no more items remaining | [
"Call",
"when",
"a",
"result",
"is",
"received",
"to",
"decrement",
"the",
"remaining",
"count",
":",
"return",
":",
"True",
"if",
"there",
"are",
"no",
"more",
"items",
"remaining"
] | train | https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/couchbase-python-cffi/couchbase_ffi/result.py#L152-L161 |
ardydedase/pycouchbase | couchbase-python-cffi/couchbase_ffi/result.py | MultiResult._maybe_throw | def _maybe_throw(self):
"""
Throw any deferred exceptions set via :meth:`_add_err`
"""
if self._err:
ex_cls, ex_obj, ex_bt = self._err
self._err = None
PyCBC.raise_helper(ex_cls, ex_obj, ex_bt) | python | def _maybe_throw(self):
"""
Throw any deferred exceptions set via :meth:`_add_err`
"""
if self._err:
ex_cls, ex_obj, ex_bt = self._err
self._err = None
PyCBC.raise_helper(ex_cls, ex_obj, ex_bt) | [
"def",
"_maybe_throw",
"(",
"self",
")",
":",
"if",
"self",
".",
"_err",
":",
"ex_cls",
",",
"ex_obj",
",",
"ex_bt",
"=",
"self",
".",
"_err",
"self",
".",
"_err",
"=",
"None",
"PyCBC",
".",
"raise_helper",
"(",
"ex_cls",
",",
"ex_obj",
",",
"ex_bt",... | Throw any deferred exceptions set via :meth:`_add_err` | [
"Throw",
"any",
"deferred",
"exceptions",
"set",
"via",
":",
"meth",
":",
"_add_err"
] | train | https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/couchbase-python-cffi/couchbase_ffi/result.py#L163-L170 |
ardydedase/pycouchbase | couchbase-python-cffi/couchbase_ffi/result.py | MultiResult.unwrap_single | def unwrap_single(self):
"""
Unwrap the single Result item. Call this from single-operation
methods to return the actual result
:return: The actual result
"""
try:
return next(self.itervalues())
except AttributeError:
return next(iter(self.... | python | def unwrap_single(self):
"""
Unwrap the single Result item. Call this from single-operation
methods to return the actual result
:return: The actual result
"""
try:
return next(self.itervalues())
except AttributeError:
return next(iter(self.... | [
"def",
"unwrap_single",
"(",
"self",
")",
":",
"try",
":",
"return",
"next",
"(",
"self",
".",
"itervalues",
"(",
")",
")",
"except",
"AttributeError",
":",
"return",
"next",
"(",
"iter",
"(",
"self",
".",
"values",
"(",
")",
")",
")"
] | Unwrap the single Result item. Call this from single-operation
methods to return the actual result
:return: The actual result | [
"Unwrap",
"the",
"single",
"Result",
"item",
".",
"Call",
"this",
"from",
"single",
"-",
"operation",
"methods",
"to",
"return",
"the",
"actual",
"result",
":",
"return",
":",
"The",
"actual",
"result"
] | train | https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/couchbase-python-cffi/couchbase_ffi/result.py#L172-L181 |
limiear/soyprice | soyprice/bots/statistic.py | VariableRegression.pearson_correlation | def pearson_correlation(self):
x, y, dt = self.data
X, Y = np.array(x), np.array(y)
''' Compute Pearson Correlation Coefficient. '''
# Normalise X and Y
X -= X.mean(0)
Y -= Y.mean(0)
# Standardise X and Y
X /= X.std(0)
Y /= Y.std(0)
# Compu... | python | def pearson_correlation(self):
x, y, dt = self.data
X, Y = np.array(x), np.array(y)
''' Compute Pearson Correlation Coefficient. '''
# Normalise X and Y
X -= X.mean(0)
Y -= Y.mean(0)
# Standardise X and Y
X /= X.std(0)
Y /= Y.std(0)
# Compu... | [
"def",
"pearson_correlation",
"(",
"self",
")",
":",
"x",
",",
"y",
",",
"dt",
"=",
"self",
".",
"data",
"X",
",",
"Y",
"=",
"np",
".",
"array",
"(",
"x",
")",
",",
"np",
".",
"array",
"(",
"y",
")",
"# Normalise X and Y",
"X",
"-=",
"X",
".",
... | Compute Pearson Correlation Coefficient. | [
"Compute",
"Pearson",
"Correlation",
"Coefficient",
"."
] | train | https://github.com/limiear/soyprice/blob/b7f8847b1ab4ba7d9e654135321c5598c7d1aeb1/soyprice/bots/statistic.py#L147-L158 |
pjuren/pyokit | src/pyokit/io/bedIterators.py | intervalTrees | def intervalTrees(reffh, scoreType=int, verbose=False):
"""
Build a dictionary of interval trees indexed by chrom from a BED stream or
file
:param reffh: This can be either a string, or a stream-like object. In the
former case, it is treated as a filename. The format of the
file... | python | def intervalTrees(reffh, scoreType=int, verbose=False):
"""
Build a dictionary of interval trees indexed by chrom from a BED stream or
file
:param reffh: This can be either a string, or a stream-like object. In the
former case, it is treated as a filename. The format of the
file... | [
"def",
"intervalTrees",
"(",
"reffh",
",",
"scoreType",
"=",
"int",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"type",
"(",
"reffh",
")",
".",
"__name__",
"==",
"\"str\"",
":",
"fh",
"=",
"open",
"(",
"reffh",
")",
"else",
":",
"fh",
"=",
"reffh... | Build a dictionary of interval trees indexed by chrom from a BED stream or
file
:param reffh: This can be either a string, or a stream-like object. In the
former case, it is treated as a filename. The format of the
file/stream must be BED.
:param scoreType: The data type for score... | [
"Build",
"a",
"dictionary",
"of",
"interval",
"trees",
"indexed",
"by",
"chrom",
"from",
"a",
"BED",
"stream",
"or",
"file"
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/io/bedIterators.py#L62-L107 |
pjuren/pyokit | src/pyokit/io/bedIterators.py | BEDIterator | def BEDIterator(filehandle, sortedby=None, verbose=False, scoreType=int,
dropAfter=None):
"""
Get an iterator for a BED file
:param filehandle: this can be either a string, or a stream-like object. In
the former case, it is treated as a filename. The format
... | python | def BEDIterator(filehandle, sortedby=None, verbose=False, scoreType=int,
dropAfter=None):
"""
Get an iterator for a BED file
:param filehandle: this can be either a string, or a stream-like object. In
the former case, it is treated as a filename. The format
... | [
"def",
"BEDIterator",
"(",
"filehandle",
",",
"sortedby",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"scoreType",
"=",
"int",
",",
"dropAfter",
"=",
"None",
")",
":",
"chromsSeen",
"=",
"set",
"(",
")",
"prev",
"=",
"None",
"if",
"type",
"(",
"f... | Get an iterator for a BED file
:param filehandle: this can be either a string, or a stream-like object. In
the former case, it is treated as a filename. The format
of the file/stream must be BED.
:param sortedby: if None, order is not checked.
if == ITER... | [
"Get",
"an",
"iterator",
"for",
"a",
"BED",
"file"
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/io/bedIterators.py#L114-L204 |
pjuren/pyokit | src/pyokit/io/bedIterators.py | pairedBEDIterator | def pairedBEDIterator(inputStreams, mirror=False, mirrorScore=None,
ignoreStrand=False, ignoreScore=True, ignoreName=True,
sortedby=ITERATOR_SORTED_END, scoreType=float,
verbose=False):
"""
Iterate over multiple BED format files simultaneously and yi... | python | def pairedBEDIterator(inputStreams, mirror=False, mirrorScore=None,
ignoreStrand=False, ignoreScore=True, ignoreName=True,
sortedby=ITERATOR_SORTED_END, scoreType=float,
verbose=False):
"""
Iterate over multiple BED format files simultaneously and yi... | [
"def",
"pairedBEDIterator",
"(",
"inputStreams",
",",
"mirror",
"=",
"False",
",",
"mirrorScore",
"=",
"None",
",",
"ignoreStrand",
"=",
"False",
",",
"ignoreScore",
"=",
"True",
",",
"ignoreName",
"=",
"True",
",",
"sortedby",
"=",
"ITERATOR_SORTED_END",
",",... | Iterate over multiple BED format files simultaneously and yield lists of
genomic intervals for each matching set of intervals found. By default,
regions which are not found in all files will be skipped (mirror = false).
Optionally (by setting mirror to true) if a file is missing an interval,
it can be added on-... | [
"Iterate",
"over",
"multiple",
"BED",
"format",
"files",
"simultaneously",
"and",
"yield",
"lists",
"of",
"genomic",
"intervals",
"for",
"each",
"matching",
"set",
"of",
"intervals",
"found",
".",
"By",
"default",
"regions",
"which",
"are",
"not",
"found",
"in... | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/io/bedIterators.py#L207-L289 |
tBaxter/django-fretboard | fretboard/signals.py | update_forum_votes | def update_forum_votes(sender, **kwargs):
"""
When a Vote is added, re-saves the topic or post to update vote count.
Since Votes can be assigned
to any content type, first makes sure we are dealing with a forum post or topic.
Deprecated 1-6-14 by storing score as cached property
"""
... | python | def update_forum_votes(sender, **kwargs):
"""
When a Vote is added, re-saves the topic or post to update vote count.
Since Votes can be assigned
to any content type, first makes sure we are dealing with a forum post or topic.
Deprecated 1-6-14 by storing score as cached property
"""
... | [
"def",
"update_forum_votes",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"vote",
"=",
"kwargs",
"[",
"'instance'",
"]",
"if",
"vote",
".",
"content_type",
".",
"app_label",
"!=",
"\"fretboard\"",
":",
"return",
"if",
"vote",
".",
"content_type",
".",... | When a Vote is added, re-saves the topic or post to update vote count.
Since Votes can be assigned
to any content type, first makes sure we are dealing with a forum post or topic.
Deprecated 1-6-14 by storing score as cached property | [
"When",
"a",
"Vote",
"is",
"added",
"re",
"-",
"saves",
"the",
"topic",
"or",
"post",
"to",
"update",
"vote",
"count",
".",
"Since",
"Votes",
"can",
"be",
"assigned",
"to",
"any",
"content",
"type",
"first",
"makes",
"sure",
"we",
"are",
"dealing",
"wi... | train | https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/signals.py#L7-L25 |
cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/connection_plugins/paramiko_ssh.py | Connection._connect_uncached | def _connect_uncached(self):
''' activates the connection object '''
if not HAVE_PARAMIKO:
raise errors.AnsibleError("paramiko is not installed")
user = self.runner.remote_user
vvv("ESTABLISH CONNECTION FOR USER: %s on PORT %s TO %s" % (user, self.port, self.host), host=se... | python | def _connect_uncached(self):
''' activates the connection object '''
if not HAVE_PARAMIKO:
raise errors.AnsibleError("paramiko is not installed")
user = self.runner.remote_user
vvv("ESTABLISH CONNECTION FOR USER: %s on PORT %s TO %s" % (user, self.port, self.host), host=se... | [
"def",
"_connect_uncached",
"(",
"self",
")",
":",
"if",
"not",
"HAVE_PARAMIKO",
":",
"raise",
"errors",
".",
"AnsibleError",
"(",
"\"paramiko is not installed\"",
")",
"user",
"=",
"self",
".",
"runner",
".",
"remote_user",
"vvv",
"(",
"\"ESTABLISH CONNECTION FOR... | activates the connection object | [
"activates",
"the",
"connection",
"object"
] | train | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/connection_plugins/paramiko_ssh.py#L67-L109 |
cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/connection_plugins/paramiko_ssh.py | Connection.exec_command | def exec_command(self, cmd, tmp_path, sudo_user, sudoable=False, executable='/bin/sh'):
''' run a command on the remote host '''
bufsize = 4096
try:
chan = self.ssh.get_transport().open_session()
except Exception, e:
msg = "Failed to open session"
if ... | python | def exec_command(self, cmd, tmp_path, sudo_user, sudoable=False, executable='/bin/sh'):
''' run a command on the remote host '''
bufsize = 4096
try:
chan = self.ssh.get_transport().open_session()
except Exception, e:
msg = "Failed to open session"
if ... | [
"def",
"exec_command",
"(",
"self",
",",
"cmd",
",",
"tmp_path",
",",
"sudo_user",
",",
"sudoable",
"=",
"False",
",",
"executable",
"=",
"'/bin/sh'",
")",
":",
"bufsize",
"=",
"4096",
"try",
":",
"chan",
"=",
"self",
".",
"ssh",
".",
"get_transport",
... | run a command on the remote host | [
"run",
"a",
"command",
"on",
"the",
"remote",
"host"
] | train | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/connection_plugins/paramiko_ssh.py#L111-L154 |
cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/connection_plugins/paramiko_ssh.py | Connection.put_file | def put_file(self, in_path, out_path):
''' transfer a file from local to remote '''
vvv("PUT %s TO %s" % (in_path, out_path), host=self.host)
if not os.path.exists(in_path):
raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
try:
self.... | python | def put_file(self, in_path, out_path):
''' transfer a file from local to remote '''
vvv("PUT %s TO %s" % (in_path, out_path), host=self.host)
if not os.path.exists(in_path):
raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
try:
self.... | [
"def",
"put_file",
"(",
"self",
",",
"in_path",
",",
"out_path",
")",
":",
"vvv",
"(",
"\"PUT %s TO %s\"",
"%",
"(",
"in_path",
",",
"out_path",
")",
",",
"host",
"=",
"self",
".",
"host",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"i... | transfer a file from local to remote | [
"transfer",
"a",
"file",
"from",
"local",
"to",
"remote"
] | train | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/connection_plugins/paramiko_ssh.py#L156-L168 |
cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/connection_plugins/paramiko_ssh.py | Connection.fetch_file | def fetch_file(self, in_path, out_path):
''' save a remote file to the specified path '''
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host)
try:
self.sftp = self._connect_sftp()
except:
raise errors.AnsibleError("failed to open a SFTP connection")
... | python | def fetch_file(self, in_path, out_path):
''' save a remote file to the specified path '''
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host)
try:
self.sftp = self._connect_sftp()
except:
raise errors.AnsibleError("failed to open a SFTP connection")
... | [
"def",
"fetch_file",
"(",
"self",
",",
"in_path",
",",
"out_path",
")",
":",
"vvv",
"(",
"\"FETCH %s TO %s\"",
"%",
"(",
"in_path",
",",
"out_path",
")",
",",
"host",
"=",
"self",
".",
"host",
")",
"try",
":",
"self",
".",
"sftp",
"=",
"self",
".",
... | save a remote file to the specified path | [
"save",
"a",
"remote",
"file",
"to",
"the",
"specified",
"path"
] | train | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/connection_plugins/paramiko_ssh.py#L178-L188 |
cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/connection_plugins/paramiko_ssh.py | Connection.close | def close(self):
''' terminate the connection '''
cache_key = self._cache_key()
SSH_CONNECTION_CACHE.pop(cache_key, None)
SFTP_CONNECTION_CACHE.pop(cache_key, None)
if self.sftp is not None:
self.sftp.close()
self.ssh.close() | python | def close(self):
''' terminate the connection '''
cache_key = self._cache_key()
SSH_CONNECTION_CACHE.pop(cache_key, None)
SFTP_CONNECTION_CACHE.pop(cache_key, None)
if self.sftp is not None:
self.sftp.close()
self.ssh.close() | [
"def",
"close",
"(",
"self",
")",
":",
"cache_key",
"=",
"self",
".",
"_cache_key",
"(",
")",
"SSH_CONNECTION_CACHE",
".",
"pop",
"(",
"cache_key",
",",
"None",
")",
"SFTP_CONNECTION_CACHE",
".",
"pop",
"(",
"cache_key",
",",
"None",
")",
"if",
"self",
"... | terminate the connection | [
"terminate",
"the",
"connection"
] | train | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/connection_plugins/paramiko_ssh.py#L190-L197 |
thomas-maurice/clifactory | clifactory/clifactory.py | CommandLineInterface.parse | def parse(self, line=None):
"""parses the line provided, if None then uses sys.argv"""
args = self.parser.parse_args(args=line)
return args.func(args) | python | def parse(self, line=None):
"""parses the line provided, if None then uses sys.argv"""
args = self.parser.parse_args(args=line)
return args.func(args) | [
"def",
"parse",
"(",
"self",
",",
"line",
"=",
"None",
")",
":",
"args",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"args",
"=",
"line",
")",
"return",
"args",
".",
"func",
"(",
"args",
")"
] | parses the line provided, if None then uses sys.argv | [
"parses",
"the",
"line",
"provided",
"if",
"None",
"then",
"uses",
"sys",
".",
"argv"
] | train | https://github.com/thomas-maurice/clifactory/blob/b0649e3fe8901a3de7a3e3ecf4bf23499f6a87b3/clifactory/clifactory.py#L65-L68 |
thomas-maurice/clifactory | clifactory/clifactory.py | CommandLineInterface.endpoint | def endpoint(self, *args):
"""endpoint: Decorates a function to make it a CLI endpoint
The function must be called do_<some>_<action> and accept one 'args'
parameter. It will be converted into a ./cli some action commandline
endpoint.
A set of Arguments can be p... | python | def endpoint(self, *args):
"""endpoint: Decorates a function to make it a CLI endpoint
The function must be called do_<some>_<action> and accept one 'args'
parameter. It will be converted into a ./cli some action commandline
endpoint.
A set of Arguments can be p... | [
"def",
"endpoint",
"(",
"self",
",",
"*",
"args",
")",
":",
"# Decorator function",
"def",
"decorator",
"(",
"func",
")",
":",
"func_name",
"=",
"func",
".",
"__name__",
"func_name",
"=",
"func_name",
".",
"replace",
"(",
"\"do_\"",
",",
"\"\"",
")",
"ac... | endpoint: Decorates a function to make it a CLI endpoint
The function must be called do_<some>_<action> and accept one 'args'
parameter. It will be converted into a ./cli some action commandline
endpoint.
A set of Arguments can be passed to the decorator, the syntax is ... | [
"endpoint",
":",
"Decorates",
"a",
"function",
"to",
"make",
"it",
"a",
"CLI",
"endpoint",
"The",
"function",
"must",
"be",
"called",
"do_<some",
">",
"_<action",
">",
"and",
"accept",
"one",
"args",
"parameter",
".",
"It",
"will",
"be",
"converted",
"into... | train | https://github.com/thomas-maurice/clifactory/blob/b0649e3fe8901a3de7a3e3ecf4bf23499f6a87b3/clifactory/clifactory.py#L71-L126 |
timgabets/tracetools | tracetools/tracetools.py | dump | def dump(data):
"""
Dump the memory data, e.g.:
00 cc 30 31 30 30 72 30 05 80 20 c0 92 00 31 36 ..0100r0.. ...16
38 39 39 30 30 31 31 32 33 34 35 36 37 38 39 30 8990011234567890
30 30 30 30 30 30 30 30 30 30 30 30 30 32 30 30 0000000000000200
30 30 31 34 39 34 35 30 ... | python | def dump(data):
"""
Dump the memory data, e.g.:
00 cc 30 31 30 30 72 30 05 80 20 c0 92 00 31 36 ..0100r0.. ...16
38 39 39 30 30 31 31 32 33 34 35 36 37 38 39 30 8990011234567890
30 30 30 30 30 30 30 30 30 30 30 30 30 32 30 30 0000000000000200
30 30 31 34 39 34 35 30 ... | [
"def",
"dump",
"(",
"data",
")",
":",
"i",
"=",
"1",
"if",
"(",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"==",
"False",
")",
":",
"raise",
"TypeError",
"(",
"'tracetools.dump(): data is expected to be bytes, not {}'",
".",
"format",
"(",
"type",
"(",
... | Dump the memory data, e.g.:
00 cc 30 31 30 30 72 30 05 80 20 c0 92 00 31 36 ..0100r0.. ...16
38 39 39 30 30 31 31 32 33 34 35 36 37 38 39 30 8990011234567890
30 30 30 30 30 30 30 30 30 30 30 30 30 32 30 30 0000000000000200
30 30 31 34 39 34 35 30 34 34 39 34 38 30 30 32 ... | [
"Dump",
"the",
"memory",
"data",
"e",
".",
"g",
".",
":",
"00",
"cc",
"30",
"31",
"30",
"30",
"72",
"30",
"05",
"80",
"20",
"c0",
"92",
"00",
"31",
"36",
"..",
"0100r0",
"..",
"...",
"16",
"38",
"39",
"39",
"30",
"30",
"31",
"31",
"32",
"33... | train | https://github.com/timgabets/tracetools/blob/c6cbaa7090756d9db853d092ac78dd7dc4023bce/tracetools/tracetools.py#L5-L58 |
timgabets/tracetools | tracetools/tracetools.py | trace | def trace(data, title=None):
"""
Trace the binary data - add user-defined title, timstamp and dumped data, e.g.:
12:08:16.762628 >> User-defined-title:
00 cc 30 31 30 30 72 30 05 80 20 c0 92 00 31 36 ..0100r0.. ...16
38 39 39 30 30 31 31 32 33 34 35 36 37 38 39 30 8990011234567890
... | python | def trace(data, title=None):
"""
Trace the binary data - add user-defined title, timstamp and dumped data, e.g.:
12:08:16.762628 >> User-defined-title:
00 cc 30 31 30 30 72 30 05 80 20 c0 92 00 31 36 ..0100r0.. ...16
38 39 39 30 30 31 31 32 33 34 35 36 37 38 39 30 8990011234567890
... | [
"def",
"trace",
"(",
"data",
",",
"title",
"=",
"None",
")",
":",
"if",
"title",
":",
"print",
"(",
"'{} {}\\n{}'",
".",
"format",
"(",
"get_timestamp",
"(",
")",
",",
"title",
",",
"dump",
"(",
"data",
")",
")",
")",
"else",
":",
"print",
"(",
"... | Trace the binary data - add user-defined title, timstamp and dumped data, e.g.:
12:08:16.762628 >> User-defined-title:
00 cc 30 31 30 30 72 30 05 80 20 c0 92 00 31 36 ..0100r0.. ...16
38 39 39 30 30 31 31 32 33 34 35 36 37 38 39 30 8990011234567890
30 30 30 30 30 30 30 30 30 30 30 30 30... | [
"Trace",
"the",
"binary",
"data",
"-",
"add",
"user",
"-",
"defined",
"title",
"timstamp",
"and",
"dumped",
"data",
"e",
".",
"g",
".",
":"
] | train | https://github.com/timgabets/tracetools/blob/c6cbaa7090756d9db853d092ac78dd7dc4023bce/tracetools/tracetools.py#L61-L84 |
openbermuda/ripl | ripl/slidelayout.py | SlideLayout.interpret | def interpret(self, msg):
""" Load input """
slides = msg.get('slides', [])
result = []
for slide in slides:
image = self.layout(slide)
result.append(image)
return result | python | def interpret(self, msg):
""" Load input """
slides = msg.get('slides', [])
result = []
for slide in slides:
image = self.layout(slide)
result.append(image)
return result | [
"def",
"interpret",
"(",
"self",
",",
"msg",
")",
":",
"slides",
"=",
"msg",
".",
"get",
"(",
"'slides'",
",",
"[",
"]",
")",
"result",
"=",
"[",
"]",
"for",
"slide",
"in",
"slides",
":",
"image",
"=",
"self",
".",
"layout",
"(",
"slide",
")",
... | Load input | [
"Load",
"input"
] | train | https://github.com/openbermuda/ripl/blob/4886b1a697e4b81c2202db9cb977609e034f8e70/ripl/slidelayout.py#L33-L43 |
openbermuda/ripl | ripl/slidelayout.py | SlideLayout.layout | def layout(self, slide):
""" Return layout information for slide """
image = Image.new('RGB', (WIDTH, HEIGHT), 'black')
draw = ImageDraw.Draw(image)
draw.font = self.font
self.vertical_layout(draw, slide)
self.horizontal_layout(draw, slide)
ret... | python | def layout(self, slide):
""" Return layout information for slide """
image = Image.new('RGB', (WIDTH, HEIGHT), 'black')
draw = ImageDraw.Draw(image)
draw.font = self.font
self.vertical_layout(draw, slide)
self.horizontal_layout(draw, slide)
ret... | [
"def",
"layout",
"(",
"self",
",",
"slide",
")",
":",
"image",
"=",
"Image",
".",
"new",
"(",
"'RGB'",
",",
"(",
"WIDTH",
",",
"HEIGHT",
")",
",",
"'black'",
")",
"draw",
"=",
"ImageDraw",
".",
"Draw",
"(",
"image",
")",
"draw",
".",
"font",
"=",... | Return layout information for slide | [
"Return",
"layout",
"information",
"for",
"slide"
] | train | https://github.com/openbermuda/ripl/blob/4886b1a697e4b81c2202db9cb977609e034f8e70/ripl/slidelayout.py#L45-L56 |
openbermuda/ripl | ripl/slidelayout.py | SlideLayout.vertical_layout | def vertical_layout(self, draw, slide):
""" Augment slide with vertical layout info """
padding = self.padding
heading = slide['heading']
width, height = draw.textsize(heading['text'])
top = padding
left = padding
# Calculate size and location of heading
... | python | def vertical_layout(self, draw, slide):
""" Augment slide with vertical layout info """
padding = self.padding
heading = slide['heading']
width, height = draw.textsize(heading['text'])
top = padding
left = padding
# Calculate size and location of heading
... | [
"def",
"vertical_layout",
"(",
"self",
",",
"draw",
",",
"slide",
")",
":",
"padding",
"=",
"self",
".",
"padding",
"heading",
"=",
"slide",
"[",
"'heading'",
"]",
"width",
",",
"height",
"=",
"draw",
".",
"textsize",
"(",
"heading",
"[",
"'text'",
"]"... | Augment slide with vertical layout info | [
"Augment",
"slide",
"with",
"vertical",
"layout",
"info"
] | train | https://github.com/openbermuda/ripl/blob/4886b1a697e4b81c2202db9cb977609e034f8e70/ripl/slidelayout.py#L59-L145 |
openbermuda/ripl | ripl/slidelayout.py | SlideLayout.horizontal_layout | def horizontal_layout(self, draw, slide):
""" Augment slide with horizontal layout info """
padding = self.padding
heading = slide['heading']
top = padding
left = padding
top += heading['height'] + padding
rows = slide['rows']
for row in rows:
... | python | def horizontal_layout(self, draw, slide):
""" Augment slide with horizontal layout info """
padding = self.padding
heading = slide['heading']
top = padding
left = padding
top += heading['height'] + padding
rows = slide['rows']
for row in rows:
... | [
"def",
"horizontal_layout",
"(",
"self",
",",
"draw",
",",
"slide",
")",
":",
"padding",
"=",
"self",
".",
"padding",
"heading",
"=",
"slide",
"[",
"'heading'",
"]",
"top",
"=",
"padding",
"left",
"=",
"padding",
"top",
"+=",
"heading",
"[",
"'height'",
... | Augment slide with horizontal layout info | [
"Augment",
"slide",
"with",
"horizontal",
"layout",
"info"
] | train | https://github.com/openbermuda/ripl/blob/4886b1a697e4b81c2202db9cb977609e034f8e70/ripl/slidelayout.py#L147-L184 |
ardydedase/pycouchbase | couchbase-python-cffi/couchbase_ffi/__init__.py | _mk_imp_override | def _mk_imp_override(srcname, replacement):
"""
Create a simple one for one replacement for a module
:param srcname: The source module name to replace
:param replacement: The object which should act as the replacement
"""
class DummyImporter(object):
def find_module(self, fullname, path)... | python | def _mk_imp_override(srcname, replacement):
"""
Create a simple one for one replacement for a module
:param srcname: The source module name to replace
:param replacement: The object which should act as the replacement
"""
class DummyImporter(object):
def find_module(self, fullname, path)... | [
"def",
"_mk_imp_override",
"(",
"srcname",
",",
"replacement",
")",
":",
"class",
"DummyImporter",
"(",
"object",
")",
":",
"def",
"find_module",
"(",
"self",
",",
"fullname",
",",
"path",
")",
":",
"if",
"fullname",
"==",
"srcname",
":",
"return",
"self",... | Create a simple one for one replacement for a module
:param srcname: The source module name to replace
:param replacement: The object which should act as the replacement | [
"Create",
"a",
"simple",
"one",
"for",
"one",
"replacement",
"for",
"a",
"module",
":",
"param",
"srcname",
":",
"The",
"source",
"module",
"name",
"to",
"replace",
":",
"param",
"replacement",
":",
"The",
"object",
"which",
"should",
"act",
"as",
"the",
... | train | https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/couchbase-python-cffi/couchbase_ffi/__init__.py#L7-L27 |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_xfac.py | gp_xfac | def gp_xfac():
"""example using QM12 enhancement factors
- uses `gpcalls` kwarg to reset xtics
- numpy.loadtxt needs reshaping for input files w/ only one datapoint
- according poster presentations see QM12_ & NSD_ review
.. _QM12: http://indico.cern.ch/getFile.py/access?contribId=268&sessionId=10&resId=0&m... | python | def gp_xfac():
"""example using QM12 enhancement factors
- uses `gpcalls` kwarg to reset xtics
- numpy.loadtxt needs reshaping for input files w/ only one datapoint
- according poster presentations see QM12_ & NSD_ review
.. _QM12: http://indico.cern.ch/getFile.py/access?contribId=268&sessionId=10&resId=0&m... | [
"def",
"gp_xfac",
"(",
")",
":",
"# prepare data",
"inDir",
",",
"outDir",
"=",
"getWorkDirs",
"(",
")",
"data",
"=",
"OrderedDict",
"(",
")",
"# TODO: \"really\" reproduce plot using spectral data",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
"inDir",
")",
... | example using QM12 enhancement factors
- uses `gpcalls` kwarg to reset xtics
- numpy.loadtxt needs reshaping for input files w/ only one datapoint
- according poster presentations see QM12_ & NSD_ review
.. _QM12: http://indico.cern.ch/getFile.py/access?contribId=268&sessionId=10&resId=0&materialId=slides&con... | [
"example",
"using",
"QM12",
"enhancement",
"factors"
] | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_xfac.py#L12-L63 |
ramrod-project/database-brain | schema/brain/checks.py | verify | def verify(value, msg):
"""
C-style validator
Keyword arguments:
value -- dictionary to validate (required)
msg -- the protobuf schema to validate against (required)
Returns:
True: If valid input
False: If invalid input
"""
return bool(value) and \
converts_t... | python | def verify(value, msg):
"""
C-style validator
Keyword arguments:
value -- dictionary to validate (required)
msg -- the protobuf schema to validate against (required)
Returns:
True: If valid input
False: If invalid input
"""
return bool(value) and \
converts_t... | [
"def",
"verify",
"(",
"value",
",",
"msg",
")",
":",
"return",
"bool",
"(",
"value",
")",
"and",
"converts_to_proto",
"(",
"value",
",",
"msg",
")",
"and",
"successfuly_encodes",
"(",
"msg",
")",
"and",
"special_typechecking",
"(",
"value",
",",
"msg",
"... | C-style validator
Keyword arguments:
value -- dictionary to validate (required)
msg -- the protobuf schema to validate against (required)
Returns:
True: If valid input
False: If invalid input | [
"C",
"-",
"style",
"validator"
] | train | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/checks.py#L13-L28 |
ramrod-project/database-brain | schema/brain/checks.py | special_typechecking | def special_typechecking(value, msg):
"""
Special Typechecking not available via protocol itself
:param value: <dict>
:param msg: <proto object>
:return: <bool>
"""
result = True
if msg.DESCRIPTOR.name == TARGET:
result &= special_target_typecheck(value)
elif msg.DESCRIPTOR.n... | python | def special_typechecking(value, msg):
"""
Special Typechecking not available via protocol itself
:param value: <dict>
:param msg: <proto object>
:return: <bool>
"""
result = True
if msg.DESCRIPTOR.name == TARGET:
result &= special_target_typecheck(value)
elif msg.DESCRIPTOR.n... | [
"def",
"special_typechecking",
"(",
"value",
",",
"msg",
")",
":",
"result",
"=",
"True",
"if",
"msg",
".",
"DESCRIPTOR",
".",
"name",
"==",
"TARGET",
":",
"result",
"&=",
"special_target_typecheck",
"(",
"value",
")",
"elif",
"msg",
".",
"DESCRIPTOR",
"."... | Special Typechecking not available via protocol itself
:param value: <dict>
:param msg: <proto object>
:return: <bool> | [
"Special",
"Typechecking",
"not",
"available",
"via",
"protocol",
"itself",
":",
"param",
"value",
":",
"<dict",
">",
":",
"param",
"msg",
":",
"<proto",
"object",
">",
":",
"return",
":",
"<bool",
">"
] | train | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/checks.py#L31-L43 |
ramrod-project/database-brain | schema/brain/checks.py | special_target_typecheck | def special_target_typecheck(value):
"""
Special type checking for the target object
:param value: <dict>
:return: <bool>
"""
result = True
# if key:Optional exists, it must be a dict object
result &= isinstance(value.get(TARGET_OPTIONAL_FIELD, dict()), dict)
return result | python | def special_target_typecheck(value):
"""
Special type checking for the target object
:param value: <dict>
:return: <bool>
"""
result = True
# if key:Optional exists, it must be a dict object
result &= isinstance(value.get(TARGET_OPTIONAL_FIELD, dict()), dict)
return result | [
"def",
"special_target_typecheck",
"(",
"value",
")",
":",
"result",
"=",
"True",
"# if key:Optional exists, it must be a dict object",
"result",
"&=",
"isinstance",
"(",
"value",
".",
"get",
"(",
"TARGET_OPTIONAL_FIELD",
",",
"dict",
"(",
")",
")",
",",
"dict",
"... | Special type checking for the target object
:param value: <dict>
:return: <bool> | [
"Special",
"type",
"checking",
"for",
"the",
"target",
"object",
":",
"param",
"value",
":",
"<dict",
">",
":",
"return",
":",
"<bool",
">"
] | train | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/checks.py#L55-L64 |
ramrod-project/database-brain | schema/brain/checks.py | converts_to_proto | def converts_to_proto(value, msg, raise_err=False):
"""
Boolean response if a dictionary can convert into the proto's schema
:param value: <dict>
:param msg: <proto object>
:param raise_err: <bool> (default false) raise for troubleshooting
:return: <bool> whether the dict can covert
"""
... | python | def converts_to_proto(value, msg, raise_err=False):
"""
Boolean response if a dictionary can convert into the proto's schema
:param value: <dict>
:param msg: <proto object>
:param raise_err: <bool> (default false) raise for troubleshooting
:return: <bool> whether the dict can covert
"""
... | [
"def",
"converts_to_proto",
"(",
"value",
",",
"msg",
",",
"raise_err",
"=",
"False",
")",
":",
"result",
"=",
"True",
"try",
":",
"dict_to_protobuf",
".",
"dict_to_protobuf",
"(",
"value",
",",
"msg",
")",
"except",
"TypeError",
"as",
"type_error",
":",
"... | Boolean response if a dictionary can convert into the proto's schema
:param value: <dict>
:param msg: <proto object>
:param raise_err: <bool> (default false) raise for troubleshooting
:return: <bool> whether the dict can covert | [
"Boolean",
"response",
"if",
"a",
"dictionary",
"can",
"convert",
"into",
"the",
"proto",
"s",
"schema"
] | train | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/checks.py#L67-L83 |
ramrod-project/database-brain | schema/brain/checks.py | successfuly_encodes | def successfuly_encodes(msg, raise_err=False):
"""
boolean response if a message contains correct information to serialize
:param msg: <proto object>
:param raise_err: <bool>
:return: <bool>
"""
result = True
try:
msg.SerializeToString()
except EncodeError as encode_error:
... | python | def successfuly_encodes(msg, raise_err=False):
"""
boolean response if a message contains correct information to serialize
:param msg: <proto object>
:param raise_err: <bool>
:return: <bool>
"""
result = True
try:
msg.SerializeToString()
except EncodeError as encode_error:
... | [
"def",
"successfuly_encodes",
"(",
"msg",
",",
"raise_err",
"=",
"False",
")",
":",
"result",
"=",
"True",
"try",
":",
"msg",
".",
"SerializeToString",
"(",
")",
"except",
"EncodeError",
"as",
"encode_error",
":",
"if",
"raise_err",
":",
"raise",
"encode_err... | boolean response if a message contains correct information to serialize
:param msg: <proto object>
:param raise_err: <bool>
:return: <bool> | [
"boolean",
"response",
"if",
"a",
"message",
"contains",
"correct",
"information",
"to",
"serialize"
] | train | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/checks.py#L86-L101 |
ramrod-project/database-brain | schema/brain/checks.py | strip | def strip(value, msg):
"""
Strips all non-essential keys from the value dictionary
given the message format protobuf
raises ValueError exception if value does not have all required keys
:param value: <dict> with arbitrary keys
:param msg: <protobuf> with a defined schema
:return: NEW <dict... | python | def strip(value, msg):
"""
Strips all non-essential keys from the value dictionary
given the message format protobuf
raises ValueError exception if value does not have all required keys
:param value: <dict> with arbitrary keys
:param msg: <protobuf> with a defined schema
:return: NEW <dict... | [
"def",
"strip",
"(",
"value",
",",
"msg",
")",
":",
"dict_to_protobuf",
".",
"dict_to_protobuf",
"(",
"value",
",",
"msg",
")",
"try",
":",
"msg",
".",
"SerializeToString",
"(",
")",
"#raise error for insufficient input",
"except",
"EncodeError",
"as",
"encode_e... | Strips all non-essential keys from the value dictionary
given the message format protobuf
raises ValueError exception if value does not have all required keys
:param value: <dict> with arbitrary keys
:param msg: <protobuf> with a defined schema
:return: NEW <dict> with keys defined by msg, omits a... | [
"Strips",
"all",
"non",
"-",
"essential",
"keys",
"from",
"the",
"value",
"dictionary",
"given",
"the",
"message",
"format",
"protobuf"
] | train | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/checks.py#L104-L121 |
markomanninen/abnum | remarkuple/svg.py | svg | def svg(*args, **kw):
"""
Use in this way:
´from remarkuple import helper as h, svg´
"""
class svg(type(helper.svg())):
def __init__(self, *args, **kw):
super(self.__class__, self).__init__(*args, **kw)
# cartesian grid on/off
self.__dic... | python | def svg(*args, **kw):
"""
Use in this way:
´from remarkuple import helper as h, svg´
"""
class svg(type(helper.svg())):
def __init__(self, *args, **kw):
super(self.__class__, self).__init__(*args, **kw)
# cartesian grid on/off
self.__dic... | [
"def",
"svg",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"class",
"svg",
"(",
"type",
"(",
"helper",
".",
"svg",
"(",
")",
")",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"super",
"(",
... | Use in this way:
´from remarkuple import helper as h, svg´ | [
"Use",
"in",
"this",
"way",
":",
"´from",
"remarkuple",
"import",
"helper",
"as",
"h",
"svg´"
] | train | https://github.com/markomanninen/abnum/blob/9bfc8f06f34d9a51aab038638f87e2bb5f9f4c99/remarkuple/svg.py#L8-L193 |
ulf1/oxyba | oxyba/clean_german_number.py | clean_german_number | def clean_german_number(x):
"""Convert a string with a German number into a Decimal
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A string with a number with German formatting,
or an array of these strings, e.g. list, ndarray, df.
Returns
-------
... | python | def clean_german_number(x):
"""Convert a string with a German number into a Decimal
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A string with a number with German formatting,
or an array of these strings, e.g. list, ndarray, df.
Returns
-------
... | [
"def",
"clean_german_number",
"(",
"x",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"pandas",
"as",
"pd",
"import",
"re",
"def",
"proc_elem",
"(",
"e",
")",
":",
"# abort if it is not a string",
"if",
"not",
"isinstance",
"(",
"e",
",",
"str",
")",
... | Convert a string with a German number into a Decimal
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A string with a number with German formatting,
or an array of these strings, e.g. list, ndarray, df.
Returns
-------
y : str, list, tuple, numpy.ndar... | [
"Convert",
"a",
"string",
"with",
"a",
"German",
"number",
"into",
"a",
"Decimal"
] | train | https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/clean_german_number.py#L2-L121 |
voidpp/python-web-tools | voidpp_web_tools/remote_controller_daemon.py | rpc | def rpc(method):
"""
Decorator function for register method for RPC.
Must be used a RemoteControllerDeamon (-derived) class method!
"""
@wraps(method)
def rpc_wrapper(*args, **kwargs):
controller_instance = args[0]
if not isinstance(controller_instance, RemoteControllerDeamon):
... | python | def rpc(method):
"""
Decorator function for register method for RPC.
Must be used a RemoteControllerDeamon (-derived) class method!
"""
@wraps(method)
def rpc_wrapper(*args, **kwargs):
controller_instance = args[0]
if not isinstance(controller_instance, RemoteControllerDeamon):
... | [
"def",
"rpc",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"rpc_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"controller_instance",
"=",
"args",
"[",
"0",
"]",
"if",
"not",
"isinstance",
"(",
"controller_instance"... | Decorator function for register method for RPC.
Must be used a RemoteControllerDeamon (-derived) class method! | [
"Decorator",
"function",
"for",
"register",
"method",
"for",
"RPC",
".",
"Must",
"be",
"used",
"a",
"RemoteControllerDeamon",
"(",
"-",
"derived",
")",
"class",
"method!"
] | train | https://github.com/voidpp/python-web-tools/blob/3987aafb5dc8ded39c540353b2461a7570e7dc92/voidpp_web_tools/remote_controller_daemon.py#L13-L55 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.