code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# Init records
record_dirs = set()
result_set = set()
for filename in Settings.paths:
# Record dirs to put timestamps in later
filename_full = os.path.abspath(filename)
if Settings.recurse and os.path.isdir(filename_full):
record_dirs.add(filename_full)
... | def _walk_all_files() | Optimize the files from the arugments list in two batches.
One for absolute paths which are probably outside the current
working directory tree and one for relative files. | 3.781346 | 3.783605 | 0.999403 |
# Setup Multiprocessing
# manager = multiprocessing.Manager()
Settings.pool = multiprocessing.Pool(Settings.jobs)
# Optimize Files
record_dirs, bytes_in, bytes_out, nag_about_gifs, errors = \
_walk_all_files()
# Shut down multiprocessing
Settings.pool.close()
Settings.pool... | def run() | Use preconfigured settings to optimize files. | 8.135599 | 7.485554 | 1.08684 |
filename_base = os.path.splitext(filename)[0]
new_filename = '{}.{}'.format(filename_base, new_ext)
return new_filename | def replace_ext(filename, new_ext) | Replace the file extention. | 2.158937 | 2.255202 | 0.957314 |
bytes_in = 0
bytes_out = 0
final_filename = filename
try:
bytes_in = os.stat(filename).st_size
bytes_out = os.stat(new_filename).st_size
if (bytes_out > 0) and ((bytes_out < bytes_in) or Settings.bigger):
if old_format != new_format:
final_filenam... | def _cleanup_after_optimize_aux(filename, new_filename, old_format,
new_format) | Replace old file with better one or discard new wasteful file. | 2.766359 | 2.712776 | 1.019752 |
final_filename, bytes_in, bytes_out = _cleanup_after_optimize_aux(
filename, new_filename, old_format, new_format)
return stats.ReportStats(final_filename, bytes_count=(bytes_in, bytes_out)) | def cleanup_after_optimize(filename, new_filename, old_format, new_format) | Replace old file with better one or discard new wasteful file.
And report results using the stats module. | 5.262287 | 4.934923 | 1.066336 |
install_reqs = parse_requirements(filename, session=False)
return [str(ir.req) for ir in install_reqs] | def parse_reqs(filename) | Parse setup requirements from a requirements.txt file. | 2.357547 | 2.356862 | 1.000291 |
req_list = parse_reqs(REQUIREMENTS['prod'])
if len(sys.argv) > 2 and sys.argv[2] == ('develop'):
req_list += parse_reqs(REQUIREMENTS['dev'])
return req_list | def get_req_list() | Get the requirements by weather we're building develop or not. | 4.402882 | 3.711399 | 1.186313 |
image_format = None
filename_ext = os.path.splitext(filename)[-1].lower()
if filename_ext in _COMIC_EXTS:
if zipfile.is_zipfile(filename):
image_format = _CBZ_FORMAT
elif rarfile.is_rarfile(filename):
image_format = _CBR_FORMAT
return image_format | def get_comic_format(filename) | Return the comic format if it is a comic archive. | 2.671611 | 2.4677 | 1.082632 |
head, tail = os.path.split(filename)
return os.path.join(head, _ARCHIVE_TMP_DIR_TEMPLATE.format(tail)) | def _get_archive_tmp_dir(filename) | Get the name of the working dir to use for this filename. | 3.026073 | 2.902843 | 1.042451 |
if not Settings.comics:
report = ['Skipping archive file: {}'.format(filename)]
return None, ReportStats(filename, report=report)
if Settings.verbose:
truncated_filename = stats.truncate_cwd(filename)
print("Extracting {}...".format(truncated_filename), end='')
# creat... | def comic_archive_uncompress(filename, image_format) | Uncompress comic archives.
Return the name of the working directory we uncompressed into. | 3.15944 | 3.268308 | 0.96669 |
if Settings.verbose:
print('Rezipping archive', end='')
with zipfile.ZipFile(new_filename, 'w',
compression=zipfile.ZIP_DEFLATED) as new_zf:
root_len = len(os.path.abspath(tmp_dir))
for r_d_f in os.walk(tmp_dir):
root = r_d_f[0]
filen... | def _comic_archive_write_zipfile(new_filename, tmp_dir) | Zip up the files in the tempdir into the new filename. | 2.310652 | 2.261706 | 1.021641 |
try:
filename, old_format, settings, nag_about_gifs = args
Settings.update(settings)
tmp_dir = _get_archive_tmp_dir(filename)
# archive into new filename
new_filename = files.replace_ext(filename, _NEW_ARCHIVE_SUFFIX)
_comic_archive_write_zipfile(new_filename, ... | def comic_archive_compress(args) | Called back by every optimization inside a comic archive.
When they're all done it creates the new archive and cleans up. | 5.724963 | 5.624943 | 1.017782 |
args = copy.copy(_MOZJPEG_ARGS)
if Settings.destroy_metadata:
args += ["-copy", "none"]
else:
args += ["-copy", "all"]
args += ['-outfile']
args += [ext_args.new_filename, ext_args.old_filename]
extern.run_ext(args)
return _JPEG_FORMAT | def mozjpeg(ext_args) | Create argument list for mozjpeg. | 6.524629 | 6.571361 | 0.992889 |
args = copy.copy(_JPEGTRAN_ARGS)
if Settings.destroy_metadata:
args += ["-copy", "none"]
else:
args += ["-copy", "all"]
if Settings.jpegtran_prog:
args += ["-progressive"]
args += ['-outfile']
args += [ext_args.new_filename, ext_args.old_filename]
extern.run_ext(... | def jpegtran(ext_args) | Create argument list for jpegtran. | 5.30244 | 5.215309 | 1.016707 |
args = copy.copy(_JPEGRESCAN_ARGS)
if Settings.jpegrescan_multithread:
args += ['-t']
if Settings.destroy_metadata:
args += ['-s']
args += [ext_args.old_filename, ext_args.new_filename]
extern.run_ext(args)
return _JPEG_FORMAT | def jpegrescan(ext_args) | Run the EXTERNAL program jpegrescan. | 7.132724 | 6.953775 | 1.025734 |
Settings.update(arguments)
Settings.config_program_reqs(PROGRAMS)
Settings.verbose = arguments.verbose + 1
Settings.paths = set(arguments.paths)
if arguments.formats == DEFAULT_FORMATS:
Settings.formats = arguments.to_png_formats | \
jpeg.FORMATS | gif.FORMATS
else:
... | def process_arguments(arguments) | Recompute special cases for input arguments. | 6.132612 | 6.052416 | 1.01325 |
raw_arguments = get_arguments(args[1:])
process_arguments(raw_arguments)
walk.run()
return True | def run(args) | Process command line arguments and walk inputs. | 11.450155 | 7.628705 | 1.50093 |
try:
with open('/dev/null') as null:
subprocess.call([prog, '-h'], stdout=null, stderr=null)
result = True
except OSError:
if verbose > 1:
print("couldn't run {}".format(prog))
result = False
return result | def does_external_program_run(prog, verbose) | Test to see if the external programs can be run. | 2.944553 | 2.995523 | 0.982985 |
try:
subprocess.check_call(args)
except subprocess.CalledProcessError as exc:
print(exc)
print(exc.cmd)
print(exc.returncode)
print(exc.output)
raise | def run_ext(args) | Run EXTERNAL program. | 2.474586 | 2.476733 | 0.999133 |
if num_bytes == 0:
return 'no bytes'
if num_bytes == 1:
return '1 byte'
factored_bytes = 0
factor_suffix = 'bytes'
for factor, suffix in ABBREVS:
if num_bytes >= factor:
factored_bytes = num_bytes / factor
factor_suffix = suffix
break... | def _humanize_bytes(num_bytes, precision=1) | Return a humanized string representation of a number of num_bytes.
from:
http://code.activestate.com/recipes/
577081-humanized-representation-of-a-number-of-num_bytes/
Assumes `from __future__ import division`.
>>> humanize_bytes(1)
'1 byte'
>>> humanize_bytes(1024)
'1.0 kB'
... | 2.75566 | 2.913227 | 0.945913 |
size_in = report_stats.bytes_in
if size_in > 0:
size_out = report_stats.bytes_out
ratio = size_out / size_in
kb_saved = _humanize_bytes(size_in - size_out)
else:
ratio = 0
kb_saved = 0
percent_saved = (1 - ratio) * 100
result = '{:.{prec}f}% ({})'.format... | def new_percent_saved(report_stats) | Spit out how much space the optimization saved. | 2.924966 | 2.760075 | 1.059741 |
if full_filename.startswith(os.getcwd()):
truncated_filename = full_filename.split(os.getcwd(), 1)[1]
truncated_filename = truncated_filename.split(os.sep, 1)[1]
else:
truncated_filename = full_filename
return truncated_filename | def truncate_cwd(full_filename) | Remove the cwd from the full filename. | 1.933256 | 1.907832 | 1.013326 |
if Settings.verbose:
report = ''
truncated_filename = truncate_cwd(report_stats.final_filename)
report += '{}: '.format(truncated_filename)
total = new_percent_saved(report_stats)
if total:
report += total
else:
report += '0%'
if ... | def report_saved(report_stats) | Record the percent saved & print it. | 5.661668 | 5.354635 | 1.05734 |
if bytes_in:
bytes_saved = bytes_in - bytes_out
percent_bytes_saved = bytes_saved / bytes_in * 100
msg = ''
if Settings.test:
if percent_bytes_saved > 0:
msg += "Could save"
elif percent_bytes_saved == 0:
msg += "Could even... | def report_totals(bytes_in, bytes_out, nag_about_gifs, errors) | Report the total number and percent of bytes saved. | 3.647444 | 3.56669 | 1.022641 |
report = ['Skipping {} file: {}'.format(type_name, filename)]
report_stats = ReportStats(filename, report=report)
return report_stats | def skip(type_name, filename) | Provide reporting statistics for a skipped file. | 6.939239 | 5.8345 | 1.189346 |
args = _GIFSICLE_ARGS + [ext_args.new_filename]
extern.run_ext(args)
return _GIF_FORMAT | def gifsicle(ext_args) | Run the EXTERNAL program gifsicle. | 8.666829 | 8.59831 | 1.007969 |
new_filename = filename + TMP_SUFFIX + new_ext
new_filename = os.path.normpath(new_filename)
shutil.copy2(filename, new_filename)
ext_args = ExtArgs(filename, new_filename)
new_image_format = func(ext_args)
report_stats = files.cleanup_after_optimize(filename, new_filename,
... | def _optimize_image_external(filename, func, image_format, new_ext) | Optimize the file with the external function. | 4.485415 | 4.413938 | 1.016194 |
filesize_in = os.stat(filename).st_size
report_stats = None
for func in format_module.PROGRAMS:
if not getattr(Settings, func.__name__):
continue
report_stats = _optimize_image_external(
filename, func, image_format, format_module.OUT_EXT)
filename = rep... | def _optimize_with_progs(format_module, filename, image_format) | Use the correct optimizing functions in sequence.
And report back statistics. | 4.849541 | 4.788157 | 1.01282 |
format_module = None
nag_about_gifs = False
if detect_format.is_format_selected(image_format,
Settings.to_png_formats,
png.PROGRAMS):
format_module = png
elif detect_format.is_format_selected(image_format, jpeg... | def _get_format_module(image_format) | Get the format module to use for optimizing the image. | 4.540451 | 4.402696 | 1.031289 |
try:
filename, image_format, settings = arg
Settings.update(settings)
format_module, nag_about_gifs = _get_format_module(image_format)
if format_module is None:
if Settings.verbose > 1:
print(filename, image_format) # image.mode)
p... | def optimize_image(arg) | Optimize a given image from a filename. | 6.793963 | 6.819398 | 0.99627 |
mode = False
for prog in progs:
if getattr(Settings, prog.__name__):
mode = True
break
return mode | def _is_program_selected(progs) | Determine if the program is enabled in the settings. | 7.207613 | 4.962017 | 1.452557 |
intersection = formats & Settings.formats
mode = _is_program_selected(progs)
result = (image_format in intersection) and mode
return result | def is_format_selected(image_format, formats, progs) | Determine if the image format is selected by command line arguments. | 11.682374 | 12.282552 | 0.951136 |
try:
image.seek(1)
image.seek(0)
result = True
except EOFError:
result = False
return result | def _is_image_sequenced(image) | Determine if the image is a sequenced image. | 4.155919 | 3.673939 | 1.131189 |
image = None
bad_image = 1
image_format = NONE_FORMAT
sequenced = False
try:
bad_image = Image.open(filename).verify()
image = Image.open(filename)
image_format = image.format
sequenced = _is_image_sequenced(image)
except (OSError, IOError, AttributeError):
... | def get_image_format(filename) | Get the image format. | 4.002295 | 3.945263 | 1.014456 |
image_format = get_image_format(filename)
if image_format in Settings.formats:
return image_format
if image_format in (NONE_FORMAT, ERROR_FORMAT):
return None
if Settings.verbose > 1 and not Settings.list_only:
print(filename, image_format, 'is not a enabled image or '
... | def detect_file(filename) | Decide what to do with the file. | 7.34377 | 7.469493 | 0.983168 |
for key, val in settings.__dict__.items():
if key.startswith('_'):
continue
setattr(cls, key, val) | def update(cls, settings) | Update settings with a dict. | 3.266888 | 3.05643 | 1.068857 |
for program in programs:
val = getattr(cls, program.__name__) \
and extern.does_external_program_run(program.__name__,
Settings.verbose)
setattr(cls, program.__name__, val) | def _set_program_defaults(cls, programs) | Run the external program tester on the required binaries. | 11.181342 | 9.066114 | 1.233311 |
cls._set_program_defaults(programs)
do_png = cls.optipng or cls.pngout or cls.advpng
do_jpeg = cls.mozjpeg or cls.jpegrescan or cls.jpegtran
do_comics = cls.comics
if not do_png and not do_jpeg and not do_comics:
print("All optimizers are not available or ... | def config_program_reqs(cls, programs) | Run the program tester and determine if we can do anything. | 7.45732 | 7.176166 | 1.039179 |
args = _OPTIPNG_ARGS + [ext_args.new_filename]
extern.run_ext(args)
return _PNG_FORMAT | def optipng(ext_args) | Run the external program optipng on the file. | 11.368484 | 10.921601 | 1.040917 |
args = _ADVPNG_ARGS + [ext_args.new_filename]
extern.run_ext(args)
return _PNG_FORMAT | def advpng(ext_args) | Run the external program advpng on the file. | 11.34038 | 10.702751 | 1.059576 |
args = _PNGOUT_ARGS + [ext_args.old_filename, ext_args.new_filename]
extern.run_ext(args)
return _PNG_FORMAT | def pngout(ext_args) | Run the external program pngout on the file. | 8.221986 | 7.851901 | 1.047133 |
func_chain = cls(attr_scts=_attr_scts)
func_chain._stack.append([f, args, kwargs])
return func_chain | def _from_func(cls, f, *args, _attr_scts=None, **kwargs) | Creates a function chain starting with the specified SCT (f), and its arguments. | 4.798503 | 3.588253 | 1.337281 |
# type: (Callable) -> Callable
@wraps(fn)
def wrapped(self, *args, **kwargs):
# type: (SessionFactory) -> Any
try:
rv = fn(self, *args, **kwargs)
except _TransactionalPolicyViolationError as e:
getattr(self, _TX_HOLDER_ATTRIBUTE).rollback()
r... | def _nested_transactional(fn) | In a transactional method create a nested transaction. | 4.616993 | 4.895476 | 0.943114 |
if use_fs:
p = Path(fname)
if not p.exists():
state.report(Feedback(missing_msg.format(fname))) # test file exists
if p.is_dir():
state.report(Feedback(is_dir_msg.format(fname))) # test its not a dir
code = p.read_text()
else:
code = _get_... | def check_file(
state,
fname,
missing_msg="Did you create a file named `{}`?",
is_dir_msg="Want to check a file named `{}`, but found a directory.",
parse=True,
use_fs=True,
use_solution=False,
) | Test whether file exists, and make its contents the student code.
Note: this SCT fails if the file is a directory. | 3.090445 | 2.917331 | 1.05934 |
if not Path(fname).is_dir():
state.report(Feedback(incorrect_msg.format(fname)))
return state | def has_dir(state, fname, incorrect_msg="Did you create a directory named `{}`?") | Test whether a directory exists. | 5.791033 | 5.279135 | 1.096966 |
if not data:
data = {'data': None, 'path': task_path}
elif not isinstance(data, (str, bytes)):
data = {'data': json.dumps(data, cls=RequestJSONEncoder),
'path': task_path}
else:
# Open the data from file, if necessary.
if data is not None and data.start... | def exec_task(task_path, data) | Execute task.
:param task_path: task path
:type task_path: str|Callable
:param data: task's data
:type data: Any
:return: | 3.88766 | 4.00028 | 0.971847 |
if config.is_node(node):
fields = OrderedDict()
for name in config.fields_iter(node):
attr = config.field_val(node, name)
if attr is not None:
fields[name] = dump(attr, config)
return {"type": config.node_type(node), "data": fields}
elif confi... | def dump(node, config) | Convert a node tree to a simple nested dict
All steps in this conversion are configurable using DumpConfig
dump dictionary node: {"type": str, "data": dict} | 2.614231 | 2.500626 | 1.045431 |
# type: (Query)->Query
assert self.record_count >= 0, "Record count must be set."
return q.limit(self.page_size).offset(self.offset) | def apply_pagination(self, q) | Filters the query so that a given page is returned. The record count
must be set in advance.
:param q: Query to be paged.
:return: Paged query. | 6.111911 | 4.315215 | 1.416363 |
self.record_count = q.count()
return self.apply_pagination(q).all() | def paginate(self, q) | Filters the query so that a given page is returned. The record count
is computed automatically from query.
:param q: Query to be paged.
:return: Paged query. | 7.632698 | 6.744864 | 1.131631 |
@wraps(f)
def wrapper_fn(*args, **kwargs):
res = f(*args, **kwargs)
logging.debug("Logging result %s.", res)
return res
return wrapper_fn | def log_output(f) | Logs the output value. | 3.902589 | 3.819216 | 1.02183 |
def decorator_fn(f):
@wraps(f)
def wrapper_fn(*args, **kwargs):
res = f(*args, **kwargs)
makedirs(os.path.dirname(destination_filename))
mode = "a" if append else "w"
with open(destination_filename, mode) as text_file:
text_file.... | def save_to_file(destination_filename, append=False) | Save the output value to file. | 2.253166 | 2.254339 | 0.99948 |
@wraps(f)
def json_input_decorator(*args, **kwargs):
# If the data is already transformed, we do not transform it any
# further.
task_data = _get_data_from_args(args)
if task_data is None:
logging.error("Task data is empty during JSON decoding.")
if ta... | def json_input(f) | Expects task input data in json format and parse this data. | 4.774374 | 4.64851 | 1.027076 |
@wraps(f)
def json_output_decorator(*args, **kwargs):
@inject(config=Config)
def get_config(config):
return config
config = get_config()
rv = f(*args, **kwargs)
indent = None
if config.get('DEBUG', False):
logging.getLogger(__name__... | def json_output(f) | Format response to json and in case of web-request set response content type
to 'application/json'. | 4.285221 | 4.055484 | 1.056649 |
def decorator_fn(f):
@wraps(f)
def jsonp_output_decorator(*args, **kwargs):
task_data = _get_data_from_args(args)
data = task_data.get_data()
if callback_key not in data:
raise KeyError(
'Missing required parameter "{0}"... | def jsonp_wrap(callback_key='callback') | Format response to jsonp and add a callback to JSON data - a jsonp request | 4.127878 | 4.102997 | 1.006064 |
fail_exception_classes = fail_exception_classes if fail_exception_classes \
else ()
def decorator_fn(f):
@wraps(f)
@json_output
def jsend_output_decorator(*args, **kwargs):
try:
rv = f(*args, **kwargs)
except fail_exception_classes ... | def jsend_output(fail_exception_classes=None) | Format task result to json output in jsend specification format. See:
https://github.com/omniti-labs. Task return value must be dict or None.
@param fail_exception_classes: exceptions which will produce 'fail' response
status. | 2.375371 | 2.380084 | 0.99802 |
@wraps(f)
def web_error_and_result_decorator(*args, **kwargs):
return error_and_result_decorator_inner_fn(f, True, *args, **kwargs)
return web_error_and_result_decorator | def web_error_and_result(f) | Same as error_and_result decorator, except:
If no exception was raised during task execution, ONLY IN CASE OF WEB
REQUEST formats task result into json dictionary {'data': task return value} | 2.912253 | 2.628402 | 1.107994 |
@wraps(f)
def error_and_result_decorator(*args, **kwargs):
return error_and_result_decorator_inner_fn(f, False, *args, **kwargs)
return error_and_result_decorator | def error_and_result(f) | Format task result into json dictionary `{'data': task return value}` if no
exception was raised during the task execution. If there was raised an
exception during task execution, formats task result into dictionary
`{'error': exception message with traceback}`. | 2.942808 | 3.231866 | 0.91056 |
def decorator_fn(f):
@wraps(f)
def required_data_decorator(*args, **kwargs):
task_data = _get_data_from_args(args).get_data()
for i in data:
if i not in task_data:
raise KeyError(
'Missing required parameter "... | def required_data(*data) | Task decorator which checks if the given variables (indices) are stored
inside the task data. | 3.471794 | 2.907105 | 1.194244 |
# type: (bool) -> Callable
def wrapper(f):
@wraps(f)
def append_get_parameters_wrapper_fn(*args, **kwargs):
jc = JobContext.get_current_context()
if isinstance(jc, WebJobContext):
# Update the data with GET parameters
web_request = ... | def append_get_parameters(accept_only_web=True) | Task decorator which appends the GET data to the task data.
:param accept_only_web: Parameter which limits using this task only
with web requests. | 4.480083 | 4.271155 | 1.048916 |
@wraps(f)
def web_task_decorator(*args, **kwargs):
jc = JobContext.get_current_context()
if not isinstance(jc, WebJobContext):
raise Exception(
"The WebTask is not called through the web interface.")
data = f(*args, **kwargs)
jc.add_responder(Web... | def web_task(f) | Checks if the task is called through the web interface.
Task return value should be in format {'data': ...}. | 4.45789 | 3.64968 | 1.221447 |
@wraps(f)
def secured_task_decorator(*args, **kwargs):
task_data = _get_data_from_args(args)
assert isinstance(task_data, TaskData)
if not verify_security_data(task_data.get_data()['security']):
raise SecurityException(
task_data.get_data()['security']['... | def secured_task(f) | Secured task decorator. | 3.793899 | 3.642443 | 1.041581 |
@wraps(f)
def xml_output_inner_fn(*args, **kwargs):
ret_val = f(*args, **kwargs)
if isinstance(JobContext.get_current_context(), WebJobContext):
JobContext.get_current_context().add_responder(
MimeSetterWebTaskResponder('text/xml'))
return ret_val
... | def xml_output(f) | Set content-type for response to WEB-REQUEST to 'text/xml' | 5.898049 | 5.333691 | 1.10581 |
@wraps(f)
def file_upload_decorator(*args, **kwargs):
# If the data is already transformed, we do not transform it any
# further.
task_data = _get_data_from_args(args)
if task_data is None:
logging.error("Task data is empty during FilesUploadDecorator.")
... | def file_upload(f) | Return list of `werkzeug.datastructures.FileStorage` objects - files to be
uploaded | 5.620243 | 5.453196 | 1.030633 |
@wraps(f)
def wrapper_fn(*args, **kwargs):
if isinstance(JobContext.get_current_context(), WebJobContext):
raise ForbiddenError('Access forbidden from web.')
return f(*args, **kwargs)
return wrapper_fn | def forbid_web_access(f) | Forbids running task using http request.
:param f: Callable
:return Callable | 4.694984 | 4.750692 | 0.988274 |
fields = arg.split(',')
mapper = class_mapper(model_cls)
if not arg_types:
arg_types = {}
exprs = []
joins = set()
for expr in fields:
if expr == "":
continue
e_mapper = mapper
e_model_cls = model_cls
operator = None
method = ... | def filter_from_url_arg(model_cls, query, arg, query_operator=and_,
arg_types=None) | Parse filter URL argument ``arg`` and apply to ``query``
Example: 'column1<=value,column2==value' -> query.filter(Model.column1 <= value, Model.column2 == value) | 2.429798 | 2.421366 | 1.003482 |
if not visited:
visited = set()
visited.add(model_cls)
mapper = class_mapper(model_cls)
columns = [column.key for column in mapper.column_attrs]
related = [model_tree(rel.key, rel.mapper.entity, visited)
for rel in mapper.relationships if rel.mapper.entity not in visite... | def model_tree(name, model_cls, visited=None) | Create a simple tree of model's properties and its related models.
It traverse trough relations, but ignore any loops.
:param name: name of the model
:type name: str
:param model_cls: model class
:param visited: set of visited models
:type visited: list or None
:return: a dictionary where ... | 2.741157 | 3.160931 | 0.867199 |
names = []
for columns in viewvalues(tree):
for col in columns:
if isinstance(col, dict):
col_name = list(col)[0]
names += [col_name + '__' + c for c in flat_model(col)]
else:
names.append(col)
return names | def flat_model(tree) | Flatten the tree into a list of properties adding parents as prefixes. | 3.934316 | 3.682427 | 1.068403 |
# type: (Job, Zsl, TaskRouter) -> dict
app.logger.info("Job fetched, preparing the task '{0}'.".format(job.path))
task, task_callable = task_router.route(job.path)
jc = JobContext(job, task, task_callable)
app.logger.info("Executing task.")
result = jc.task_callable(jc.task_data)
ap... | def execute_job(job, app=Injected, task_router=Injected) | Execute a job.
:param job: job to execute
:type job: Job
:param app: service application instance, injected
:type app: ServiceApplication
:param task_router: task router instance, injected
:type task_router: TaskRouter
:return: task result
:rtype: dict | 5.045492 | 5.566072 | 0.906473 |
# type: (Exception, str) -> dict
self._app.logger.error(str(e) + "\n" + traceback.format_exc())
return {'task_name': task_path, 'data': None, 'error': str(e)} | def handle_exception(self, e, task_path) | Handle exception raised during task execution.
:param e: exception
:type e: Exception
:param task_path: task path
:type task_path: str
:return: exception as task result
:rtype: dict | 4.265367 | 5.030391 | 0.84792 |
# type: (Job) -> dict
try:
return execute_job(job)
except KillWorkerException:
self._app.logger.info("Stopping Gearman worker on demand flag set.")
self.stop_worker()
except Exception as e:
return self.handle_exception(e, job.pat... | def execute_job(self, job) | Execute job given by the task queue.
:param job: job
:type job: Job
:return: task result
:rtype: dict | 8.301332 | 9.813637 | 0.845898 |
def signature_decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
redirected_kwargs = {
kwargs_mapping[k] if k in kwargs_mapping else k: v
for k, v in kwargs.items()
}
return f(*args, **redirected_kwargs)
return wra... | def legacy_signature(**kwargs_mapping) | This decorator makes it possible to call a function using old argument names
when they are passed as keyword arguments.
@legacy_signature(old_arg1='arg1', old_arg2='arg2')
def func(arg1, arg2=1):
return arg1 + arg2
func(old_arg1=1) == 2
func(old_arg1=1, old_arg2=2) == 3 | 2.262876 | 2.253901 | 1.003982 |
module = importlib.import_module(package_name)
cls = getattr(module, cls_name)
binder.bind(
cls,
to=binder.injector.create_object(cls),
scope=singleton
)
logging.debug("Created {0} binding.".format(cls)) | def _bind_service(package_name, cls_name, binder=Injected) | Bind service to application injector.
:param package_name: service package
:type package_name: str
:param cls_name: service class
:type cls_name: str
:param binder: current application binder, injected
:type binder: Binder | 3.935945 | 4.511863 | 0.872355 |
service_injection_config = config.get('SERVICE_INJECTION', ())
if not isinstance(service_injection_config, (tuple, list)):
service_injection_config = (service_injection_config,)
for si_conf in service_injection_config:
if isinstance(si_conf, str):
... | def initialize(config) | Initialize method.
:param config: current application config, injected
:type config: Config | 2.565531 | 2.660714 | 0.964227 |
# TODO ako vysledok vrat nejaky JOB ID, aby sa dalo checkovat na pozadi
# TODO vytvorit este vseobecny background_task nielen pre metody
def decorator_fn(fn):
gearman = None
@inject(config=Config)
def gearman_connect(config):
# type: (Config) -> GearmanService
... | def background_task_method(task) | Decorate an object method as a background task (called with help of
gearman).
You have to create a task which will handle the gearman call. The
method arguments will be encoded as JSON.
:param task: name of the task
:type task: str
:return: decorated function | 4.959494 | 4.682518 | 1.059151 |
# type: (int, int, int, str) -> Dict[str, str]
current_page = _page_arg(page)
links = {}
end = page * per_page
if page > 1:
links['prev'] = page_url.replace(current_page, _page_arg(page - 1))
if end < count:
links['next'] = page_url.replace(current_page, _page_arg(page + 1... | def _get_link_pages(page, per_page, count, page_url) | Create link header for page metadata.
:param page: current page
:param per_page: page limit
:param count: count of all resources
:param page_url: url for resources
:return: dictionary with name of the link as key and its url as value | 2.008591 | 2.41457 | 0.831863 |
return filter_from_url_arg(self.model_cls, query, arg, query_operator=or_) | def to_filter(self, query, arg) | Json-server filter using the _or_ operator. | 14.684732 | 11.088921 | 1.324271 |
resource = super(JsonServerResource, self).create(*args, **kwargs)
return ResourceResult(
body=resource,
status=get_http_status_code_value(http.client.CREATED),
location="{}/{}".format(request.url, resource.get_id())
) | def create(self, *args, **kwargs) | Adds created http status response and location link. | 6.193692 | 5.160004 | 1.200327 |
filter_by = []
for name, values in request.args.copy().lists(): # copy.lists works in py2 and py3
if name not in _SKIPPED_ARGUMENTS:
column = _re_column_name.search(name).group(1)
if column not in self._model_columns:
continue
... | def _create_filter_by(self) | Transform the json-server filter arguments to model-resource ones. | 3.074158 | 2.915875 | 1.054283 |
# type: (Dict) -> None
if '_embed' in request.args:
embeds = request.args.getlist('_embed')
args['related'] = ','.join(embeds)
del args['_embed'] | def _create_related(args) | Create related field from `_embed` arguments. | 6.219129 | 4.839538 | 1.285067 |
filter_by = []
if 'q' in request.args:
columns = flat_model(model_tree(self.__class__.__name__, self.model_cls))
for q in request.args.getlist('q'):
filter_by += ['{col}::like::%{q}%'.format(col=col, q=q) for col in columns]
return filter_by | def _create_fulltext_query(self) | Support the json-server fulltext search with a broad LIKE filter. | 6.234043 | 5.537516 | 1.125783 |
# type: (dict) -> None
if '_limit' in args:
args['limit'] = int(args['_limit'])
del args['_limit']
if '_page' in args:
page = int(args['_page'])
if page < 0:
page = 1
args['page'] = page
del args[... | def _transform_list_args(self, args) | Transforms all list arguments from json-server to model-resource ones.
This modifies the given arguments. | 2.136186 | 2.145608 | 0.995608 |
result_count = None
result_links = None
if params is None:
params = []
if args:
args = args.copy()
else:
args = {}
ctx = self._create_context(params, args, data)
row_id = ctx.get_row_id()
if not row_id:
... | def read(self, params, args, data) | Modifies the parameters and adds metadata for read results. | 3.827502 | 3.82477 | 1.000714 |
if request.method == 'PUT':
logging.warning("Called not implemented resource method PUT")
resource = super(JsonServerResource, self).update(*args, **kwargs)
if resource:
return resource
else:
return NOT_FOUND | def update(self, *args, **kwargs) | Modifies the parameters and adds metadata for update results.
Currently it does not support `PUT` method, which works as replacing
the resource. This is somehow questionable in relation DB. | 7.473889 | 6.48393 | 1.152679 |
ctx = self._create_context(params, args, data)
row_id = ctx.get_row_id()
if row_id:
deleted = self._delete_one(row_id, ctx)
if deleted:
return ResourceResult(body={})
else:
return NOT_FOUND
else:
r... | def delete(self, params, args, data) | Supports only singular delete and adds proper http status. | 4.202761 | 3.988381 | 1.053751 |
task = instantiate(task_cls)
task_callable = get_callable(task)
return task_callable(TaskData(task_data)) | def run_task(task_cls, task_data) | Instantiate and run the perform method od given task data.
:param task_cls: task class
:param task_data: task data
:type task_data: TaskData
:return: task's result | 6.044378 | 7.553324 | 0.800228 |
# TODO what does set_skipping_json do?
task = instantiate(task_cls)
task_callable = get_callable(task)
td = TaskData(task_data)
td.set_skipping_json(True)
return task_callable(td) | def run_task_json(task_cls, task_data) | Instantiate and run the perform method od given task data.
:param task_cls: task class
:param task_data: task data
:type task_data: TaskData
:return: task's result | 6.583873 | 7.685446 | 0.856668 |
'''
Counts the number of occurances of each item in 'data'.
Inputs
data: a list of values.
norm: normalize the resulting counts (as percent)
sort_by: how to sort the retured data. Options are 'value' and 'count'.
Output
a non-redundant list of values (from 'data') and a list of counts.... | def _aggregate(data, norm=True, sort_by='value', keys=None) | Counts the number of occurances of each item in 'data'.
Inputs
data: a list of values.
norm: normalize the resulting counts (as percent)
sort_by: how to sort the retured data. Options are 'value' and 'count'.
Output
a non-redundant list of values (from 'data') and a list of counts. | 2.453878 | 1.646365 | 1.490482 |
generator = ApiaryDoc()
for m in task_router.get_task_packages() + get_method_packages():
m = importlib.import_module(m)
generator.docmodule(m)
return generator | def generate_apiary_doc(task_router) | Generate apiary documentation.
Create a Apiary generator and add application packages to it.
:param task_router: task router, injected
:type task_router: TaskRouter
:return: apiary generator
:rtype: ApiaryDoc | 8.661665 | 7.937698 | 1.091206 |
'''
Set up logging using the built-in ``logging`` package.
A stream handler is added to all logs, so that logs at or above
``logging.INFO`` level are printed to screen as well as written
to the log file.
Arguments:
logfile (str): Path to the log file. If the parent directory
... | def setup_logging(logfile, print_log_location=True, debug=False) | Set up logging using the built-in ``logging`` package.
A stream handler is added to all logs, so that logs at or above
``logging.INFO`` level are printed to screen as well as written
to the log file.
Arguments:
logfile (str): Path to the log file. If the parent directory
does not ... | 2.583659 | 1.454414 | 1.776426 |
'''
Get a logging handle.
As with ``setup_logging``, a stream handler is added to the
log handle.
Arguments:
name (str): Name of the log handle. Default is ``None``.
'''
logger = logging.getLogger(name)
if len(logger.handlers) == 0:
logger = add_stream_handler(logger)
... | def get_logger(name=None) | Get a logging handle.
As with ``setup_logging``, a stream handler is added to the
log handle.
Arguments:
name (str): Name of the log handle. Default is ``None``. | 4.928011 | 2.041893 | 2.413452 |
def outer_wrapper(f):
def function_wrapper(ff):
for key, value in viewitems(bindings):
bindings[key] = BindingKey(value)
@functools.wraps(ff)
def _inject(*args, **kwargs):
inj = get_current_app().injector
dependencies... | def inject(**bindings) | Decorator for injecting parameters for ASL objects. | 5.428151 | 5.424172 | 1.000734 |
'''
Computes a phylogenetic tree using IgPhyML.
.. note::
IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML.
Args:
input_file (str): Path to a Phylip-formatted multiple sequence alignment. Required.
tree_file (str): Path to the o... | def igphyml(input_file=None, tree_file=None, root=None, verbose=False) | Computes a phylogenetic tree using IgPhyML.
.. note::
IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML.
Args:
input_file (str): Path to a Phylip-formatted multiple sequence alignment. Required.
tree_file (str): Path to the output tree f... | 3.989682 | 2.794176 | 1.427856 |
@wraps(f)
def _response_decorator(*args, **kwargs):
r = f(*args, **kwargs)
response = r if isinstance(r, Response) else make_response(r)
append_all(response)
return response
return _response_decorator | def append_headers(f) | Appends all the web headers:
* ZSL version and information,
* default CORS if not already set up,
* cache.
:param f: The decorated function.
:return: The function which appends the web headers. | 3.135288 | 3.378885 | 0.927906 |
try:
with open(filename) as f:
lines = f.readlines()
except IOError:
lines = []
tmp_file = tempfile.NamedTemporaryFile(delete=False)
lines.reverse()
# first copy before start line
while lines:
line = lines.pop()
if line == start_line:
... | def integrate_to_file(what, filename, start_line, end_line) | WARNING this is working every second run.. so serious bug
Integrate content into a file withing "line marks" | 2.472787 | 2.490862 | 0.992744 |
if forbidden_keys is None:
forbidden_keys = []
if type(app_model) != dict:
app_model = app_model.__dict__
if inverse:
for k in app_model:
logging.debug("Considering property {0}.".format(k))
if (hasattr(raw_model, k)) and (k not in forbidden_keys):
... | def update_model(raw_model, app_model, forbidden_keys=None, inverse=False) | Updates the `raw_model` according to the values in the `app_model`.
:param raw_model: Raw model which gets updated.
:param app_model: App model holding the data.
:param forbidden_keys: Data/attributes which will not be updated.
:type forbidden_keys: list
:param inverse: If the value is `True` all `... | 1.66218 | 1.737067 | 0.956889 |
'''
Prints an ASCII progress bar.
Each call to ``progress_bar`` will update the progress bar. An example
of tracking the progress of a list of items would look like::
job_list = [job1, job2, job3, ... jobN]
total_jobs = len(job_list)
#initialize the progress bar
progre... | def progress_bar(finished, total, start_time=None, extra_info=None,
autocomplete=True, completion_string='/n') | Prints an ASCII progress bar.
Each call to ``progress_bar`` will update the progress bar. An example
of tracking the progress of a list of items would look like::
job_list = [job1, job2, job3, ... jobN]
total_jobs = len(job_list)
#initialize the progress bar
progress_bar(0, to... | 2.638396 | 1.407355 | 1.87472 |
r"test -> in1 /\ ~test -> in0"
assert len({test, in0, in1}) == 3
true_out = bit_flipper([test]) >> or_gate([test, in1], 'true_out')
false_out = or_gate([test, in0], 'false_out')
return (true_out | false_out) >> and_gate(['true_out', 'false_out'],
output... | def _ite(test: str, in1: str, in0: str, output: str = None) | r"test -> in1 /\ ~test -> in0 | 6.17621 | 4.349995 | 1.41982 |
if forbidden_keys is None:
forbidden_keys = []
update_model(self, app_model, forbidden_keys, inverse) | def update(self, app_model, forbidden_keys=None, inverse=False) | Updates the raw model. Consult `zsl.utils.model_helper.update_model`. | 3.139854 | 2.349558 | 1.336359 |
# TODO document tuple - it looks little too complex
# handle simple definition
if isinstance(definition, str) and len(definition) > 0:
if definition[0] == '@': # test for attribute
return element.get(definition[1:])
# get tag text
else:
sub_element = el... | def xml_to_json(element, definition, required=False) | Convert XML (ElementTree) to dictionary from a definition schema.
Definition schema can be a simple string - XPath or @attribute for
direct extraction or a complex one described by
* dictionary ``{key: 'xpath or @attribute', second: 'complex definition'}`` \
required parameters can be marked with * ... | 3.203358 | 3.086769 | 1.037771 |
sub_dict = {}
for name, subdef in viewitems(definition):
(name, required) = _parse_name(name)
sub_dict[name] = xml_to_json(element, subdef, required)
return sub_dict | def _parse_dict(element, definition) | Parse xml element by a definition given in dict format.
:param element: ElementTree element
:param definition: definition schema
:type definition: dict
:return: parsed xml
:rtype: dict | 4.730954 | 5.907985 | 0.800773 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.