repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
Othernet-Project/conz | conz/console.py | Console.pwa | python | def pwa(self, val, wa='WARN'):
self.pstd(self.color.yellow('{}: {}'.format(val, wa))) | Print val: WARN in yellow on STDOUT | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L87-L89 | [
"def pstd(self, *args, **kwargs):\n \"\"\" Console to STDOUT \"\"\"\n kwargs['file'] = self.out\n self.print(*args, **kwargs)\n sys.stdout.flush()\n"
] | class Console:
"""
Wrapper around print with helper methods that cover typical ``print()``
usage in console programs.
"""
ProgressEnd = progress.ProgressEnd
ProgressOK = progress.ProgressOK
ProgressAbrt = progress.ProgressAbrt
color = ansi_colors.color
def __init__(self, verbose=F... |
Othernet-Project/conz | conz/console.py | Console.pverb | python | def pverb(self, *args, **kwargs):
if not self.verbose:
return
self.pstd(*args, **kwargs) | Console verbose message to STDOUT | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L95-L99 | [
"def pstd(self, *args, **kwargs):\n \"\"\" Console to STDOUT \"\"\"\n kwargs['file'] = self.out\n self.print(*args, **kwargs)\n sys.stdout.flush()\n"
] | class Console:
"""
Wrapper around print with helper methods that cover typical ``print()``
usage in console programs.
"""
ProgressEnd = progress.ProgressEnd
ProgressOK = progress.ProgressOK
ProgressAbrt = progress.ProgressAbrt
color = ansi_colors.color
def __init__(self, verbose=F... |
Othernet-Project/conz | conz/console.py | Console.read | python | def read(self, prompt='', clean=lambda x: x):
ans = read(prompt + ' ')
return clean(ans) | Display a prompt and ask user for input
A function to clean the user input can be passed as ``clean`` argument.
This function takes a single value, which is the string user entered,
and returns a cleaned value. Default is a pass-through function, which
is an equivalent of::
... | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L104-L116 | [
"def safeint(s):\n \"\"\" Convert the string to int without raising errors \"\"\"\n try:\n return int(s.strip())\n except (TypeError, ValueError):\n return None\n",
"def read(self, prompt='', clean=lambda x: x):\n",
"validator=lambda x: x != '', clean=lambda x: x.strip(),\n"
] | class Console:
"""
Wrapper around print with helper methods that cover typical ``print()``
usage in console programs.
"""
ProgressEnd = progress.ProgressEnd
ProgressOK = progress.ProgressOK
ProgressAbrt = progress.ProgressAbrt
color = ansi_colors.color
def __init__(self, verbose=F... |
Othernet-Project/conz | conz/console.py | Console.rvpl | python | def rvpl(self, prompt, error='Entered value is invalid', intro=None,
validator=lambda x: x != '', clean=lambda x: x.strip(),
strict=True, default=None):
if intro:
self.pstd(utils.rewrap_long(intro))
val = self.read(prompt, clean)
while not validator(val):
... | Start a read-validate-print loop
The RVPL will read the user input, validate it, and loop until the
entered value passes the validation, then return it.
Error message can be customized using the ``error`` argument. If the
value is a callable, it will be called with the value and it wil... | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L118-L150 | [
"validator=lambda x: x > 12)\n",
"validator=lambda x: x > 12, strict=False, default=15)\n",
"def rewrap_long(s, width=COLS):\n \"\"\" Rewrap longer texts with paragraph breaks (two consecutive LF) \"\"\"\n paras = s.split('\\n\\n')\n return '\\n\\n'.join(rewrap(p) for p in paras)\n",
"def pstd(self, ... | class Console:
"""
Wrapper around print with helper methods that cover typical ``print()``
usage in console programs.
"""
ProgressEnd = progress.ProgressEnd
ProgressOK = progress.ProgressOK
ProgressAbrt = progress.ProgressAbrt
color = ansi_colors.color
def __init__(self, verbose=F... |
Othernet-Project/conz | conz/console.py | Console.yesno | python | def yesno(self, prompt, error='Please type either y or n', intro=None,
default=None):
if default is None:
prompt += ' (y/n):'
else:
if default is True:
prompt += ' (Y/n):'
default = 'y'
if default is False:
... | Ask user for yes or no answer
The prompt will include a typical '(y/n):' at the end. Depending on
whether ``default`` was specified, this may also be '(Y/n):' or
'(y/N):'.
The ``default`` argument can be ``True`` or ``False``, with meaning of
'yes' and 'no' respectively. Defaul... | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L152-L181 | [
"def rvpl(self, prompt, error='Entered value is invalid', intro=None,\n validator=lambda x: x != '', clean=lambda x: x.strip(),\n strict=True, default=None):\n \"\"\" Start a read-validate-print loop\n\n The RVPL will read the user input, validate it, and loop until the\n entered value pass... | class Console:
"""
Wrapper around print with helper methods that cover typical ``print()``
usage in console programs.
"""
ProgressEnd = progress.ProgressEnd
ProgressOK = progress.ProgressOK
ProgressAbrt = progress.ProgressAbrt
color = ansi_colors.color
def __init__(self, verbose=F... |
Othernet-Project/conz | conz/console.py | Console.menu | python | def menu(self, choices, prompt='Please choose from the provided options:',
error='Invalid choice', intro=None, strict=True, default=None,
numerator=lambda x: [i + 1 for i in range(x)],
formatter=lambda x, y: '{0:>3}) {1}'.format(x, y),
clean=utils.safeint):
nu... | Print a menu
The choices must be an iterable of two-tuples where the first value is
the value of the menu item, and the second is the label for that
matches the value.
The menu will be printed with numeric choices. For example::
1) foo
2) bar
Formattin... | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L183-L239 | [
"numerator = lambda n: ['abcd'[i] for i in range(n)]\n",
"formatter = lambda i, l: '[{}] {}'.format(i, l)\n",
"def rewrap_long(s, width=COLS):\n \"\"\" Rewrap longer texts with paragraph breaks (two consecutive LF) \"\"\"\n paras = s.split('\\n\\n')\n return '\\n\\n'.join(rewrap(p) for p in paras)\n",
... | class Console:
"""
Wrapper around print with helper methods that cover typical ``print()``
usage in console programs.
"""
ProgressEnd = progress.ProgressEnd
ProgressOK = progress.ProgressOK
ProgressAbrt = progress.ProgressAbrt
color = ansi_colors.color
def __init__(self, verbose=F... |
Othernet-Project/conz | conz/console.py | Console.readpipe | python | def readpipe(self, chunk=None):
read = []
while True:
l = sys.stdin.readline()
if not l:
if read:
yield read
return
return
if not chunk:
yield l
else:
r... | Return iterator that iterates over STDIN line by line
If ``chunk`` is set to a positive non-zero integer value, then the
reads are performed in chunks of that many lines, and returned as a
list. Otherwise the lines are returned one by one. | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L241-L261 | null | class Console:
"""
Wrapper around print with helper methods that cover typical ``print()``
usage in console programs.
"""
ProgressEnd = progress.ProgressEnd
ProgressOK = progress.ProgressOK
ProgressAbrt = progress.ProgressAbrt
color = ansi_colors.color
def __init__(self, verbose=F... |
Othernet-Project/conz | conz/console.py | Console.error | python | def error(self, msg='Program error: {err}', exit=None):
def handler(exc):
if msg:
self.perr(msg.format(err=exc))
if exit is not None:
self.quit(exit)
return handler | Error handler factory
This function takes a message with optional ``{err}`` placeholder and
returns a function that takes an exception object, prints the error
message to STDERR and optionally quits.
If no message is supplied (e.g., passing ``None`` or ``False`` or empty
string... | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L282-L304 | null | class Console:
"""
Wrapper around print with helper methods that cover typical ``print()``
usage in console programs.
"""
ProgressEnd = progress.ProgressEnd
ProgressOK = progress.ProgressOK
ProgressAbrt = progress.ProgressAbrt
color = ansi_colors.color
def __init__(self, verbose=F... |
Othernet-Project/conz | conz/console.py | Console.progress | python | def progress(self, msg, onerror=None, sep='...', end='DONE', abrt='FAIL',
prog='.', excs=(Exception,), reraise=True):
if not onerror:
onerror = self.error()
if type(onerror) is str:
onerror = self.error(msg=onerror)
self.pverb(msg, end=sep)
prog =... | Context manager for handling interactive prog indication
This context manager streamlines presenting banners and prog
indicators. To start the prog, pass ``msg`` argument as a start
message. For example::
printer = Console(verbose=True)
with printer.progress('Checking f... | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L307-L369 | [
"def pverb(self, *args, **kwargs):\n \"\"\" Console verbose message to STDOUT \"\"\"\n if not self.verbose:\n return\n self.pstd(*args, **kwargs)\n",
"def error(self, msg='Program error: {err}', exit=None):\n \"\"\" Error handler factory\n\n This function takes a message with optional ``{err... | class Console:
"""
Wrapper around print with helper methods that cover typical ``print()``
usage in console programs.
"""
ProgressEnd = progress.ProgressEnd
ProgressOK = progress.ProgressOK
ProgressAbrt = progress.ProgressAbrt
color = ansi_colors.color
def __init__(self, verbose=F... |
Othernet-Project/conz | conz/progress.py | Progress.end | python | def end(self, s=None, post=None, noraise=False):
s = s or self.end_msg
self.printer(self.color.green(s))
if post:
post()
if noraise:
return
raise ProgressOK() | Prints the end banner and raises ``ProgressOK`` exception
When ``noraise`` flag is set to ``True``, then the exception is not
raised, and progress is allowed to continue.
If ``post`` function is supplied it is invoked with no arguments after
the close banner is printed, but before exce... | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/progress.py#L55-L71 | [
"def pverb(self, *args, **kwargs):\n \"\"\" Console verbose message to STDOUT \"\"\"\n if not self.verbose:\n return\n self.pstd(*args, **kwargs)\n"
] | class Progress:
"""
Wrapper that manages step progress
"""
color = ansi_colors.color
def __init__(self, printer, end='DONE', abrt='FAIL', prog='.'):
"""
The ``Console`` method to be used is specified using the ``printer``
argument.
``end`` argument specified the pr... |
Othernet-Project/conz | conz/progress.py | Progress.abrt | python | def abrt(self, s=None, post=None, noraise=False):
s = s or self.abrt_msg
self.printer(self.color.red(s))
if post:
post()
if noraise:
return
raise ProgressAbrt() | Prints the abrt banner and raises ``ProgressAbrt`` exception
When ``noraise`` flag is set to ``True``, then the exception is not
raised, and progress is allowed to continue.
If ``post`` function is supplied it is invoked with no arguments after
the close banner is printed, but before e... | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/progress.py#L73-L89 | [
"def pverb(self, *args, **kwargs):\n \"\"\" Console verbose message to STDOUT \"\"\"\n if not self.verbose:\n return\n self.pstd(*args, **kwargs)\n"
] | class Progress:
"""
Wrapper that manages step progress
"""
color = ansi_colors.color
def __init__(self, printer, end='DONE', abrt='FAIL', prog='.'):
"""
The ``Console`` method to be used is specified using the ``printer``
argument.
``end`` argument specified the pr... |
Othernet-Project/conz | conz/progress.py | Progress.prog | python | def prog(self, s=None):
s = s or self.prog_msg
self.printer(s, end='') | Prints the progress indicator | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/progress.py#L91-L94 | null | class Progress:
"""
Wrapper that manages step progress
"""
color = ansi_colors.color
def __init__(self, printer, end='DONE', abrt='FAIL', prog='.'):
"""
The ``Console`` method to be used is specified using the ``printer``
argument.
``end`` argument specified the pr... |
Othernet-Project/conz | conz/utils.py | rewrap | python | def rewrap(s, width=COLS):
s = ' '.join([l.strip() for l in s.strip().split('\n')])
return '\n'.join(textwrap.wrap(s, width)) | Join all lines from input string and wrap it at specified width | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/utils.py#L17-L20 | null | """
Misc utility functions
Copyright 2015, Outernet Inc.
Some rights reserved.
This software is free software licensed under the terms of GPLv3. See COPYING
file that comes with the source code, or http://www.gnu.org/licenses/gpl.txt.
"""
import os
import textwrap
COLS = os.getenv('COLUMNS', 79)
def rewrap_long(... |
Othernet-Project/conz | conz/utils.py | rewrap_long | python | def rewrap_long(s, width=COLS):
paras = s.split('\n\n')
return '\n\n'.join(rewrap(p) for p in paras) | Rewrap longer texts with paragraph breaks (two consecutive LF) | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/utils.py#L23-L26 | null | """
Misc utility functions
Copyright 2015, Outernet Inc.
Some rights reserved.
This software is free software licensed under the terms of GPLv3. See COPYING
file that comes with the source code, or http://www.gnu.org/licenses/gpl.txt.
"""
import os
import textwrap
COLS = os.getenv('COLUMNS', 79)
def rewrap(s, wid... |
dustinmm80/healthy | pylint_runner.py | score | python | def score(package_path):
python_files = find_files(package_path, '*.py')
total_counter = Counter()
for python_file in python_files:
output = run_pylint(python_file)
counter = parse_pylint_output(output)
total_counter += counter
score_value = 0
for count, stat in enumerate... | Runs pylint on a package and returns a score
Lower score is better
:param package_path: path of the package to score
:return: number of score | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/pylint_runner.py#L22-L44 | [
"def find_files(directory, pattern):\n \"\"\"\n Recusively finds files in a directory re\n :param directory: base directory\n :param pattern: wildcard pattern\n :return: generator with filenames matching pattern\n \"\"\"\n for root, __, files in os.walk(directory):\n for basename in file... | #! /usr/bin/env python
# coding=utf-8
"""
Utilities for fetching and unpacking packages from pypi
"""
from collections import Counter
import fnmatch
import os
from pylint.lint import Run
from pylint.reporters.text import TextReporter
SCORING_VALUES = {
'F': 5,
'E': 4,
'W': 3,
'R': 2,
'C': 1
}
d... |
dustinmm80/healthy | pylint_runner.py | parse_pylint_output | python | def parse_pylint_output(output):
stripped_output = [x[0] for x in output]
counter = Counter(stripped_output)
return counter | Parses pylint output, counting number of errors, conventions, etc
:param output: output list generated by run_pylint()
:return: | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/pylint_runner.py#L46-L57 | null | #! /usr/bin/env python
# coding=utf-8
"""
Utilities for fetching and unpacking packages from pypi
"""
from collections import Counter
import fnmatch
import os
from pylint.lint import Run
from pylint.reporters.text import TextReporter
SCORING_VALUES = {
'F': 5,
'E': 4,
'W': 3,
'R': 2,
'C': 1
}
de... |
dustinmm80/healthy | pylint_runner.py | run_pylint | python | def run_pylint(filename):
ARGS = [
'-r',
'n'
]
pylint_output = WritableObject()
Run([filename]+ARGS, reporter=TextReporter(pylint_output), exit=False)
lines = []
for line in pylint_output.read():
if not line.startswith('*') and line != '\n':
lines.append(line... | Runs pylint on a given file
:param filename:
:return: list of pylint errors | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/pylint_runner.py#L72-L90 | [
"def read(self):\n \"dummy read\"\n return self.content\n"
] | #! /usr/bin/env python
# coding=utf-8
"""
Utilities for fetching and unpacking packages from pypi
"""
from collections import Counter
import fnmatch
import os
from pylint.lint import Run
from pylint.reporters.text import TextReporter
SCORING_VALUES = {
'F': 5,
'E': 4,
'W': 3,
'R': 2,
'C': 1
}
de... |
dustinmm80/healthy | pylint_runner.py | find_files | python | def find_files(directory, pattern):
for root, __, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
filename = os.path.join(root, basename)
yield filename | Recusively finds files in a directory re
:param directory: base directory
:param pattern: wildcard pattern
:return: generator with filenames matching pattern | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/pylint_runner.py#L92-L103 | null | #! /usr/bin/env python
# coding=utf-8
"""
Utilities for fetching and unpacking packages from pypi
"""
from collections import Counter
import fnmatch
import os
from pylint.lint import Run
from pylint.reporters.text import TextReporter
SCORING_VALUES = {
'F': 5,
'E': 4,
'W': 3,
'R': 2,
'C': 1
}
de... |
dustinmm80/healthy | checks.py | check_license | python | def check_license(package_info, *args):
classifiers = package_info.get('classifiers')
reason = "No License"
result = False
if len([c for c in classifiers if c.startswith('License ::')]) > 0:
result = True
return result, reason, HAS_LICENSE | Does the package have a license classifier?
:param package_info: package_info dictionary
:return: Tuple (is the condition True or False?, reason if it is False else None, score to be applied) | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/checks.py#L33-L46 | null | #! /usr/bin/env python
# coding=utf-8
"""
checks.py
Check functions that healthy employs to generate a score
"""
from datetime import datetime, timedelta
DAYS_STALE = 180 # number of days without update that a package is considered 'stale'
# Points
HAS_LICENSE = 20
HAS_RELEASE_FILES = 30
NOT_STAL... |
dustinmm80/healthy | checks.py | check_homepage | python | def check_homepage(package_info, *args):
reason = "Home page missing"
result = False
if package_info.get('home_page') not in BAD_VALUES:
result = True
return result, reason, HAS_HOMEPAGE | Does the package have a homepage listed?
:param package_info: package_info dictionary
:return: Tuple (is the condition True or False?, reason if it is False else None) | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/checks.py#L49-L61 | null | #! /usr/bin/env python
# coding=utf-8
"""
checks.py
Check functions that healthy employs to generate a score
"""
from datetime import datetime, timedelta
DAYS_STALE = 180 # number of days without update that a package is considered 'stale'
# Points
HAS_LICENSE = 20
HAS_RELEASE_FILES = 30
NOT_STAL... |
dustinmm80/healthy | checks.py | check_summary | python | def check_summary(package_info, *args):
reason = "Summary missing"
result = False
if package_info.get('summary') not in BAD_VALUES:
result = True
return result, reason, HAS_SUMMARY | Does the package have a summary listed?
:param package_info: package_info dictionary
:return: Tuple (is the condition True or False?, reason if it is False else None) | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/checks.py#L64-L76 | null | #! /usr/bin/env python
# coding=utf-8
"""
checks.py
Check functions that healthy employs to generate a score
"""
from datetime import datetime, timedelta
DAYS_STALE = 180 # number of days without update that a package is considered 'stale'
# Points
HAS_LICENSE = 20
HAS_RELEASE_FILES = 30
NOT_STAL... |
dustinmm80/healthy | checks.py | check_description | python | def check_description(package_info, *args):
reason = "Description missing"
result = False
if package_info.get('description') not in BAD_VALUES:
result = True
return result, reason, HAS_DESCRIPTION | Does the package have a description listed?
:param package_info: package_info dictionary
:return: Tuple (is the condition True or False?, reason if it is False else None) | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/checks.py#L79-L91 | null | #! /usr/bin/env python
# coding=utf-8
"""
checks.py
Check functions that healthy employs to generate a score
"""
from datetime import datetime, timedelta
DAYS_STALE = 180 # number of days without update that a package is considered 'stale'
# Points
HAS_LICENSE = 20
HAS_RELEASE_FILES = 30
NOT_STAL... |
dustinmm80/healthy | checks.py | check_python_classifiers | python | def check_python_classifiers(package_info, *args):
classifiers = package_info.get('classifiers')
reason = "Python classifiers missing"
result = False
if len([c for c in classifiers if c.startswith('Programming Language :: Python ::')]) > 0:
result = True
return result, reason, HAS_PYTHON_C... | Does the package have Python classifiers?
:param package_info: package_info dictionary
:return: Tuple (is the condition True or False?, reason if it is False else None, score to be applied) | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/checks.py#L94-L107 | null | #! /usr/bin/env python
# coding=utf-8
"""
checks.py
Check functions that healthy employs to generate a score
"""
from datetime import datetime, timedelta
DAYS_STALE = 180 # number of days without update that a package is considered 'stale'
# Points
HAS_LICENSE = 20
HAS_RELEASE_FILES = 30
NOT_STAL... |
dustinmm80/healthy | checks.py | check_author_info | python | def check_author_info(package_info, *args):
reason = "Author name or email missing"
result = False
if package_info.get('author') not in BAD_VALUES or package_info.get('author_email') not in BAD_VALUES:
result = True
return result, reason, HAS_AUTHOR_INFO | Does the package have author information listed?
:param package_info: package_info dictionary
:return: Tuple (is the condition True or False?, reason if it is False else None) | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/checks.py#L110-L122 | null | #! /usr/bin/env python
# coding=utf-8
"""
checks.py
Check functions that healthy employs to generate a score
"""
from datetime import datetime, timedelta
DAYS_STALE = 180 # number of days without update that a package is considered 'stale'
# Points
HAS_LICENSE = 20
HAS_RELEASE_FILES = 30
NOT_STAL... |
dustinmm80/healthy | checks.py | check_release_files | python | def check_release_files(package_info, *args):
reason = "No release files uploaded"
result = False
release_urls = args[0]
if len(release_urls) > 0:
result = True
return result, reason, HAS_RELEASE_FILES | Does the package have release files?
:param package_info: package_info dictionary
:return: Tuple (is the condition True or False?, reason if it is False else None) | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/checks.py#L125-L138 | null | #! /usr/bin/env python
# coding=utf-8
"""
checks.py
Check functions that healthy employs to generate a score
"""
from datetime import datetime, timedelta
DAYS_STALE = 180 # number of days without update that a package is considered 'stale'
# Points
HAS_LICENSE = 20
HAS_RELEASE_FILES = 30
NOT_STAL... |
dustinmm80/healthy | checks.py | check_stale | python | def check_stale(package_info, *args):
reason = 'Package not updated in {} days'.format(DAYS_STALE)
result = False
now = datetime.utcnow()
release_urls = args[0]
if len(release_urls) > 0:
package_uploaded_time = release_urls[0]['upload_time']
if now - timedelta(days=DAYS_STALE) <= p... | Is the package stale?
:param package_info: package_info dictionary
:return: Tuple (is the condition True or False?, reason if it is False else None) | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/checks.py#L141-L158 | null | #! /usr/bin/env python
# coding=utf-8
"""
checks.py
Check functions that healthy employs to generate a score
"""
from datetime import datetime, timedelta
DAYS_STALE = 180 # number of days without update that a package is considered 'stale'
# Points
HAS_LICENSE = 20
HAS_RELEASE_FILES = 30
NOT_STAL... |
dustinmm80/healthy | healthy.py | calculate_health | python | def calculate_health(package_name, package_version=None, verbose=False, no_output=False):
total_score = 0
reasons = []
package_releases = CLIENT.package_releases(package_name)
if not package_releases:
if not no_output:
print(TERMINAL.red('{} is not listed on pypi'.format(package_nam... | Calculates the health of a package, based on several factors
:param package_name: name of package on pypi.python.org
:param package_version: version number of package to check, optional - defaults to latest version
:param verbose: flag to print out reasons
:param no_output: print no output
:param l... | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/healthy.py#L34-L104 | [
"def get_health_color(score):\n \"\"\"\n Returns a color based on the health score\n :param score: integer from 0 - 100 representing health\n :return: string of color to apply in terminal\n \"\"\"\n color = TERMINAL.green\n\n if score <= 80:\n color = TERMINAL.yellow\n elif score <= 6... | #! /usr/bin/env python
# coding=utf-8
"""
healthy.py
Checks the health of a Python package, based on it's Pypi information
"""
import argparse
import os
import checks
try:
# Different location in Python 3
from xmlrpc.client import ServerProxy
except ImportError:
from xmlrpclib import ServerProxy
try:
... |
dustinmm80/healthy | healthy.py | get_health_color | python | def get_health_color(score):
color = TERMINAL.green
if score <= 80:
color = TERMINAL.yellow
elif score <= 60:
color = TERMINAL.orange
elif score <= 40:
color = TERMINAL.red
return color | Returns a color based on the health score
:param score: integer from 0 - 100 representing health
:return: string of color to apply in terminal | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/healthy.py#L119-L134 | null | #! /usr/bin/env python
# coding=utf-8
"""
healthy.py
Checks the health of a Python package, based on it's Pypi information
"""
import argparse
import os
import checks
try:
# Different location in Python 3
from xmlrpc.client import ServerProxy
except ImportError:
from xmlrpclib import ServerProxy
try:
... |
dustinmm80/healthy | healthy.py | main | python | def main():
parser = argparse.ArgumentParser('Determines the health of a package')
parser.add_argument(
'package_name',
help='Name of package listed on pypi.python.org',
)
parser.add_argument(
'package_version', nargs='?',
help='Version of package to check',
)
... | Parses user input for a package name
:return: | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/healthy.py#L136-L167 | [
"def calculate_health(package_name, package_version=None, verbose=False, no_output=False):\n \"\"\"\n Calculates the health of a package, based on several factors\n\n :param package_name: name of package on pypi.python.org\n :param package_version: version number of package to check, optional - defaults... | #! /usr/bin/env python
# coding=utf-8
"""
healthy.py
Checks the health of a Python package, based on it's Pypi information
"""
import argparse
import os
import checks
try:
# Different location in Python 3
from xmlrpc.client import ServerProxy
except ImportError:
from xmlrpclib import ServerProxy
try:
... |
dustinmm80/healthy | package_utils.py | create_sandbox | python | def create_sandbox(name='healthybox'):
sandbox = tempfile.mkdtemp(prefix=name)
if not os.path.isdir(sandbox):
os.mkdir(sandbox)
return sandbox | Create a temporary sandbox directory
:param name: name of the directory to create
:return: The directory created | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/package_utils.py#L14-L24 | null | #! /usr/bin/env python
# coding=utf-8
"""
Utilities for fetching and unpacking packages from pypi
"""
import os
import shutil
import tarfile
import tempfile
import requests
def download_package_to_sandbox(sandbox, package_url):
"""
Downloads an unzips a package to the sandbox
:param sandbox: temporary di... |
dustinmm80/healthy | package_utils.py | download_package_to_sandbox | python | def download_package_to_sandbox(sandbox, package_url):
response = requests.get(package_url)
package_tar = os.path.join(sandbox, 'package.tar.gz')
with open(package_tar, 'w') as f:
f.write(response.content)
os.chdir(sandbox)
with tarfile.open('package.tar.gz', 'r:gz') as tf:
tf.e... | Downloads an unzips a package to the sandbox
:param sandbox: temporary directory name
:param package_url: link to package download
:returns: name of unzipped package directory | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/package_utils.py#L26-L48 | null | #! /usr/bin/env python
# coding=utf-8
"""
Utilities for fetching and unpacking packages from pypi
"""
import os
import shutil
import tarfile
import tempfile
import requests
def create_sandbox(name='healthybox'):
"""
Create a temporary sandbox directory
:param name: name of the directory to create
:re... |
dustinmm80/healthy | package_utils.py | main | python | def main():
sandbox = create_sandbox()
directory = download_package_to_sandbox(
sandbox,
'https://pypi.python.org/packages/source/c/checkmyreqs/checkmyreqs-0.1.6.tar.gz'
)
print(directory)
destroy_sandbox(sandbox) | Main function for this module | train | https://github.com/dustinmm80/healthy/blob/b59016c3f578ca45b6ce857a2d5c4584b8542288/package_utils.py#L60-L70 | [
"def create_sandbox(name='healthybox'):\n \"\"\"\n Create a temporary sandbox directory\n :param name: name of the directory to create\n :return: The directory created\n \"\"\"\n sandbox = tempfile.mkdtemp(prefix=name)\n if not os.path.isdir(sandbox):\n os.mkdir(sandbox)\n\n return sa... | #! /usr/bin/env python
# coding=utf-8
"""
Utilities for fetching and unpacking packages from pypi
"""
import os
import shutil
import tarfile
import tempfile
import requests
def create_sandbox(name='healthybox'):
"""
Create a temporary sandbox directory
:param name: name of the directory to create
:re... |
Sean1708/HipPy | hippy/compiler.py | Compiler.compile | python | def compile(self):
if self.buffer is None:
self.buffer = self._compile_value(self.data, 0)
return self.buffer.strip() | Return Hip string if already compiled else compile it. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/compiler.py#L15-L20 | [
"def _compile_value(self, data, indent_level):\n \"\"\"Dispatch to correct compilation method.\"\"\"\n if isinstance(data, dict):\n return self._compile_key_val(data, indent_level)\n elif isinstance(data, list):\n return self._compile_list(data, indent_level)\n else:\n return self._... | class Compiler:
"""Compiles data structure into a Hip serialized string."""
def __init__(self, data, indent=4):
"""Set the data structure."""
self.data = data
self.buffer = None
self._indent = ' '*indent if indent > 0 else '\t'
def _compile_value(self, data, indent_level)... |
Sean1708/HipPy | hippy/compiler.py | Compiler._compile_value | python | def _compile_value(self, data, indent_level):
if isinstance(data, dict):
return self._compile_key_val(data, indent_level)
elif isinstance(data, list):
return self._compile_list(data, indent_level)
else:
return self._compile_literal(data) | Dispatch to correct compilation method. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/compiler.py#L22-L29 | [
"def _compile_literal(self, data):\n \"\"\"Write correct representation of literal.\"\"\"\n if data is None:\n return 'nil'\n elif data is True:\n return 'yes'\n elif data is False:\n return 'no'\n else:\n return repr(data)\n",
"def _compile_list(self, data, indent_level... | class Compiler:
"""Compiles data structure into a Hip serialized string."""
def __init__(self, data, indent=4):
"""Set the data structure."""
self.data = data
self.buffer = None
self._indent = ' '*indent if indent > 0 else '\t'
def compile(self):
"""Return Hip stri... |
Sean1708/HipPy | hippy/compiler.py | Compiler._compile_literal | python | def _compile_literal(self, data):
if data is None:
return 'nil'
elif data is True:
return 'yes'
elif data is False:
return 'no'
else:
return repr(data) | Write correct representation of literal. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/compiler.py#L31-L40 | null | class Compiler:
"""Compiles data structure into a Hip serialized string."""
def __init__(self, data, indent=4):
"""Set the data structure."""
self.data = data
self.buffer = None
self._indent = ' '*indent if indent > 0 else '\t'
def compile(self):
"""Return Hip stri... |
Sean1708/HipPy | hippy/compiler.py | Compiler._compile_list | python | def _compile_list(self, data, indent_level):
if len(data) == 0:
return '--'
elif not any(isinstance(i, (dict, list)) for i in data):
return ', '.join(self._compile_literal(value) for value in data)
else:
# 'ere be dragons,
# granted there are fewer... | Correctly write possibly nested list. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/compiler.py#L42-L80 | null | class Compiler:
"""Compiles data structure into a Hip serialized string."""
def __init__(self, data, indent=4):
"""Set the data structure."""
self.data = data
self.buffer = None
self._indent = ' '*indent if indent > 0 else '\t'
def compile(self):
"""Return Hip stri... |
Sean1708/HipPy | hippy/compiler.py | Compiler._compile_key_val | python | def _compile_key_val(self, data, indent_level):
buffer = ''
for (key, val) in data.items():
buffer += self._indent * indent_level
# TODO: assumes key is a string
buffer += key + ':'
if isinstance(val, dict):
buffer += '\n'
... | Compile a dictionary. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/compiler.py#L82-L103 | null | class Compiler:
"""Compiles data structure into a Hip serialized string."""
def __init__(self, data, indent=4):
"""Set the data structure."""
self.data = data
self.buffer = None
self._indent = ' '*indent if indent > 0 else '\t'
def compile(self):
"""Return Hip stri... |
Sean1708/HipPy | hippy/__init__.py | write | python | def write(file_name, data):
with open(file_name, 'w') as f:
f.write(encode(data)) | Encode and write a Hip file. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/__init__.py#L21-L24 | [
"def encode(data):\n \"\"\"Encode data structure into a Hip serialized string.\"\"\"\n return compiler.Compiler(data).compile()\n"
] | """Python parser for reading Hip data files."""
from . import lexer, parser, compiler
def encode(data):
"""Encode data structure into a Hip serialized string."""
return compiler.Compiler(data).compile()
def decode(string):
"""Decode a Hip serialized string into a data structure."""
return parser.Par... |
Sean1708/HipPy | hippy/lexer.py | tokenize_number | python | def tokenize_number(val, line):
try:
num = int(val)
typ = TokenType.int
except ValueError:
num = float(val)
typ = TokenType.float
return {'type': typ, 'value': num, 'line': line} | Parse val correctly into int or float. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/lexer.py#L43-L52 | null | """Contains the Lexer and Token classes responsible for tokenizing the file.
Also does stuff.
"""
import re
import ast
import enum
from .error import Error
class LexError(Error):
"""Raised when the lexer encounters an error."""
def __init__(self, line, char):
"""Set the line and character which cau... |
Sean1708/HipPy | hippy/parser.py | Parser.data | python | def data(self):
if self._data is None:
# reset after possible parsing failure
self.__init__(self.tokens)
return self._parse()
else:
return self._data | Return parsed data structure. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L47-L54 | [
"def __init__(self, tokens):\n \"\"\"Initialize tokens excluding comments.\"\"\"\n self.tokens = [t for t in tokens if t['type'] is not TT.comment]\n self.num_tokens = len(self.tokens)\n self._cur_position = 0\n self._finished = False\n self._data = None\n self._literals = (TT.str, TT.int, TT.f... | class Parser:
"""Parses an iterable of tokens into a data structure."""
# .==. .==.
# //`^\\ //^`\\
# // ^ ^\(\__/)/^ ^^\\
# //^ ^^ ^/6 6\ ^^ ^ \\
# //^ ^^ ^/( .. )\^ ^ ^ \\
# // ^^ ^/\| v""v |/\^ ^ ^\\
# // ^^/\/ / `~~` \ \/\^ ^\\
# ------------... |
Sean1708/HipPy | hippy/parser.py | Parser._increment | python | def _increment(self, n=1):
if self._cur_position >= self.num_tokens-1:
self._cur_positon = self.num_tokens - 1
self._finished = True
else:
self._cur_position += n | Move forward n tokens in the stream. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L71-L77 | null | class Parser:
"""Parses an iterable of tokens into a data structure."""
# .==. .==.
# //`^\\ //^`\\
# // ^ ^\(\__/)/^ ^^\\
# //^ ^^ ^/6 6\ ^^ ^ \\
# //^ ^^ ^/( .. )\^ ^ ^ \\
# // ^^ ^/\| v""v |/\^ ^ ^\\
# // ^^/\/ / `~~` \ \/\^ ^\\
# ------------... |
Sean1708/HipPy | hippy/parser.py | Parser._skip_whitespace | python | def _skip_whitespace(self):
i = 0
while self._cur_token['type'] is TT.ws and not self._finished:
self._increment()
i += 1
return i | Increment over whitespace, counting characters. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L79-L86 | null | class Parser:
"""Parses an iterable of tokens into a data structure."""
# .==. .==.
# //`^\\ //^`\\
# // ^ ^\(\__/)/^ ^^\\
# //^ ^^ ^/6 6\ ^^ ^ \\
# //^ ^^ ^/( .. )\^ ^ ^ \\
# // ^^ ^/\| v""v |/\^ ^ ^\\
# // ^^/\/ / `~~` \ \/\^ ^\\
# ------------... |
Sean1708/HipPy | hippy/parser.py | Parser._skip_newlines | python | def _skip_newlines(self):
while self._cur_token['type'] is TT.lbreak and not self._finished:
self._increment() | Increment over newlines. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L88-L91 | null | class Parser:
"""Parses an iterable of tokens into a data structure."""
# .==. .==.
# //`^\\ //^`\\
# // ^ ^\(\__/)/^ ^^\\
# //^ ^^ ^/6 6\ ^^ ^ \\
# //^ ^^ ^/( .. )\^ ^ ^ \\
# // ^^ ^/\| v""v |/\^ ^ ^\\
# // ^^/\/ / `~~` \ \/\^ ^\\
# ------------... |
Sean1708/HipPy | hippy/parser.py | Parser._parse | python | def _parse(self):
while self._cur_token['type'] in (TT.ws, TT.lbreak):
self._skip_whitespace()
self._skip_newlines()
self._data = self._parse_value()
return self._data | Parse the token stream into a nice dictionary data structure. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L93-L101 | [
"def _skip_whitespace(self):\n \"\"\"Increment over whitespace, counting characters.\"\"\"\n i = 0\n while self._cur_token['type'] is TT.ws and not self._finished:\n self._increment()\n i += 1\n\n return i\n",
"def _skip_newlines(self):\n \"\"\"Increment over newlines.\"\"\"\n whil... | class Parser:
"""Parses an iterable of tokens into a data structure."""
# .==. .==.
# //`^\\ //^`\\
# // ^ ^\(\__/)/^ ^^\\
# //^ ^^ ^/6 6\ ^^ ^ \\
# //^ ^^ ^/( .. )\^ ^ ^ \\
# // ^^ ^/\| v""v |/\^ ^ ^\\
# // ^^/\/ / `~~` \ \/\^ ^\\
# ------------... |
Sean1708/HipPy | hippy/parser.py | Parser._parse_value | python | def _parse_value(self):
indent = 0
while self._cur_token['type'] is TT.ws:
indent = self._skip_whitespace()
self._skip_newlines()
if self._cur_token['type'] is TT.id:
return self._parse_key(indent)
elif self._cur_token['type'] is TT.hyphen:
... | Parse the value of a key-value pair. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L103-L121 | null | class Parser:
"""Parses an iterable of tokens into a data structure."""
# .==. .==.
# //`^\\ //^`\\
# // ^ ^\(\__/)/^ ^^\\
# //^ ^^ ^/6 6\ ^^ ^ \\
# //^ ^^ ^/( .. )\^ ^ ^ \\
# // ^^ ^/\| v""v |/\^ ^ ^\\
# // ^^/\/ / `~~` \ \/\^ ^\\
# ------------... |
Sean1708/HipPy | hippy/parser.py | Parser._parse_key | python | def _parse_key(self, indent):
data = {}
new_indent = indent
while not self._finished and new_indent == indent:
self._skip_whitespace()
cur_token = self._cur_token
if cur_token['type'] is TT.id:
key = cur_token['value']
next_tok... | Parse a series of key-value pairs. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L123-L172 | null | class Parser:
"""Parses an iterable of tokens into a data structure."""
# .==. .==.
# //`^\\ //^`\\
# // ^ ^\(\__/)/^ ^^\\
# //^ ^^ ^/6 6\ ^^ ^ \\
# //^ ^^ ^/( .. )\^ ^ ^ \\
# // ^^ ^/\| v""v |/\^ ^ ^\\
# // ^^/\/ / `~~` \ \/\^ ^\\
# ------------... |
Sean1708/HipPy | hippy/parser.py | Parser._parse_object_list | python | def _parse_object_list(self):
array = []
indent = 0
while not self._finished:
self._skip_newlines()
if self._cur_token['type'] is TT.ws:
while self._cur_token['type'] is TT.ws:
indent = self._skip_whitespace()
self.... | Parse a list of data structures. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L174-L194 | null | class Parser:
"""Parses an iterable of tokens into a data structure."""
# .==. .==.
# //`^\\ //^`\\
# // ^ ^\(\__/)/^ ^^\\
# //^ ^^ ^/6 6\ ^^ ^ \\
# //^ ^^ ^/( .. )\^ ^ ^ \\
# // ^^ ^/\| v""v |/\^ ^ ^\\
# // ^^/\/ / `~~` \ \/\^ ^\\
# ------------... |
Sean1708/HipPy | hippy/parser.py | Parser._parse_literal_list | python | def _parse_literal_list(self, indent):
if self._cur_token['type'] not in self._literals:
raise Exception(
"Parser failed, _parse_literal_list was called on non-literal"
" {} on line {}.".format(
repr(self._cur_token['value']), self._cur_token['line... | Parse a list of literals. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L196-L237 | null | class Parser:
"""Parses an iterable of tokens into a data structure."""
# .==. .==.
# //`^\\ //^`\\
# // ^ ^\(\__/)/^ ^^\\
# //^ ^^ ^/6 6\ ^^ ^ \\
# //^ ^^ ^/( .. )\^ ^ ^ \\
# // ^^ ^/\| v""v |/\^ ^ ^\\
# // ^^/\/ / `~~` \ \/\^ ^\\
# ------------... |
Sean1708/HipPy | hippy/parser.py | Parser._parse_comma_list | python | def _parse_comma_list(self):
if self._cur_token['type'] not in self._literals:
raise Exception(
"Parser failed, _parse_comma_list was called on non-literal"
" {} on line {}.".format(
repr(self._cur_token['value']), self._cur_token['line']
... | Parse a comma seperated list. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L239-L263 | null | class Parser:
"""Parses an iterable of tokens into a data structure."""
# .==. .==.
# //`^\\ //^`\\
# // ^ ^\(\__/)/^ ^^\\
# //^ ^^ ^/6 6\ ^^ ^ \\
# //^ ^^ ^/( .. )\^ ^ ^ \\
# // ^^ ^/\| v""v |/\^ ^ ^\\
# // ^^/\/ / `~~` \ \/\^ ^\\
# ------------... |
Sean1708/HipPy | hippy/parser.py | Parser._parse_newline_list | python | def _parse_newline_list(self, indent):
if self._cur_token['type'] not in self._literals:
raise Exception(
"Parser failed, _parse_newline_list was called on non-literal"
" {} on line {}.".format(
repr(self._cur_token['value']), self._cur_token['line... | Parse a newline seperated list. | train | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/parser.py#L265-L330 | null | class Parser:
"""Parses an iterable of tokens into a data structure."""
# .==. .==.
# //`^\\ //^`\\
# // ^ ^\(\__/)/^ ^^\\
# //^ ^^ ^/6 6\ ^^ ^ \\
# //^ ^^ ^/( .. )\^ ^ ^ \\
# // ^^ ^/\| v""v |/\^ ^ ^\\
# // ^^/\/ / `~~` \ \/\^ ^\\
# ------------... |
wdbm/shijian | shijian.py | tail | python | def tail(
filepath = "log.txt",
lines = 50
):
try:
filepath = os.path.expanduser(os.path.expandvars(filepath))
if os.path.isfile(filepath):
text = subprocess.check_output(["tail", "-" + str(lines), filepath])
if text:
return text
els... | Return a specified number of last lines of a specified file. If there is an
error or the file does not exist, return False. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L657-L676 | null | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | convert_type_list_elements | python | def convert_type_list_elements(
list_object = None,
element_type = str
):
if element_type is str:
return [str(element) if not isinstance(element, list) else convert_type_list_elements(
list_object = element,
element_type = str
) for element in list_object] | Recursively convert all elements and all elements of all sublists of a list
to a specified type and return the new list. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L878-L890 | null | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | select_spread | python | def select_spread(
list_of_elements = None,
number_of_elements = None
):
if len(list_of_elements) <= number_of_elements:
return list_of_elements
if number_of_elements == 0:
return []
if number_of_elements == 1:
return [list_of_elements[int(round((len(list_of_elements) -... | This function returns the specified number of elements of a list spread
approximately evenly. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L997-L1015 | [
"def select_spread(\n list_of_elements = None,\n number_of_elements = None\n ):\n \"\"\"\n This function returns the specified number of elements of a list spread\n approximately evenly.\n \"\"\"\n if len(list_of_elements) <= number_of_elements:\n return list_of_elements\n if num... | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | split_list | python | def split_list(
list_object = None,
granularity = None
):
if granularity < 0:
raise Exception("negative granularity")
mean_length = len(list_object) / float(granularity)
split_list_object = []
last_length = float(0)
if len(list_object) > granularity:
while last_length < l... | This function splits a list into a specified number of lists. It returns a
list of lists that correspond to these parts. Negative numbers of parts are
not accepted and numbers of parts greater than the number of elements in the
list result in the maximum possible number of lists being returned. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1017-L1040 | null | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | ranges_edge_pairs | python | def ranges_edge_pairs(
extent = None,
range_length = None
):
number_of_ranges = int(math.ceil(extent / range_length))
return [
(
index * range_length + index,
min((index + 1) * range_length + index, extent)
)
for index in range(0, number_of_range... | Return the edges of ranges within an extent of some length. For example, to
separate 76 variables into groups of at most 20 variables, the ranges of the
variables could be 0 to 20, 21 to 41, 42 to 62 and 63 to 76. These range
edges could be returned by this function as a list of tuples:
>>> ranges_edge... | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1042-L1065 | null | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | ustr | python | def ustr(text):
if text is not None:
if sys.version_info >= (3, 0):
return str(text)
else:
return unicode(text)
else:
return text | Convert a string to Python 2 unicode or Python 3 string as appropriate to
the version of Python in use. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1231-L1242 | null | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | replace_contractions_with_full_words_and_replace_numbers_with_digits | python | def replace_contractions_with_full_words_and_replace_numbers_with_digits(
text = None,
remove_articles = True
):
words = text.split()
text_translated = ""
for word in words:
if remove_articles and word in ["a", "an", "the"]:
continue
contractions_expansions... | This function replaces contractions with full words and replaces numbers
with digits in specified text. There is the option to remove articles. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1362-L1499 | null | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | add_time_variables | python | def add_time_variables(df, reindex = True):
if not "datetime" in df.columns:
log.error("field datetime not found in DataFrame")
return False
df["datetime"] = pd.to_datetime(df["datetime"])
df["month"] = df["datetime"].dt.month
df["month_name"] = df["d... | Return a DataFrame with variables for weekday index, weekday name, timedelta
through day, fraction through day, hours through day and days through week
added, optionally with the index set to datetime and the variable `datetime`
removed. It is assumed that the variable `datetime` exists. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1578-L1611 | null | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | daily_plots | python | def daily_plots(
df,
variable,
renormalize = True,
plot = True,
scatter = False,
linestyle = "-",
linewidth = 1,
s = 1
):
if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]:
log.error("index is not datetime")
return False
... | Create daily plots of a variable in a DataFrame, optionally renormalized. It
is assumed that the DataFrame index is datetime. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1613-L1644 | null | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | weekly_plots | python | def weekly_plots(
df,
variable,
renormalize = True,
plot = True,
scatter = False,
linestyle = "-",
linewidth = 1,
s = 1
):
if not "days_through_week" in df.columns:
log.error("field days_through_week not found in DataFrame")
return False
... | Create weekly plots of a variable in a DataFrame, optionally renormalized.
It is assumed that the variable `days_through_week` exists. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1646-L1680 | null | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | yearly_plots | python | def yearly_plots(
df,
variable,
renormalize = True,
horizontal_axis_labels_days = False,
horizontal_axis_labels_months = True,
plot = True,
scatter = False,
linestyle = "-",
linewidth ... | Create yearly plots of a variable in a DataFrame, optionally renormalized.
It is assumed that the DataFrame index is datetime. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1682-L1721 | null | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | add_rolling_statistics_variables | python | def add_rolling_statistics_variables(
df = None,
variable = None,
window = 20,
upper_factor = 2,
lower_factor = 2
):
df[variable + "_rolling_mean"] = pd.stats.moments.rolling_mean(df[variable], window)
df[variable + "_rolling_standard_deviation"] = pd.st... | Add rolling statistics variables derived from a specified variable in a
DataFrame. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1723-L1738 | null | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | rescale_variables | python | def rescale_variables(
df,
variables_include = [],
variables_exclude = []
):
variables_not_rescale = variables_exclude
variables_not_rescale.extend(df.columns[df.isna().any()].tolist()) # variables with NaNs
variables_not_rescale.extend(df.select_dtypes(inc... | Rescale variables in a DataFrame, excluding variables with NaNs and strings,
excluding specified variables, and including specified variables. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1740-L1756 | null | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | histogram_hour_counts | python | def histogram_hour_counts(
df,
variable
):
if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]:
log.error("index is not datetime")
return False
counts = df.groupby(df.index.hour)[variable].count()
counts.plot(kind = "bar", width = 1, rot = 0, alpha = 0.7) | Create a day-long histogram of counts of the variable for each hour. It is
assumed that the DataFrame index is datetime and that the variable
`hour` exists. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1758-L1771 | null | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | histogram_day_counts | python | def histogram_day_counts(
df,
variable
):
if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]:
log.error("index is not datetime")
return False
counts = df.groupby(df.index.weekday_name)[variable].count().reindex(calendar.day_name[0:])
counts.plot(kind = "bar", width... | Create a week-long histogram of counts of the variable for each day. It is
assumed that the DataFrame index is datetime and that the variable
`weekday_name` exists. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1773-L1786 | null | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | histogram_month_counts | python | def histogram_month_counts(
df,
variable
):
if not df.index.dtype in ["datetime64[ns]", "<M8[ns]", ">M8[ns]"]:
log.error("index is not datetime")
return False
counts = df.groupby(df.index.strftime("%B"))[variable].count().reindex(calendar.month_name[1:])
counts.plot(kind = "bar",... | Create a year-long histogram of counts of the variable for each month. It is
assumed that the DataFrame index is datetime and that the variable
`month_name` exists. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1788-L1801 | null | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | setup_Jupyter | python | def setup_Jupyter():
sns.set(context = "paper", font = "monospace")
warnings.filterwarnings("ignore")
pd.set_option("display.max_rows", 500)
pd.set_option("display.max_columns", 500)
plt.rcParams["figure.figsize"] = (17, 10) | Set up a Jupyter notebook with a few defaults. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L1803-L1811 | null | # -*- coding: utf-8 -*-
"""
################################################################################
# #
# shijian #
# ... |
wdbm/shijian | shijian.py | List_Consensus.ensure_size | python | def ensure_size(
self,
size = None
):
if size is None:
size = self.size_constraint
while sys.getsizeof(self) > size:
element_frequencies = collections.Counter(self)
infrequent_element = element_frequencies.most_common()[-1:][0][0]
s... | This function removes the least frequent elements until the size
constraint is met. | train | https://github.com/wdbm/shijian/blob/ad6aea877e1eb99fe148127ea185f39f1413ed4f/shijian.py#L919-L932 | null | class List_Consensus(list):
"""
This class is designed to instantiate a list of elements. It features
functionality that limits approximately the memory usage of the list. On
estimating the size of the list as greater than the specified or default
size limit, the list reduces the number of elements ... |
heikomuller/sco-engine | scoengine/reqbuf_worker.py | handle_request | python | def handle_request(request):
connector = request['connector']
hostname = connector['host']
port = connector['port']
virtual_host = connector['virtualHost']
queue = connector['queue']
user = connector['user']
password = connector['password']
# Establish connection with RabbitMQ server
... | Convert a model run request from the buffer into a message in a RabbitMQ
queue.
Parameters
----------
request : dict
Buffer entry containing 'connector' and 'request' field | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/reqbuf_worker.py#L19-L64 | null | #!venv/bin/python
"""Request buffer worker - Polls the request buffer and transforms documents
into RabbitMQ messages.
"""
import logging
import json
import pika
import sys
import time
import yaml
from scodata.mongo import MongoDBFactory
"""MongoDB collection that is used as request buffer."""
COLL_REQBUFFER = 'requ... |
heikomuller/sco-engine | scoengine/model.py | ModelOutputFile.from_dict | python | def from_dict(doc):
if 'path' in doc:
path = doc['path']
else:
path = None
return ModelOutputFile(
doc['filename'],
doc['mimeType'],
path=path
) | Create a model output file object from a dictionary. | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L61-L73 | null | class ModelOutputFile(object):
"""Description of a output file generated by a model run. Each file has a
unique name (i.e., the relative path to the file in the model output
directory) and a Mime type.
Attributes
----------
filename : string
Relative path to the file in the model output... |
heikomuller/sco-engine | scoengine/model.py | ModelOutputFile.to_dict | python | def to_dict(self):
doc = {
'filename' : self.filename,
'mimeType' : self.mime_type
}
# Add path if present
if self.filename != self.path:
doc['path'] = self.path
return doc | Get a dictionary serialization of the object to convert into a Json
object.
Returns
-------
dict | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L75-L90 | null | class ModelOutputFile(object):
"""Description of a output file generated by a model run. Each file has a
unique name (i.e., the relative path to the file in the model output
directory) and a Mime type.
Attributes
----------
filename : string
Relative path to the file in the model output... |
heikomuller/sco-engine | scoengine/model.py | ModelOutputs.from_dict | python | def from_dict(doc):
return ModelOutputs(
ModelOutputFile.from_dict(doc['prediction']),
[ModelOutputFile.from_dict(a) for a in doc['attachments']]
) | Create a model output object from a dictionary. | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L131-L138 | [
"def from_dict(doc):\n \"\"\"Create a model output file object from a dictionary.\n\n \"\"\"\n if 'path' in doc:\n path = doc['path']\n else:\n path = None\n return ModelOutputFile(\n doc['filename'],\n doc['mimeType'],\n path=path\n )\n"
] | class ModelOutputs(object):
"""Description of output files that are generated by a particular model. The
output has to include a prediction file and a optional list of attachments.
Each attachment has a unique filename and a Mime type.
Raises ValueError if the list of attachments contains multiple ent... |
heikomuller/sco-engine | scoengine/model.py | ModelOutputs.to_dict | python | def to_dict(self):
return {
'prediction' : self.prediction_file.to_dict(),
'attachments' : [a.to_dict() for a in self.attachments]
} | Get a dictionary serialization of the object to convert into a Json
object.
Returns
-------
dict | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L140-L151 | null | class ModelOutputs(object):
"""Description of output files that are generated by a particular model. The
output has to include a prediction file and a optional list of attachments.
Each attachment has a unique filename and a Mime type.
Raises ValueError if the list of attachments contains multiple ent... |
heikomuller/sco-engine | scoengine/model.py | ModelRegistry.delete_model | python | def delete_model(self, model_id, erase=False):
return self.delete_object(model_id, erase=erase) | Delete the model with given identifier in the database. Returns the
handle for the deleted model or None if object identifier is unknown.
Parameters
----------
model_id : string
Unique model identifier
erase : Boolean, optinal
If true, the record will be ... | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L239-L255 | null | class ModelRegistry(MongoDBStore):
"""Default implementation for model registry. Uses MongoDB as storage
backend and makes use of the SCO datastore implementation. Provides
wrappers for delete, exists, get, and list model operations.
"""
def __init__(self, mongo):
"""Initialize the MongoDB c... |
heikomuller/sco-engine | scoengine/model.py | ModelRegistry.register_model | python | def register_model(self, model_id, properties, parameters, outputs, connector):
# Create object handle and store it in database before returning it
obj = ModelHandle(model_id, properties, parameters, outputs, connector)
self.insert_object(obj)
return obj | Create an experiment object for the subject and image group. Objects
are referenced by their identifier. The reference to a functional data
object is optional.
Raises ValueError if no valid experiment name is given in property list.
Parameters
----------
model_id : stri... | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L339-L367 | null | class ModelRegistry(MongoDBStore):
"""Default implementation for model registry. Uses MongoDB as storage
backend and makes use of the SCO datastore implementation. Provides
wrappers for delete, exists, get, and list model operations.
"""
def __init__(self, mongo):
"""Initialize the MongoDB c... |
heikomuller/sco-engine | scoengine/model.py | ModelRegistry.to_dict | python | def to_dict(self, model):
# Get the basic Json object from the super class
obj = super(ModelRegistry, self).to_dict(model)
# Add model parameter
obj['parameters'] = [
para.to_dict() for para in model.parameters
]
obj['outputs'] = model.outputs.to_dict()
... | Create a dictionary serialization for a model.
Parameters
----------
model : ModelHandle
Returns
-------
dict
Dictionary serialization for a model | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L369-L389 | null | class ModelRegistry(MongoDBStore):
"""Default implementation for model registry. Uses MongoDB as storage
backend and makes use of the SCO datastore implementation. Provides
wrappers for delete, exists, get, and list model operations.
"""
def __init__(self, mongo):
"""Initialize the MongoDB c... |
heikomuller/sco-engine | scoengine/model.py | ModelRegistry.update_connector | python | def update_connector(self, model_id, connector):
model = self.get_model(model_id)
if model is None:
return None
model.connector = connector
self.replace_object(model)
return model | Update the connector information for a given model.
Returns None if the specified model not exist.
Parameters
----------
model_id : string
Unique model identifier
connector : dict
New connection information
Returns
-------
ModelH... | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/model.py#L391-L412 | null | class ModelRegistry(MongoDBStore):
"""Default implementation for model registry. Uses MongoDB as storage
backend and makes use of the SCO datastore implementation. Provides
wrappers for delete, exists, get, and list model operations.
"""
def __init__(self, mongo):
"""Initialize the MongoDB c... |
heikomuller/sco-engine | scoengine/__init__.py | init_registry | python | def init_registry(mongo, model_defs, clear_collection=False):
# Create model registry
registry = SCOEngine(mongo).registry
# Drop collection if clear flag is set to True
if clear_collection:
registry.clear_collection()
for i in range(len(model_defs)):
model = registry.from_dict(model... | Initialize a model registry with a list of model definitions in Json
format.
Parameters
----------
mongo : scodata.MongoDBFactory
Connector for MongoDB
model_defs : list()
List of model definitions in Json-like format
clear_collection : boolean
If true, collection will b... | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/__init__.py#L506-L532 | null | """Standard Cortical Observer - Workflow Engine API.
The workflow engine is used to register and run predictive models. The engine
maintains a registry for existing models and it is used to run models for
experiments that are defined in the SCO Data Store.
Workers are used to actually execute a predictive model run. ... |
heikomuller/sco-engine | scoengine/__init__.py | SCOEngine.list_models | python | def list_models(self, limit=-1, offset=-1):
return self.registry.list_models(limit=limit, offset=offset) | Get a list of models in the registry.
Parameters
----------
limit : int
Limit number of items in the result set
offset : int
Set offset in list (order as defined by object store)
Returns
-------
list(ModelHandle) | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/__init__.py#L94-L108 | null | class SCOEngine(object):
"""SCO workflow engine. Maintains a registry of models and communicates with
backend workers to run predictive models.
"""
def __init__(self, mongo):
"""Initialize the MongoDB collection where models and connector
information is stored.
Parameters
... |
heikomuller/sco-engine | scoengine/__init__.py | SCOEngine.register_model | python | def register_model(self, model_id, properties, parameters, outputs, connector):
# Validate the given connector information
self.validate_connector(connector)
# Connector information is valid. Ok to register the model. Will raise
# ValueError if model with given identifier exists. Catch d... | Register a new model with the engine. Expects connection information
for RabbitMQ to submit model run requests to workers.
Raises ValueError if the given model identifier is not unique.
Parameters
----------
model_id : string
Unique model identifier
properti... | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/__init__.py#L110-L148 | [
"def validate_connector(self, connector):\n \"\"\"Validate a given connector. Raises ValueError if the connector is not\n valid.\n\n Parameters\n ----------\n connector : dict\n Connection information\n \"\"\"\n if not 'connector' in connector:\n raise ValueError('missing connecto... | class SCOEngine(object):
"""SCO workflow engine. Maintains a registry of models and communicates with
backend workers to run predictive models.
"""
def __init__(self, mongo):
"""Initialize the MongoDB collection where models and connector
information is stored.
Parameters
... |
heikomuller/sco-engine | scoengine/__init__.py | SCOEngine.run_model | python | def run_model(self, model_run, run_url):
# Get model to verify that it exists and to get connector information
model = self.get_model(model_run.model_id)
if model is None:
raise ValueError('unknown model: ' + model_run.model_id)
# By now there is only one connector. Use the b... | Execute the given model run.
Throws a ValueError if the given run specifies an unknown model or if
the model connector is invalid. An EngineException is thrown if running
the model (i.e., communication with the backend) fails.
Parameters
----------
model_run : ModelRunH... | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/__init__.py#L150-L170 | [
"def get_model(self, model_id):\n \"\"\"Get the registered model with the given identifier.\n\n Parameters\n ----------\n model_id : string\n Unique model identifier\n\n Returns\n -------\n ModelHandle\n Handle for requested model or None if no model with given identifier\n ... | class SCOEngine(object):
"""SCO workflow engine. Maintains a registry of models and communicates with
backend workers to run predictive models.
"""
def __init__(self, mongo):
"""Initialize the MongoDB collection where models and connector
information is stored.
Parameters
... |
heikomuller/sco-engine | scoengine/__init__.py | SCOEngine.update_model_connector | python | def update_model_connector(self, model_id, connector):
# Validate the given connector information
self.validate_connector(connector)
# Connector information is valid. Ok to update the model.
return self.registry.update_connector(model_id, connector) | Update the connector information for a given model.
Returns None if the specified model not exist.
Parameters
----------
model_id : string
Unique model identifier
connector : dict
New connection information
Returns
-------
ModelH... | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/__init__.py#L172-L191 | [
"def validate_connector(self, connector):\n \"\"\"Validate a given connector. Raises ValueError if the connector is not\n valid.\n\n Parameters\n ----------\n connector : dict\n Connection information\n \"\"\"\n if not 'connector' in connector:\n raise ValueError('missing connecto... | class SCOEngine(object):
"""SCO workflow engine. Maintains a registry of models and communicates with
backend workers to run predictive models.
"""
def __init__(self, mongo):
"""Initialize the MongoDB collection where models and connector
information is stored.
Parameters
... |
heikomuller/sco-engine | scoengine/__init__.py | SCOEngine.validate_connector | python | def validate_connector(self, connector):
if not 'connector' in connector:
raise ValueError('missing connector name')
elif connector['connector'] != CONNECTOR_RABBITMQ:
raise ValueError('unknown connector: ' + str(connector['connector']))
# Call the connector specific vali... | Validate a given connector. Raises ValueError if the connector is not
valid.
Parameters
----------
connector : dict
Connection information | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/__init__.py#L214-L229 | [
"def validate(connector):\n \"\"\"Validate the given connector information. Expects the following\n elements: host, port (int), virtualHost, queue, user, and password.\n\n Raises ValueError if any of the mandatory elements is missing or not of\n expected type.\n \"\"\"\n for key in ['host', 'port'... | class SCOEngine(object):
"""SCO workflow engine. Maintains a registry of models and communicates with
backend workers to run predictive models.
"""
def __init__(self, mongo):
"""Initialize the MongoDB collection where models and connector
information is stored.
Parameters
... |
heikomuller/sco-engine | scoengine/__init__.py | RabbitMQConnector.run_model | python | def run_model(self, model_run, run_url):
# Open connection to RabbitMQ server. Will raise an exception if the
# server is not running. In this case we raise an EngineException to
# allow caller to delete model run.
try:
credentials = pika.PlainCredentials(self.user, self.pass... | Run model by sending message to RabbitMQ queue containing the
run end experiment identifier. Messages are persistent to ensure that
a worker will process process the run request at some point.
Throws a EngineException if communication with the server fails.
Parameters
---------... | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/__init__.py#L278-L323 | [
"def get_request(self, model_run, run_url):\n \"\"\"Create request object to run model. Requests are handled by SCO\n worker implementations.\n\n Parameters\n ----------\n model_run : ModelRunHandle\n Handle to model run\n run_url : string\n URL for model run information\n\n Retur... | class RabbitMQConnector(SCOEngineConnector):
"""SCO Workflow Engine client using RabbitMQ. Sends Json messages containing
run identifier (and experiment identifier) to run model.
"""
def __init__(self, connector):
"""Initialize the client by providing host name and queue identifier
for m... |
heikomuller/sco-engine | scoengine/__init__.py | BufferedConnector.run_model | python | def run_model(self, model_run, run_url):
# Create model run request
request = RequestFactory().get_request(model_run, run_url)
# Write request and connector information into buffer
self.collection.insert_one({
'connector' : self.connector,
'request' : request.to_d... | Create entry in run request buffer.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model run information | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/__init__.py#L357-L373 | [
"def get_request(self, model_run, run_url):\n \"\"\"Create request object to run model. Requests are handled by SCO\n worker implementations.\n\n Parameters\n ----------\n model_run : ModelRunHandle\n Handle to model run\n run_url : string\n URL for model run information\n\n Retur... | class BufferedConnector(SCOEngineConnector):
"""Connector that writes run request into a MongoDB collection."""
def __init__(self, collection, connector):
"""Initialize the MongoDB collection and the connector.
Parameters
----------
collection : MongoDB Collection
Co... |
heikomuller/sco-engine | scoengine/__init__.py | RequestFactory.get_request | python | def get_request(self, model_run, run_url):
return ModelRunRequest(
model_run.identifier,
model_run.experiment_id,
run_url
) | Create request object to run model. Requests are handled by SCO
worker implementations.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model run information
Returns
-------
ModelRunRe... | train | https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/__init__.py#L383-L403 | null | class RequestFactory(object):
"""Helper class to generate request object for model runs. The requests are
interpreted by different worker implementations to run the predictive model.
"""
|
davisd50/sparc.cache | sparc/cache/item.py | schema_map | python | def schema_map(schema):
mapper = {}
for name in getFieldNames(schema):
mapper[name] = name
return mapper | Return a valid ICachedItemMapper.map for schema | train | https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/item.py#L14-L19 | null | import datetime
import inspect
from zope.interface import alsoProvides
from zope.interface import implements
from zope.component import subscribers
from zope.component.interfaces import IFactory
from zope.component.factory import Factory
from zope.schema import getFieldNames
from sparc.cache import ICachableItem, ICach... |
davisd50/sparc.cache | sparc/cache/sources/csvdata.py | CSVSource.items | python | def items(self):
for dictreader in self._csv_dictreader_list:
for entry in dictreader:
item = self.factory()
item.key = self.key()
item.attributes = entry
try:
item.validate()
except Exception as e:
... | Returns a generator of available ICachableItem in the ICachableSource | train | https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/sources/csvdata.py#L75-L89 | [
"def key(self):\n \"\"\"Returns string identifier key that marks unique item entries (e.g. primary key field name)\"\"\"\n return self._key if self._key else self.factory().key\n"
] | class CSVSource(object):
implements(ICachableSource)
def __init__(self, source, factory, key = None):
"""Initialize the CSV data source
The CSV data source, where the first data row in the represented file
contains the field headers (names).
Args:
source: This can... |
davisd50/sparc.cache | sparc/cache/sources/csvdata.py | CSVSource.getById | python | def getById(self, Id):
# we need to create a new object to insure we don't corrupt the generator count
csvsource = CSVSource(self.source, self.factory, self.key())
try:
for item in csvsource.items():
if Id == item.getId():
return item
excep... | Returns ICachableItem that matches id
Args:
id: String that identifies the item to return whose key matches | train | https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/sources/csvdata.py#L91-L104 | [
"def key(self):\n \"\"\"Returns string identifier key that marks unique item entries (e.g. primary key field name)\"\"\"\n return self._key if self._key else self.factory().key\n",
"def items(self):\n \"\"\"Returns a generator of available ICachableItem in the ICachableSource\n \"\"\"\n for dictrea... | class CSVSource(object):
implements(ICachableSource)
def __init__(self, source, factory, key = None):
"""Initialize the CSV data source
The CSV data source, where the first data row in the represented file
contains the field headers (names).
Args:
source: This can... |
davisd50/sparc.cache | sparc/cache/sources/csvdata.py | CSVSource.first | python | def first(self):
# we need to create a new object to insure we don't corrupt the generator count
csvsource = CSVSource(self.source, self.factory, self.key())
try:
item = csvsource.items().next()
return item
except StopIteration:
return None | Returns the first ICachableItem in the ICachableSource | train | https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/sources/csvdata.py#L106-L114 | [
"def key(self):\n \"\"\"Returns string identifier key that marks unique item entries (e.g. primary key field name)\"\"\"\n return self._key if self._key else self.factory().key\n",
"def items(self):\n \"\"\"Returns a generator of available ICachableItem in the ICachableSource\n \"\"\"\n for dictrea... | class CSVSource(object):
implements(ICachableSource)
def __init__(self, source, factory, key = None):
"""Initialize the CSV data source
The CSV data source, where the first data row in the represented file
contains the field headers (names).
Args:
source: This can... |
davisd50/sparc.cache | sparc/cache/sql/sql.py | SqlObjectCacheArea.get | python | def get(self, CachableItem):
return self.session.\
query(self.mapper.factory().__class__).\
filter(self.mapper.factory().__class__.__dict__[self.mapper.key()]==CachableItem.getId()).\
first() | Returns current ICachedItem for ICachableItem
Args:
CachableItem: ICachableItem, used as a reference to find a cached version
Returns: ICachedItem or None, if CachableItem has not been cached | train | https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/sql/sql.py#L124-L135 | null | class SqlObjectCacheArea(object):
"""Adapter implementation for cachable storage into a SQLAlchemy DB backend
You MUST indicate that your SQL Alchemy Session objects provide the
related marker interfaces prior to calling this adapter (see usage example
in sql.txt)
Interface implementation requirem... |
davisd50/sparc.cache | sparc/cache/sql/sql.py | SqlObjectCacheArea.cache | python | def cache(self, CachableItem):
_cachedItem = self.get(CachableItem)
if not _cachedItem:
_dirtyCachedItem = self.mapper.get(CachableItem)
logger.debug("new cachable item added to sql cache area {id: %s, type: %s}", str(_dirtyCachedItem.getId()), str(_dirtyCachedItem.__class__))
... | Updates cache area with latest information | train | https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/sql/sql.py#L153-L170 | [
"def get(self, CachableItem):\n \"\"\"Returns current ICachedItem for ICachableItem\n\n Args:\n CachableItem: ICachableItem, used as a reference to find a cached version\n\n Returns: ICachedItem or None, if CachableItem has not been cached\n \"\"\"\n return self.session.\\\n ... | class SqlObjectCacheArea(object):
"""Adapter implementation for cachable storage into a SQLAlchemy DB backend
You MUST indicate that your SQL Alchemy Session objects provide the
related marker interfaces prior to calling this adapter (see usage example
in sql.txt)
Interface implementation requirem... |
davisd50/sparc.cache | sparc/cache/sql/sql.py | SqlObjectCacheArea.import_source | python | def import_source(self, CachableSource):
_count = 0
for item in CachableSource.items():
if self.cache(item):
_count += 1
return _count | Updates cache area and returns number of items updated with all available entries in ICachableSource | train | https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/sql/sql.py#L172-L178 | [
"def cache(self, CachableItem):\n \"\"\"Updates cache area with latest information\n \"\"\"\n _cachedItem = self.get(CachableItem)\n if not _cachedItem:\n _dirtyCachedItem = self.mapper.get(CachableItem)\n logger.debug(\"new cachable item added to sql cache area {id: %s, type: %s}\", str(_... | class SqlObjectCacheArea(object):
"""Adapter implementation for cachable storage into a SQLAlchemy DB backend
You MUST indicate that your SQL Alchemy Session objects provide the
related marker interfaces prior to calling this adapter (see usage example
in sql.txt)
Interface implementation requirem... |
davisd50/sparc.cache | sparc/cache/sql/sql.py | SqlObjectCacheArea.reset | python | def reset(self):
self.Base.metadata.drop_all(self.session.bind)
self.initialize() | Deletes all entries in the cache area | train | https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/sql/sql.py#L186-L189 | [
"def initialize(self):\n \"\"\"Instantiates the cache area to be ready for updates\"\"\"\n self.Base.metadata.create_all(self.session.bind)\n logger.debug(\"initialized sqlalchemy orm tables\")\n"
] | class SqlObjectCacheArea(object):
"""Adapter implementation for cachable storage into a SQLAlchemy DB backend
You MUST indicate that your SQL Alchemy Session objects provide the
related marker interfaces prior to calling this adapter (see usage example
in sql.txt)
Interface implementation requirem... |
davisd50/sparc.cache | sparc/cache/sql/sql.py | SqlObjectCacheArea.initialize | python | def initialize(self):
self.Base.metadata.create_all(self.session.bind)
logger.debug("initialized sqlalchemy orm tables") | Instantiates the cache area to be ready for updates | train | https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/sql/sql.py#L191-L194 | null | class SqlObjectCacheArea(object):
"""Adapter implementation for cachable storage into a SQLAlchemy DB backend
You MUST indicate that your SQL Alchemy Session objects provide the
related marker interfaces prior to calling this adapter (see usage example
in sql.txt)
Interface implementation requirem... |
davisd50/sparc.cache | sparc/cache/sources/normalize.py | normalizedFieldNameCachableItemMixin.normalize | python | def normalize(cls, name):
name = name.lower() # lower-case
for _replace in [' ','-','(',')','?']:
name = name.replace(_replace,'')
return name | Return string in all lower case with spaces and question marks removed | train | https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/sources/normalize.py#L67-L72 | null | class normalizedFieldNameCachableItemMixin(cachableItemMixin):
"""Base class for ICachableItem implementations for data requiring normalized field names.
This class provides extra functionality to deal with minor differences
in attribute names when different variations of the string should be
considere... |
davisd50/sparc.cache | sparc/cache/sources/normalize.py | normalizedDateTimeResolver.manage | python | def manage(self, dateTimeString):
dateTime = None
dateTimeString = dateTimeString.replace('-', '/')
_date_time_split = dateTimeString.split(' ') # [0] = date, [1] = time (if exists)
_date = _date_time_split[0]
_time = '00:00:00' # default
if len(_date_time_split)... | Return a Python datetime object based on the dateTimeString
This will handle date times in the following formats:
YYYY/MM/DD HH:MM:SS
2014/11/05 21:47:28
2014/11/5 21:47:28
11/05/2014
11/5/2014
11/05/2014 16:28:00
11/05... | train | https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/sources/normalize.py#L94-L129 | null | class normalizedDateTimeResolver(object):
implements(IManagedCachedItemMapperAttribute)
adapts(INormalizedDateTime)
def __init__(self, context):
self.context = context
def manage(self, dateTimeString):
"""Return a Python datetime object based on the dateTimeString
This will ha... |
davisd50/sparc.cache | sparc/cache/splunk/area.py | CacheAreaForSplunkKV.current_kv_names | python | def current_kv_names(self):
return current_kv_names(self.sci, self.username, self.appname, request=self._request) | Return set of string names of current available Splunk KV collections | train | https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/splunk/area.py#L51-L53 | null | class CacheAreaForSplunkKV(object):
"""An area where cached information can be stored persistently."""
implements(ITrimmableCacheArea)
adapts(sparc.cache.ICachedItemMapper,
sparc.db.splunk.ISplunkKVCollectionSchema,
sparc.db.splunk.ISplunkConnectionInfo,
sparc.db.splunk.ISPl... |
davisd50/sparc.cache | sparc/cache/splunk/area.py | CacheAreaForSplunkKV.get | python | def get(self, CachableItem):
cached_item = self.mapper.get(CachableItem)
r = self.request('get',
self.url+"storage/collections/data/"+self.collname+'/'+cached_item.getId(),
data={'output_mode': 'json'})
if r.ok:
# we need to update the object with the values f... | Returns current ICachedItem for ICachableItem or None if not cached | train | https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/splunk/area.py#L94-L106 | [
"def request(self, *args, **kwargs):\n return self._request.request(*args, **kwargs)\n"
] | class CacheAreaForSplunkKV(object):
"""An area where cached information can be stored persistently."""
implements(ITrimmableCacheArea)
adapts(sparc.cache.ICachedItemMapper,
sparc.db.splunk.ISplunkKVCollectionSchema,
sparc.db.splunk.ISplunkConnectionInfo,
sparc.db.splunk.ISPl... |
davisd50/sparc.cache | sparc/cache/splunk/area.py | CacheAreaForSplunkKV.isDirty | python | def isDirty(self, CachableItem):
_cachedItem = self.get(CachableItem)
if not _cachedItem:
return True
_newCacheItem = self.mapper.get(CachableItem)
return False if _cachedItem == _newCacheItem else True | True if cached information requires update for ICachableItem | train | https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/splunk/area.py#L109-L115 | [
"def get(self, CachableItem):\n \"\"\"Returns current ICachedItem for ICachableItem or None if not cached\"\"\"\n cached_item = self.mapper.get(CachableItem)\n r = self.request('get',\n self.url+\"storage/collections/data/\"+self.collname+'/'+cached_item.getId(),\n data={'output_mode': 'json'... | class CacheAreaForSplunkKV(object):
"""An area where cached information can be stored persistently."""
implements(ITrimmableCacheArea)
adapts(sparc.cache.ICachedItemMapper,
sparc.db.splunk.ISplunkKVCollectionSchema,
sparc.db.splunk.ISplunkConnectionInfo,
sparc.db.splunk.ISPl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.