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
klmitch/requiem
requiem/decorators.py
restmethod
python
def restmethod(method, reluri, *qargs, **headers): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): # Process the arguments against the original function argmap, theSelf, req_name = _getcallargs(func, args, kwargs) # Build the URL ...
Decorate a method to inject an HTTPRequest. Generates an HTTPRequest using the given HTTP method and relative URI. If additional positional arguments are present, they are expected to be strings that name function arguments that should be included as the query parameters of the URL. If additional ...
train
https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/decorators.py#L179-L236
null
# Copyright 2011 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
klmitch/requiem
requiem/client.py
RESTClient._debug
python
def _debug(self, msg, *args, **kwargs): # Do nothing if debugging is disabled if self._debug_stream is None or self._debug_stream is False: return # What are we passing to the format? if kwargs: fmtargs = kwargs else: fmtargs = args ...
Emit debugging messages.
train
https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/client.py#L68-L82
null
class RESTClient(object): """Represent a REST client API. Methods are expected to perform REST calls to a server specified by a base URL. The @restmethod() decorator helps this process by passing an additional HTTPRequest object into the method. The request class to use can be overridden by chang...
klmitch/requiem
requiem/client.py
RESTClient._push_processor
python
def _push_processor(self, proc, index=None): if index is None: self._procstack.append(proc) else: self._procstack.insert(index, proc)
Pushes a processor onto the processor stack. Processors are objects with proc_request(), proc_response(), and/or proc_exception() methods, which can intercept requests, responses, and exceptions. When a method invokes the send() method on a request, the proc_request() method on each ...
train
https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/client.py#L84-L108
null
class RESTClient(object): """Represent a REST client API. Methods are expected to perform REST calls to a server specified by a base URL. The @restmethod() decorator helps this process by passing an additional HTTPRequest object into the method. The request class to use can be overridden by chang...
klmitch/requiem
requiem/client.py
RESTClient._make_req
python
def _make_req(self, method, url, methname, headers=None): # Build up headers hset = hdrs.HeaderDict() # Walk through our global headers for hdr, value in self._headers.items(): # If it's a callable, call it if callable(value): value = value(methn...
Create a request object for the specified method and url.
train
https://github.com/klmitch/requiem/blob/0b3b5252e1b3487af732a8666b3bdc2e7035fef5/requiem/client.py#L110-L139
null
class RESTClient(object): """Represent a REST client API. Methods are expected to perform REST calls to a server specified by a base URL. The @restmethod() decorator helps this process by passing an additional HTTPRequest object into the method. The request class to use can be overridden by chang...
rocky/python-filecache
pyficache/main.py
pyc2py
python
def pyc2py(filename): if re.match(".*py[co]$", filename): if PYTHON3: return re.sub(r'(.*)__pycache__/(.+)\.cpython-%s.py[co]$' % PYVER, '\\1\\2.py', filename) else: return filename[:-1] return filename
Find corresponding .py name given a .pyc or .pyo
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L94-L105
null
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
clear_file_cache
python
def clear_file_cache(filename=None): global file_cache, file2file_remap, file2file_remap_lines if filename is not None: if filename in file_cache: del file_cache[filename] pass else: file_cache = {} file2file_remap = {} file2file_remap_lines = {} ...
Clear the file cache. If no filename is given clear it entirely. if a filename is given, clear just that filename.
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L198-L211
null
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
clear_file_format_cache
python
def clear_file_format_cache(): for fname, cache_info in file_cache.items(): for format, lines in cache_info.lines.items(): if 'plain' == format: continue file_cache[fname].lines[format] = None pass pass pass
Remove syntax-formatted lines in the cache. Use this when you change the Pygments syntax or Token formatting and want to redo how files may have previously been syntax marked.
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L213-L224
null
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
checkcache
python
def checkcache(filename=None, opts=False): if isinstance(opts, dict): use_linecache_lines = opts['use_linecache_lines'] else: use_linecache_lines = opts pass if not filename: filenames = list(file_cache.keys()) elif filename in file_cache: filenames = [filename]...
Discard cache entries that are out of date. If *filename* is *None* all entries in the file cache *file_cache* are checked. If we do not have stat information about a file it will be kept. Return a list of invalidated filenames. None is returned if a filename was given but not found cached.
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L230-L267
null
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
cache_script
python
def cache_script(script, text, opts={}): global script_cache if script not in script_cache: update_script_cache(script, text, opts) pass return script
Cache script if it is not already cached.
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L269-L275
[ "def update_script_cache(script, text, opts={}):\n \"\"\"Cache script if it is not already cached.\"\"\"\n global script_cache\n if script not in script_cache:\n script_cache[script] = text\n return script\n" ]
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
cache_file
python
def cache_file(filename, reload_on_change=False, opts=default_opts): filename = pyc2py(filename) if filename in file_cache: if reload_on_change: checkcache(filename) pass else: opts['use_linecache_lines'] = True update_cache(filename, opts) pass if filename in fil...
Cache filename if it is not already cached. Return the expanded filename for it in the cache or nil if we can not find the file.
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L292-L307
[ "def checkcache(filename=None, opts=False):\n \"\"\"Discard cache entries that are out of date. If *filename* is *None*\n all entries in the file cache *file_cache* are checked. If we do not\n have stat information about a file it will be kept. Return a list of\n invalidated filenames. None is returne...
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
is_cached
python
def is_cached(file_or_script): if isinstance(file_or_script, str): return unmap_file(file_or_script) in file_cache else: return is_cached_script(file_or_script) return
Return True if file_or_script is cached
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L309-L315
[ "def is_cached_script(filename):\n return unmap_file(filename) in list(script_cache.keys())\n", "def unmap_file(filename):\n # FIXME: this is wrong?\n return file2file_remap.get(filename, filename)\n" ]
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
getline
python
def getline(file_or_script, line_number, opts=default_opts): filename = unmap_file(file_or_script) filename, line_number = unmap_file_line(filename, line_number) lines = getlines(filename, opts) if lines and line_number >=1 and line_number <= maxline(filename): line = lines[line_number-1] ...
Get line *line_number* from file named *file_or_script*. Return None if there was a problem or it is not found. Example: lines = pyficache.getline("/tmp/myfile.py")
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L324-L344
[ "def getlines(filename, opts=default_opts):\n \"\"\"Read lines of *filename* and cache the results. However, if\n *filename* was previously cached use the results from the\n cache. Return *None* if we can not get lines\n \"\"\"\n if get_option('reload_on_change', opts): checkcache(filename)\n fmt ...
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
getlines
python
def getlines(filename, opts=default_opts): if get_option('reload_on_change', opts): checkcache(filename) fmt = get_option('output', opts) highlight_opts = {'bg': fmt} cs = opts.get('style') # Colorstyle of Terminal255Formatter takes precidence over # light/dark colorthemes of TerminalFormatter ...
Read lines of *filename* and cache the results. However, if *filename* was previously cached use the results from the cache. Return *None* if we can not get lines
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L346-L371
[ "def checkcache(filename=None, opts=False):\n \"\"\"Discard cache entries that are out of date. If *filename* is *None*\n all entries in the file cache *file_cache* are checked. If we do not\n have stat information about a file it will be kept. Return a list of\n invalidated filenames. None is returne...
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
path
python
def path(filename): filename = unmap_file(filename) if filename not in file_cache: return None return file_cache[filename].path
Return full filename path for filename
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L407-L412
[ "def unmap_file(filename):\n # FIXME: this is wrong?\n return file2file_remap.get(filename, filename)\n" ]
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
remap_file_lines
python
def remap_file_lines(from_path, to_path, line_map_list): from_path = pyc2py(from_path) cache_file(to_path) remap_entry = file2file_remap_lines.get(to_path) if remap_entry: new_list = list(remap_entry.from_to_pairs) + list(line_map_list) else: new_list = line_map_list # FIXME: loo...
Adds line_map list to the list of association of from_file to to to_file
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L419-L434
[ "def cache_file(filename, reload_on_change=False, opts=default_opts):\n \"\"\"Cache filename if it is not already cached.\n Return the expanded filename for it in the cache\n or nil if we can not find the file.\"\"\"\n filename = pyc2py(filename)\n if filename in file_cache:\n if reload_on_cha...
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
remove_remap_file
python
def remove_remap_file(filename): global file2file_remap if filename in file2file_remap: retval = file2file_remap[filename] del file2file_remap[filename] return retval return None
Remove any mapping for *filename* and return that if it exists
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L436-L443
null
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
sha1
python
def sha1(filename): filename = unmap_file(filename) if filename not in file_cache: cache_file(filename) if filename not in file_cache: return None pass if file_cache[filename].sha1: return file_cache[filename].sha1.hexdigest() sha1 = hashlib.sha1() for lin...
Return SHA1 of filename.
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L445-L460
[ "def cache_file(filename, reload_on_change=False, opts=default_opts):\n \"\"\"Cache filename if it is not already cached.\n Return the expanded filename for it in the cache\n or nil if we can not find the file.\"\"\"\n filename = pyc2py(filename)\n if filename in file_cache:\n if reload_on_cha...
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
size
python
def size(filename, use_cache_only=False): filename = unmap_file(filename) if filename not in file_cache: if not use_cache_only: cache_file(filename) if filename not in file_cache: return None pass return len(file_cache[filename].lines['plain'])
Return the number of lines in filename. If `use_cache_only' is False, we'll try to fetch the file if it is not cached.
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L462-L471
[ "def cache_file(filename, reload_on_change=False, opts=default_opts):\n \"\"\"Cache filename if it is not already cached.\n Return the expanded filename for it in the cache\n or nil if we can not find the file.\"\"\"\n filename = pyc2py(filename)\n if filename in file_cache:\n if reload_on_cha...
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
maxline
python
def maxline(filename, use_cache_only=False): if filename not in file2file_remap_lines: return size(filename, use_cache_only) max_lineno = -1 remap_line_entry = file2file_remap_lines.get(filename) if not remap_line_entry: return size(filename, use_cache_only) for t in remap_line_entry...
Return the maximum line number filename after taking into account line remapping. If no remapping then this is the same as size
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L473-L487
[ "def size(filename, use_cache_only=False):\n \"\"\"Return the number of lines in filename. If `use_cache_only' is False,\n we'll try to fetch the file if it is not cached.\"\"\"\n filename = unmap_file(filename)\n if filename not in file_cache:\n if not use_cache_only: cache_file(filename)\n ...
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
stat
python
def stat(filename, use_cache_only=False): filename = pyc2py(filename) if filename not in file_cache: if not use_cache_only: cache_file(filename) if filename not in file_cache: return None pass return file_cache[filename].stat
Return stat() info for *filename*. If *use_cache_only* is *False*, we will try to fetch the file if it is not cached.
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L489-L498
[ "def cache_file(filename, reload_on_change=False, opts=default_opts):\n \"\"\"Cache filename if it is not already cached.\n Return the expanded filename for it in the cache\n or nil if we can not find the file.\"\"\"\n filename = pyc2py(filename)\n if filename in file_cache:\n if reload_on_cha...
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
trace_line_numbers
python
def trace_line_numbers(filename, reload_on_change=False): fullname = cache_file(filename, reload_on_change) if not fullname: return None e = file_cache[filename] if not e.line_numbers: if hasattr(coverage.coverage, 'analyze_morf'): e.line_numbers = coverage.the_coverage.analyze_morf(...
Return an Array of breakpoints in filename. The list will contain an entry for each distinct line event call so it is possible (and possibly useful) for a line number appear more than once.
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L500-L517
[ "def cache_file(filename, reload_on_change=False, opts=default_opts):\n \"\"\"Cache filename if it is not already cached.\n Return the expanded filename for it in the cache\n or nil if we can not find the file.\"\"\"\n filename = pyc2py(filename)\n if filename in file_cache:\n if reload_on_cha...
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
rocky/python-filecache
pyficache/main.py
update_cache
python
def update_cache(filename, opts=default_opts, module_globals=None): if not filename: return None orig_filename = filename filename = pyc2py(filename) if filename in file_cache: del file_cache[filename] path = os.path.abspath(filename) stat = None if get_option('use_linecache_lines', opts):...
Update a cache entry. If something is wrong, return *None*. Return *True* if the cache was updated and *False* if not. If *use_linecache_lines* is *True*, use an existing cache entry as source for the lines of the file.
train
https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L560-L676
[ "def highlight_array(array, trailing_nl=True,\n bg='light', **options):\n fmt_array = highlight_string(''.join(array),\n bg, **options).split('\\n')\n lines = [ line + \"\\n\" for line in fmt_array ]\n if not trailing_nl: lines[-1] = lines[-1].rstrip('\\n'...
# -*- coding: utf-8 -*- # Copyright (C) 2008-2009, 2012-2013, 2015-2016, 2018 # Rocky Bernstein <rocky@gnu.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of th...
Min-ops/cruddy
cruddy/__init__.py
CRUD.describe
python
def describe(self, **kwargs): response = self._new_response() description = { 'cruddy_version': __version__, 'table_name': self.table_name, 'supported_operations': copy.copy(self.supported_ops), 'prototype': copy.deepcopy(self.prototype), 'oper...
Returns descriptive information about this cruddy handler and the methods supported by it.
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/__init__.py#L181-L212
[ "def _new_response(self):\n return CRUDResponse(self._debug)\n" ]
class CRUD(object): SupportedOps = ["create", "update", "get", "delete", "bulk_delete", "list", "search", "increment_counter", "describe", "ping"] def __init__(self, **kwargs): """ Create a new CRUD handler. The CRUD handler accepts the following ...
Min-ops/cruddy
cruddy/__init__.py
CRUD.search
python
def search(self, query, **kwargs): response = self._new_response() if self._check_supported_op('search', response): if '=' not in query: response.status = 'error' response.error_type = 'InvalidQuery' msg = 'Only the = operation is supported' ...
Cruddy provides a limited but useful interface to search GSI indexes in DynamoDB with the following limitations (hopefully some of these will be expanded or eliminated in the future. * The GSI must be configured with a only HASH and not a RANGE. * The only operation supported in the que...
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/__init__.py#L214-L266
[ "def _check_supported_op(self, op_name, response):\n if op_name not in self.supported_ops:\n response.status = 'error'\n response.error_type = 'UnsupportedOperation'\n response.error_message = 'Unsupported operation: {}'.format(\n op_name)\n return False\n return True\n"...
class CRUD(object): SupportedOps = ["create", "update", "get", "delete", "bulk_delete", "list", "search", "increment_counter", "describe", "ping"] def __init__(self, **kwargs): """ Create a new CRUD handler. The CRUD handler accepts the following ...
Min-ops/cruddy
cruddy/__init__.py
CRUD.list
python
def list(self, **kwargs): response = self._new_response() if self._check_supported_op('list', response): self._call_ddb_method(self.table.scan, {}, response) if response.status == 'success': response.data = self._replace_decimals( response.raw_...
Returns a list of items in the database. Encrypted attributes are not decrypted when listing items.
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/__init__.py#L268-L280
[ "def _check_supported_op(self, op_name, response):\n if op_name not in self.supported_ops:\n response.status = 'error'\n response.error_type = 'UnsupportedOperation'\n response.error_message = 'Unsupported operation: {}'.format(\n op_name)\n return False\n return True\n"...
class CRUD(object): SupportedOps = ["create", "update", "get", "delete", "bulk_delete", "list", "search", "increment_counter", "describe", "ping"] def __init__(self, **kwargs): """ Create a new CRUD handler. The CRUD handler accepts the following ...
Min-ops/cruddy
cruddy/__init__.py
CRUD.get
python
def get(self, id, decrypt=False, id_name='id', **kwargs): response = self._new_response() if self._check_supported_op('get', response): if id is None: response.status = 'error' response.error_type = 'IDRequired' response.error_message = 'Get re...
Returns the item corresponding to ``id``. If the ``decrypt`` param is not False (the default) any encrypted attributes in the item will be decrypted before the item is returned. If not, the encrypted attributes will contain the encrypted value.
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/__init__.py#L282-L313
[ "def _check_supported_op(self, op_name, response):\n if op_name not in self.supported_ops:\n response.status = 'error'\n response.error_type = 'UnsupportedOperation'\n response.error_message = 'Unsupported operation: {}'.format(\n op_name)\n return False\n return True\n"...
class CRUD(object): SupportedOps = ["create", "update", "get", "delete", "bulk_delete", "list", "search", "increment_counter", "describe", "ping"] def __init__(self, **kwargs): """ Create a new CRUD handler. The CRUD handler accepts the following ...
Min-ops/cruddy
cruddy/__init__.py
CRUD.create
python
def create(self, item, **kwargs): response = self._new_response() if self._prototype_handler.check(item, 'create', response): self._encrypt(item) params = {'Item': item} self._call_ddb_method(self.table.put_item, params, response) ...
Creates a new item. You pass in an item containing initial values. Any attribute names defined in ``prototype`` that are missing from the item will be added using the default value defined in ``prototype``.
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/__init__.py#L315-L330
[ "def _new_response(self):\n return CRUDResponse(self._debug)\n" ]
class CRUD(object): SupportedOps = ["create", "update", "get", "delete", "bulk_delete", "list", "search", "increment_counter", "describe", "ping"] def __init__(self, **kwargs): """ Create a new CRUD handler. The CRUD handler accepts the following ...
Min-ops/cruddy
cruddy/__init__.py
CRUD.update
python
def update(self, item, encrypt=True, **kwargs): response = self._new_response() if self._check_supported_op('update', response): if self._prototype_handler.check(item, 'update', response): if encrypt: self._encrypt(item) params = {'Item': i...
Updates the item based on the current values of the dictionary passed in.
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/__init__.py#L332-L348
[ "def _check_supported_op(self, op_name, response):\n if op_name not in self.supported_ops:\n response.status = 'error'\n response.error_type = 'UnsupportedOperation'\n response.error_message = 'Unsupported operation: {}'.format(\n op_name)\n return False\n return True\n"...
class CRUD(object): SupportedOps = ["create", "update", "get", "delete", "bulk_delete", "list", "search", "increment_counter", "describe", "ping"] def __init__(self, **kwargs): """ Create a new CRUD handler. The CRUD handler accepts the following ...
Min-ops/cruddy
cruddy/__init__.py
CRUD.increment_counter
python
def increment_counter(self, id, counter_name, increment=1, id_name='id', **kwargs): response = self._new_response() if self._check_supported_op('increment_counter', response): params = { 'Key': {id_name: id}, 'UpdateExpression': 'set ...
Atomically increments a counter attribute in the item identified by ``id``. You must specify the name of the attribute as ``counter_name`` and, optionally, the ``increment`` which defaults to ``1``.
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/__init__.py#L350-L374
[ "def _check_supported_op(self, op_name, response):\n if op_name not in self.supported_ops:\n response.status = 'error'\n response.error_type = 'UnsupportedOperation'\n response.error_message = 'Unsupported operation: {}'.format(\n op_name)\n return False\n return True\n"...
class CRUD(object): SupportedOps = ["create", "update", "get", "delete", "bulk_delete", "list", "search", "increment_counter", "describe", "ping"] def __init__(self, **kwargs): """ Create a new CRUD handler. The CRUD handler accepts the following ...
Min-ops/cruddy
cruddy/__init__.py
CRUD.delete
python
def delete(self, id, id_name='id', **kwargs): response = self._new_response() if self._check_supported_op('delete', response): params = {'Key': {id_name: id}} self._call_ddb_method(self.table.delete_item, params, response) response.data = 'true' response.prepa...
Deletes the item corresponding to ``id``.
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/__init__.py#L376-L386
[ "def _check_supported_op(self, op_name, response):\n if op_name not in self.supported_ops:\n response.status = 'error'\n response.error_type = 'UnsupportedOperation'\n response.error_message = 'Unsupported operation: {}'.format(\n op_name)\n return False\n return True\n"...
class CRUD(object): SupportedOps = ["create", "update", "get", "delete", "bulk_delete", "list", "search", "increment_counter", "describe", "ping"] def __init__(self, **kwargs): """ Create a new CRUD handler. The CRUD handler accepts the following ...
Min-ops/cruddy
cruddy/__init__.py
CRUD.bulk_delete
python
def bulk_delete(self, query, **kwargs): response = self._new_response() if self._check_supported_op('search', response): n = 0 pe = 'id' response = self.search(query, projection_expression=pe, **kwargs) while response.status == 'success' and response.data:...
Perform a search and delete all items that match.
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/__init__.py#L388-L408
[ "def _check_supported_op(self, op_name, response):\n if op_name not in self.supported_ops:\n response.status = 'error'\n response.error_type = 'UnsupportedOperation'\n response.error_message = 'Unsupported operation: {}'.format(\n op_name)\n return False\n return True\n"...
class CRUD(object): SupportedOps = ["create", "update", "get", "delete", "bulk_delete", "list", "search", "increment_counter", "describe", "ping"] def __init__(self, **kwargs): """ Create a new CRUD handler. The CRUD handler accepts the following ...
Min-ops/cruddy
cruddy/__init__.py
CRUD.handler
python
def handler(self, operation=None, **kwargs): response = self._new_response() if operation is None: response.status = 'error' response.error_type = 'MissingOperation' response.error_message = 'You must pass an operation' return response operation = ...
In addition to the methods described above, cruddy also provides a generic handler interface. This is mainly useful when you want to wrap a cruddy handler in a Lambda function and then call that Lambda function to access the CRUD capabilities. To call the handler, you simply put all ne...
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/__init__.py#L410-L445
[ "def _check_supported_op(self, op_name, response):\n if op_name not in self.supported_ops:\n response.status = 'error'\n response.error_type = 'UnsupportedOperation'\n response.error_message = 'Unsupported operation: {}'.format(\n op_name)\n return False\n return True\n"...
class CRUD(object): SupportedOps = ["create", "update", "get", "delete", "bulk_delete", "list", "search", "increment_counter", "describe", "ping"] def __init__(self, **kwargs): """ Create a new CRUD handler. The CRUD handler accepts the following ...
Min-ops/cruddy
cruddy/scripts/cli.py
cli
python
def cli(ctx, profile, region, lambda_fn, config, debug): ctx.obj = CLIHandler(profile, region, lambda_fn, config, debug)
cruddy is a CLI interface to the cruddy handler. It can be used in one of two ways. First, you can pass in a ``--config`` option which is a JSON file containing all of your cruddy parameters and the CLI will create a cruddy handler to manipulate the DynamoDB table directly. Alternatively, you can...
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/scripts/cli.py#L90-L104
null
# Copyright (c) 2016 CloudNative, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # dis...
Min-ops/cruddy
cruddy/scripts/cli.py
get
python
def get(handler, item_id, decrypt): data = {'operation': 'get', 'decrypt': decrypt, 'id': item_id} handler.invoke(data)
Get an item
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/scripts/cli.py#L130-L135
null
# Copyright (c) 2016 CloudNative, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # dis...
Min-ops/cruddy
cruddy/scripts/cli.py
delete
python
def delete(handler, item_id, id_name): data = {'operation': 'delete', 'id': item_id, 'id_name': id_name} handler.invoke(data)
Delete an item
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/scripts/cli.py#L142-L147
null
# Copyright (c) 2016 CloudNative, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # dis...
Min-ops/cruddy
cruddy/scripts/cli.py
increment
python
def increment(handler, increment, item_id, counter_name): data = {'operation': 'increment_counter', 'id': item_id, 'counter_name': counter_name, 'increment': increment} handler.invoke(data)
Increment a counter attribute atomically
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/scripts/cli.py#L175-L181
null
# Copyright (c) 2016 CloudNative, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # dis...
Min-ops/cruddy
cruddy/scripts/cli.py
create
python
def create(handler, item_document): data = {'operation': 'create', 'item': json.load(item_document)} handler.invoke(data)
Create a new item from a JSON document
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/scripts/cli.py#L187-L191
null
# Copyright (c) 2016 CloudNative, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # dis...
Min-ops/cruddy
cruddy/scripts/cli.py
update
python
def update(handler, item_document): data = {'operation': 'update', 'encrypt': encrypt, 'item': json.load(item_document)} handler.invoke(data)
Update an item from a JSON document
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/scripts/cli.py#L201-L206
null
# Copyright (c) 2016 CloudNative, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # dis...
Min-ops/cruddy
cruddy/scripts/cli.py
help
python
def help(handler): data = {'operation': 'describe'} response = handler.invoke(data, raw=True) description = response.data lines = [] lines.append('# {}'.format(handler.lambda_fn)) lines.append('## Handler Info') lines.append('**Cruddy version**: {}'.format( description['cruddy_versio...
Returns a Markdown document that describes this handler and it's operations.
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/scripts/cli.py#L231-L271
[ "def _build_signature_line(method_name, argspec):\n arg_len = len(argspec['args'])\n if argspec['defaults']:\n defaults_offset = arg_len - len(argspec['defaults'])\n else:\n defaults_offset = 0\n signature = '**{}**('.format(method_name)\n params = []\n for i in range(0, arg_len):\n ...
# Copyright (c) 2016 CloudNative, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # dis...
Min-ops/cruddy
cruddy/lambdaclient.py
LambdaClient.call_operation
python
def call_operation(self, operation, **kwargs): data = {'operation': operation} data.update(kwargs) return self.invoke(data)
A generic method to call any operation supported by the Lambda handler
train
https://github.com/Min-ops/cruddy/blob/b9ba3dda1757e1075bc1c62a6f43473eea27de41/cruddy/lambdaclient.py#L62-L68
[ "def invoke(self, payload):\n try:\n response = self._lambda_client.invoke(\n FunctionName=self.func_name,\n InvocationType='RequestResponse',\n Payload=json.dumps(payload)\n )\n LOG.debug('response: %s', response)\n if response.get('StatusCode') == 20...
class LambdaClient(object): def __init__(self, func_name, profile_name=None, region_name=None, **kwargs): self.func_name = func_name self._lambda_client = None session = boto3.Session( profile_name=profile_name, region_name=region_name) self._lambda_clie...
aroberge/experimental
experimental/core/console.py
start_console
python
def start_console(local_vars={}): '''Starts a console; modified from code.interact''' transforms.CONSOLE_ACTIVE = True transforms.remove_not_allowed_in_console() sys.ps1 = prompt console = ExperimentalInteractiveConsole(locals=local_vars) console.interact(banner=banner)
Starts a console; modified from code.interact
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/core/console.py#L66-L72
[ "def remove_not_allowed_in_console():\n '''This function should be called from the console, when it starts.\n\n Some transformers are not allowed in the console and they could have\n been loaded prior to the console being activated. We effectively remove them\n and print an information message specific ...
#pylint: disable=W0102, C0103 import code import platform import os import sys from . import transforms from .. import version # define banner and prompt here so that they can be imported in tests banner = "experimental console version {}. [Python version: {}]\n".format( version.__version__, platform.pyt...
aroberge/experimental
experimental/core/console.py
ExperimentalInteractiveConsole.push
python
def push(self, line): if transforms.FROM_EXPERIMENTAL.match(line): transforms.add_transformers(line) self.buffer.append("\n") else: self.buffer.append(line) add_pass = False if line.rstrip(' ').endswith(":"): add_pass = True source...
Transform and push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter's runsource() method is called with the concatenated contents of the buffer as source. If this indicat...
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/core/console.py#L21-L63
null
class ExperimentalInteractiveConsole(code.InteractiveConsole): '''A Python console that emulates the normal Python interpreter except that it support experimental code transformations.'''
aroberge/experimental
experimental/core/transforms.py
add_transformers
python
def add_transformers(line): '''Extract the transformers names from a line of code of the form from __experimental__ import transformer1 [,...] and adds them to the globally known dict ''' assert FROM_EXPERIMENTAL.match(line) line = FROM_EXPERIMENTAL.sub(' ', line) # we now have: " tra...
Extract the transformers names from a line of code of the form from __experimental__ import transformer1 [,...] and adds them to the globally known dict
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/core/transforms.py#L19-L31
[ "def import_transformer(name):\n '''If needed, import a transformer, and adds it to the globally known dict\n The code inside a module where a transformer is defined should be\n standard Python code, which does not need any transformation.\n So, we disable the import hook, and let the normal mo...
#pylint: disable=W1401, C0103, W0703 '''This module takes care of identifying, importing and adding source code transformers. It also contains a function, `transform`, which takes care of invoking all known transformers to convert a source code. ''' import re import sys FROM_EXPERIMENTAL = re.compile("(^from\s+__exper...
aroberge/experimental
experimental/core/transforms.py
import_transformer
python
def import_transformer(name): '''If needed, import a transformer, and adds it to the globally known dict The code inside a module where a transformer is defined should be standard Python code, which does not need any transformation. So, we disable the import hook, and let the normal module impo...
If needed, import a transformer, and adds it to the globally known dict The code inside a module where a transformer is defined should be standard Python code, which does not need any transformation. So, we disable the import hook, and let the normal module import do its job - which is faste...
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/core/transforms.py#L34-L70
null
#pylint: disable=W1401, C0103, W0703 '''This module takes care of identifying, importing and adding source code transformers. It also contains a function, `transform`, which takes care of invoking all known transformers to convert a source code. ''' import re import sys FROM_EXPERIMENTAL = re.compile("(^from\s+__exper...
aroberge/experimental
experimental/core/transforms.py
extract_transformers_from_source
python
def extract_transformers_from_source(source): '''Scan a source for lines of the form from __experimental__ import transformer1 [,...] identifying transformers to be used. Such line is passed to the add_transformer function, after which it is removed from the code to be executed. ''' ...
Scan a source for lines of the form from __experimental__ import transformer1 [,...] identifying transformers to be used. Such line is passed to the add_transformer function, after which it is removed from the code to be executed.
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/core/transforms.py#L72-L89
[ "def add_transformers(line):\n '''Extract the transformers names from a line of code of the form\n from __experimental__ import transformer1 [,...]\n and adds them to the globally known dict\n '''\n assert FROM_EXPERIMENTAL.match(line)\n\n line = FROM_EXPERIMENTAL.sub(' ', line)\n # we no...
#pylint: disable=W1401, C0103, W0703 '''This module takes care of identifying, importing and adding source code transformers. It also contains a function, `transform`, which takes care of invoking all known transformers to convert a source code. ''' import re import sys FROM_EXPERIMENTAL = re.compile("(^from\s+__exper...
aroberge/experimental
experimental/core/transforms.py
remove_not_allowed_in_console
python
def remove_not_allowed_in_console(): '''This function should be called from the console, when it starts. Some transformers are not allowed in the console and they could have been loaded prior to the console being activated. We effectively remove them and print an information message specific to that tr...
This function should be called from the console, when it starts. Some transformers are not allowed in the console and they could have been loaded prior to the console being activated. We effectively remove them and print an information message specific to that transformer as written in the transformer ...
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/core/transforms.py#L91-L111
null
#pylint: disable=W1401, C0103, W0703 '''This module takes care of identifying, importing and adding source code transformers. It also contains a function, `transform`, which takes care of invoking all known transformers to convert a source code. ''' import re import sys FROM_EXPERIMENTAL = re.compile("(^from\s+__exper...
aroberge/experimental
experimental/core/transforms.py
transform
python
def transform(source): '''Used to convert the source code, making use of known transformers. "transformers" are modules which must contain a function transform_source(source) which returns a tranformed source. Some transformers (for example, those found in the standard library ...
Used to convert the source code, making use of known transformers. "transformers" are modules which must contain a function transform_source(source) which returns a tranformed source. Some transformers (for example, those found in the standard library module lib2to3) cannot cop...
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/core/transforms.py#L114-L160
[ "def import_transformer(name):\n '''If needed, import a transformer, and adds it to the globally known dict\n The code inside a module where a transformer is defined should be\n standard Python code, which does not need any transformation.\n So, we disable the import hook, and let the normal mo...
#pylint: disable=W1401, C0103, W0703 '''This module takes care of identifying, importing and adding source code transformers. It also contains a function, `transform`, which takes care of invoking all known transformers to convert a source code. ''' import re import sys FROM_EXPERIMENTAL = re.compile("(^from\s+__exper...
aroberge/experimental
experimental/core/import_hook.py
MyMetaFinder.find_spec
python
def find_spec(self, fullname, path, target=None): '''finds the appropriate properties (spec) of a module, and sets its loader.''' if not path: path = [os.getcwd()] if "." in fullname: name = fullname.split(".")[-1] else: name = fullname ...
finds the appropriate properties (spec) of a module, and sets its loader.
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/core/import_hook.py#L47-L70
null
class MyMetaFinder(MetaPathFinder): '''A custom finder to locate modules. The main reason for this code is to ensure that our custom loader, which does the code transformations, is used.''' # we don't know how to import this
aroberge/experimental
experimental/core/import_hook.py
MyLoader.exec_module
python
def exec_module(self, module): '''import the source code, transforma it before executing it so that it is known to Python.''' global MAIN_MODULE_NAME if module.__name__ == MAIN_MODULE_NAME: module.__name__ = "__main__" MAIN_MODULE_NAME = None with open...
import the source code, transforma it before executing it so that it is known to Python.
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/core/import_hook.py#L83-L103
[ "def transform(source):\n '''Used to convert the source code, making use of known transformers.\n\n \"transformers\" are modules which must contain a function\n\n transform_source(source)\n\n which returns a tranformed source.\n Some transformers (for example, those found in the stand...
class MyLoader(Loader): '''A custom loader which will transform the source prior to its execution''' def __init__(self, filename): self.filename = filename def create_module(self, spec): return None # use default module creation semantics def get_code(self, _): '''Hack to sile...
aroberge/experimental
experimental/transformers/repeat_keyword.py
transform_source
python
def transform_source(text): '''Replaces instances of repeat n: by for __VAR_i in range(n): where __VAR_i is a string that does not appear elsewhere in the code sample. ''' loop_keyword = 'repeat' nb = text.count(loop_keyword) if nb == 0: return text var_...
Replaces instances of repeat n: by for __VAR_i in range(n): where __VAR_i is a string that does not appear elsewhere in the code sample.
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/transformers/repeat_keyword.py#L29-L70
[ "def get_unique_variable_names(text, nb):\n '''returns a list of possible variables names that\n are not found in the original text.'''\n base_name = '__VAR_'\n var_names = []\n i = 0\n j = 0\n while j < nb:\n tentative_name = base_name + str(i)\n if text.count(tentative_name) ...
''' from __experimental__ import repeat_keyword introduces `repeat` as a keyword to write simple loops that repeat a set number of times. That is: repeat 3: a = 2 repeat a*a: pass is equivalent to for __VAR_1 in range(3): a = 2 for __VAR_2 in range(a*a): ...
aroberge/experimental
experimental/transformers/repeat_keyword.py
get_unique_variable_names
python
def get_unique_variable_names(text, nb): '''returns a list of possible variables names that are not found in the original text.''' base_name = '__VAR_' var_names = [] i = 0 j = 0 while j < nb: tentative_name = base_name + str(i) if text.count(tentative_name) == 0 and tenta...
returns a list of possible variables names that are not found in the original text.
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/transformers/repeat_keyword.py#L75-L89
null
''' from __experimental__ import repeat_keyword introduces `repeat` as a keyword to write simple loops that repeat a set number of times. That is: repeat 3: a = 2 repeat a*a: pass is equivalent to for __VAR_1 in range(3): a = 2 for __VAR_2 in range(a*a): ...
aroberge/experimental
experimental/transformers/utils/one2one.py
translate
python
def translate(source, dictionary): '''A dictionary with a one-to-one translation of keywords is used to provide the transformation. ''' toks = tokenize.generate_tokens(StringIO(source).readline) result = [] for toktype, tokvalue, _, _, _ in toks: if toktype == tokenize.NAME and tokvalue ...
A dictionary with a one-to-one translation of keywords is used to provide the transformation.
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/transformers/utils/one2one.py#L12-L23
null
'''This module contains a single function: translate. Using the tokenize module, this function parses some source code an apply a translation based on a one-to-one translation table represented by a Python dict. ''' from io import StringIO import tokenize
aroberge/experimental
experimental/transformers/int_seq.py
__experimental_range
python
def __experimental_range(start, stop, var, cond, loc={}): '''Utility function made to reproduce range() with unit integer step but with the added possibility of specifying a condition on the looping variable (e.g. var % 2 == 0) ''' locals().update(loc) if start < stop: for __ in ...
Utility function made to reproduce range() with unit integer step but with the added possibility of specifying a condition on the looping variable (e.g. var % 2 == 0)
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/transformers/int_seq.py#L51-L66
null
''' from __experimental__ import int_seq makes it possible to use an alternative syntax instead of using `range` in a for loop. To be more specific, instead of for i in range(3): print(i) we could write for i in 0 <= i < 3: print(i) or for i in 0 <= i <= 2: # compare upper bounda...
aroberge/experimental
experimental/transformers/int_seq.py
create_for
python
def create_for(line, search_result): '''Create a new "for loop" line as a replacement for the original code. ''' try: return line.format(search_result.group("indented_for"), search_result.group("var"), search_result.group("start"), ...
Create a new "for loop" line as a replacement for the original code.
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/transformers/int_seq.py#L180-L193
null
''' from __experimental__ import int_seq makes it possible to use an alternative syntax instead of using `range` in a for loop. To be more specific, instead of for i in range(3): print(i) we could write for i in 0 <= i < 3: print(i) or for i in 0 <= i <= 2: # compare upper bounda...
aroberge/experimental
experimental/transformers/switch_statement.py
transform_source
python
def transform_source(text): '''Replaces instances of switch expression: by for __case in _Switch(n): and replaces case expression: by if __case(expression): and default: by if __case(): ''' toks = tokenize.generate_tokens(StringIO...
Replaces instances of switch expression: by for __case in _Switch(n): and replaces case expression: by if __case(expression): and default: by if __case():
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/transformers/switch_statement.py#L73-L125
null
'''from __experimental__ import switch_statement allows the use of a Pythonic switch statement (implemented with if clauses). A current limitation is that there can only be one level of switch statement i.e. you cannot have a switch statement inside a case of another switch statement. Here's an example usage def...
aroberge/experimental
experimental/transformers/utils/simple2to3.py
get_lib2to3_fixers
python
def get_lib2to3_fixers(): '''returns a list of all fixers found in the lib2to3 library''' fixers = [] fixer_dirname = fixer_dir.__path__[0] for name in sorted(os.listdir(fixer_dirname)): if name.startswith("fix_") and name.endswith(".py"): fixers.append("lib2to3.fixes." + name[:-3]) ...
returns a list of all fixers found in the lib2to3 library
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/transformers/utils/simple2to3.py#L10-L17
null
import os from lib2to3.refactor import RefactoringTool import lib2to3.fixes as fixer_dir # This simple module appears to be incompatible with the import # hook. For this reason, it is important to wrap calls to it # with a try/except clause. I have found that a bare except, # that catches all errors, is definitely th...
aroberge/experimental
experimental/transformers/utils/simple2to3.py
get_single_fixer
python
def get_single_fixer(fixname): '''return a single fixer found in the lib2to3 library''' fixer_dirname = fixer_dir.__path__[0] for name in sorted(os.listdir(fixer_dirname)): if (name.startswith("fix_") and name.endswith(".py") and fixname == name[4:-3]): return "lib2to3.fixes...
return a single fixer found in the lib2to3 library
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/transformers/utils/simple2to3.py#L20-L26
null
import os from lib2to3.refactor import RefactoringTool import lib2to3.fixes as fixer_dir # This simple module appears to be incompatible with the import # hook. For this reason, it is important to wrap calls to it # with a try/except clause. I have found that a bare except, # that catches all errors, is definitely th...
aroberge/experimental
experimental/transformers/where_clause.py
transform_source
python
def transform_source(text): '''removes a "where" clause which is identified by the use of "where" as an identifier and ends at the first DEDENT (i.e. decrease in indentation)''' toks = tokenize.generate_tokens(StringIO(text).readline) result = [] where_clause = False for toktype, tokvalue, _, _,...
removes a "where" clause which is identified by the use of "where" as an identifier and ends at the first DEDENT (i.e. decrease in indentation)
train
https://github.com/aroberge/experimental/blob/031a9be10698b429998436da748b8fdb86f18b47/experimental/transformers/where_clause.py#L31-L46
null
''' from __experimental__ import where_clause shows how one could use `where` as a keyword to introduce a code block that would be ignored by Python. The idea was to use this as a _pythonic_ notation as an alternative for the optional type hinting described in PEP484. **This idea has been rejected** as it would no...
persandstrom/python-verisure
verisure/session.py
Session.login
python
def login(self): if os.path.exists(self._cookieFileName): with open(self._cookieFileName, 'r') as cookieFile: self._vid = cookieFile.read().strip() try: self._get_installations() except ResponseError: self._vid = None ...
Login to verisure app api Login before calling any read or write commands
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L73-L95
null
class Session(object): """ Verisure app session Args: username (str): Username used to login to verisure app password (str): Password used to login to verisure app """ def __init__(self, username, password, cookieFileName='~/.verisure-cookie'): self._username ...
persandstrom/python-verisure
verisure/session.py
Session._get_installations
python
def _get_installations(self): response = None for base_url in urls.BASE_URLS: urls.BASE_URL = base_url try: response = requests.get( urls.get_installations(self._username), headers={ 'Cookie': 'vid={}...
Get information about installations
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L127-L150
null
class Session(object): """ Verisure app session Args: username (str): Username used to login to verisure app password (str): Password used to login to verisure app """ def __init__(self, username, password, cookieFileName='~/.verisure-cookie'): self._username ...
persandstrom/python-verisure
verisure/session.py
Session.get_overview
python
def get_overview(self): response = None try: response = requests.get( urls.overview(self._giid), headers={ 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Encoding': 'gzip, deflate', ...
Get overview for installation
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L160-L174
[ "def overview(guid):\n return installation(guid) + 'overview'.format(\n installation=installation)\n", "def _validate_response(response):\n \"\"\" Verify that response is OK \"\"\"\n if response.status_code == 200:\n return\n raise ResponseError(response.status_code, response.text)\n" ]
class Session(object): """ Verisure app session Args: username (str): Username used to login to verisure app password (str): Password used to login to verisure app """ def __init__(self, username, password, cookieFileName='~/.verisure-cookie'): self._username ...
persandstrom/python-verisure
verisure/session.py
Session.set_smartplug_state
python
def set_smartplug_state(self, device_label, state): response = None try: response = requests.post( urls.smartplug(self._giid), headers={ 'Content-Type': 'application/json', 'Cookie': 'vid={}'.format(self._vid)}, ...
Turn on or off smartplug Args: device_label (str): Smartplug device label state (boolean): new status, 'True' or 'False'
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L176-L195
[ "def smartplug(guid):\n return installation(guid) + 'smartplug/state'\n", "def _validate_response(response):\n \"\"\" Verify that response is OK \"\"\"\n if response.status_code == 200:\n return\n raise ResponseError(response.status_code, response.text)\n" ]
class Session(object): """ Verisure app session Args: username (str): Username used to login to verisure app password (str): Password used to login to verisure app """ def __init__(self, username, password, cookieFileName='~/.verisure-cookie'): self._username ...
persandstrom/python-verisure
verisure/session.py
Session.get_history
python
def get_history(self, filters=(), pagesize=15, offset=0): response = None try: response = requests.get( urls.history(self._giid), headers={ 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Cookie': 'vid={}'.f...
Get recent events Args: filters (string set): 'ARM', 'DISARM', 'FIRE', 'INTRUSION', 'TECHNICAL', 'SOS', 'WARNING', 'LOCK', 'UNLOCK' pagesize (int): Number of events to display offset (int): Skip pagesize * o...
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L250-L274
[ "def _validate_response(response):\n \"\"\" Verify that response is OK \"\"\"\n if response.status_code == 200:\n return\n raise ResponseError(response.status_code, response.text)\n", "def history(guid):\n return ('{base_url}/celapi/customereventlog/installation/{guid}'\n + '/eventlo...
class Session(object): """ Verisure app session Args: username (str): Username used to login to verisure app password (str): Password used to login to verisure app """ def __init__(self, username, password, cookieFileName='~/.verisure-cookie'): self._username ...
persandstrom/python-verisure
verisure/session.py
Session.get_climate
python
def get_climate(self, device_label): response = None try: response = requests.get( urls.climate(self._giid), headers={ 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Cookie': 'vid={}'.format(self._vid)}, ...
Get climate history Args: device_label: device label of climate device
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L276-L293
[ "def climate(guid):\n return installation(guid) + 'climate/simple/search'\n", "def _validate_response(response):\n \"\"\" Verify that response is OK \"\"\"\n if response.status_code == 200:\n return\n raise ResponseError(response.status_code, response.text)\n" ]
class Session(object): """ Verisure app session Args: username (str): Username used to login to verisure app password (str): Password used to login to verisure app """ def __init__(self, username, password, cookieFileName='~/.verisure-cookie'): self._username ...
persandstrom/python-verisure
verisure/session.py
Session.set_lock_state
python
def set_lock_state(self, code, device_label, state): response = None try: response = requests.put( urls.set_lockstate(self._giid, device_label, state), headers={ 'Accept': 'application/json, text/javascript, */*; q=0.01', ...
Lock or unlock Args: code (str): Lock code device_label (str): device label of lock state (str): 'lock' or 'unlock'
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L309-L329
[ "def _validate_response(response):\n \"\"\" Verify that response is OK \"\"\"\n if response.status_code == 200:\n return\n raise ResponseError(response.status_code, response.text)\n", "def set_lockstate(guid, device_label, state):\n return installation(guid) + 'device/{device_label}/{state}'.fo...
class Session(object): """ Verisure app session Args: username (str): Username used to login to verisure app password (str): Password used to login to verisure app """ def __init__(self, username, password, cookieFileName='~/.verisure-cookie'): self._username ...
persandstrom/python-verisure
verisure/session.py
Session.get_lock_state_transaction
python
def get_lock_state_transaction(self, transaction_id): response = None try: response = requests.get( urls.get_lockstate_transaction(self._giid, transaction_id), headers={ 'Accept': 'application/json, text/javascript, */*; q=0.01', ...
Get lock state transaction status Args: transaction_id: Transaction ID received from set_lock_state
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L331-L347
[ "def _validate_response(response):\n \"\"\" Verify that response is OK \"\"\"\n if response.status_code == 200:\n return\n raise ResponseError(response.status_code, response.text)\n", "def get_lockstate_transaction(guid, transaction_id):\n return (installation(guid)\n + 'doorlockstat...
class Session(object): """ Verisure app session Args: username (str): Username used to login to verisure app password (str): Password used to login to verisure app """ def __init__(self, username, password, cookieFileName='~/.verisure-cookie'): self._username ...
persandstrom/python-verisure
verisure/session.py
Session.get_lock_config
python
def get_lock_config(self, device_label): response = None try: response = requests.get( urls.lockconfig(self._giid, device_label), headers={ 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Cookie': 'vid={}'.f...
Get lock configuration Args: device_label (str): device label of lock
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L349-L365
[ "def _validate_response(response):\n \"\"\" Verify that response is OK \"\"\"\n if response.status_code == 200:\n return\n raise ResponseError(response.status_code, response.text)\n", "def lockconfig(guid, device_label):\n return installation(guid) + 'device/{device_label}/doorlockconfig'.forma...
class Session(object): """ Verisure app session Args: username (str): Username used to login to verisure app password (str): Password used to login to verisure app """ def __init__(self, username, password, cookieFileName='~/.verisure-cookie'): self._username ...
persandstrom/python-verisure
verisure/session.py
Session.set_lock_config
python
def set_lock_config(self, device_label, volume=None, voice_level=None, auto_lock_enabled=None): response = None data = {} if volume: data['volume'] = volume if voice_level: data['voiceLevel'] = voice_level if auto_lock_enabled is no...
Set lock configuration Args: device_label (str): device label of lock volume (str): 'SILENCE', 'LOW' or 'HIGH' voice_level (str): 'ESSENTIAL' or 'NORMAL' auto_lock_enabled (boolean): auto lock enabled
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L367-L394
[ "def _validate_response(response):\n \"\"\" Verify that response is OK \"\"\"\n if response.status_code == 200:\n return\n raise ResponseError(response.status_code, response.text)\n", "def lockconfig(guid, device_label):\n return installation(guid) + 'device/{device_label}/doorlockconfig'.forma...
class Session(object): """ Verisure app session Args: username (str): Username used to login to verisure app password (str): Password used to login to verisure app """ def __init__(self, username, password, cookieFileName='~/.verisure-cookie'): self._username ...
persandstrom/python-verisure
verisure/session.py
Session.capture_image
python
def capture_image(self, device_label): response = None try: response = requests.post( urls.imagecapture(self._giid, device_label), headers={ 'Content-Type': 'application/json', 'Cookie': 'vid={}'.format(self._vid)}) ...
Capture smartcam image Args: device_label (str): device label of camera
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L396-L411
[ "def _validate_response(response):\n \"\"\" Verify that response is OK \"\"\"\n if response.status_code == 200:\n return\n raise ResponseError(response.status_code, response.text)\n", "def imagecapture(guid, device_label):\n return (installation(guid)\n + 'device/{device_label}/custo...
class Session(object): """ Verisure app session Args: username (str): Username used to login to verisure app password (str): Password used to login to verisure app """ def __init__(self, username, password, cookieFileName='~/.verisure-cookie'): self._username ...
persandstrom/python-verisure
verisure/session.py
Session.get_camera_imageseries
python
def get_camera_imageseries(self, number_of_imageseries=10, offset=0): response = None try: response = requests.get( urls.get_imageseries(self._giid), headers={ 'Accept': 'application/json, text/javascript, */*; q=0.01', ...
Get smartcam image series Args: number_of_imageseries (int): number of image series to get offset (int): skip offset amount of image series
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L413-L437
[ "def _validate_response(response):\n \"\"\" Verify that response is OK \"\"\"\n if response.status_code == 200:\n return\n raise ResponseError(response.status_code, response.text)\n", "def get_imageseries(guid):\n return (installation(guid)\n + 'device/customerimagecamera/imageseries...
class Session(object): """ Verisure app session Args: username (str): Username used to login to verisure app password (str): Password used to login to verisure app """ def __init__(self, username, password, cookieFileName='~/.verisure-cookie'): self._username ...
persandstrom/python-verisure
verisure/session.py
Session.download_image
python
def download_image(self, device_label, image_id, file_name): response = None try: response = requests.get( urls.download_image(self._giid, device_label, image_id), headers={ 'Cookie': 'vid={}'.format(self._vid)}, stream=True...
Download image taken by a smartcam Args: device_label (str): device label of camera image_id (str): image id from image series file_name (str): path to file
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L439-L460
[ "def download_image(guid, device_label, image_id):\n return (installation(guid)\n + 'device/{device_label}/customerimagecamera/image/{image_id}/'\n ).format(\n device_label=device_label,\n image_id=image_id)\n", "def _validate_response(response):\n \"\"\" ...
class Session(object): """ Verisure app session Args: username (str): Username used to login to verisure app password (str): Password used to login to verisure app """ def __init__(self, username, password, cookieFileName='~/.verisure-cookie'): self._username ...
persandstrom/python-verisure
verisure/session.py
Session.logout
python
def logout(self): response = None try: response = requests.delete( urls.login(), headers={ 'Cookie': 'vid={}'.format(self._vid)}) except requests.exceptions.RequestException as ex: raise RequestError(ex) _validat...
Logout and remove vid
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L503-L513
[ "def login():\n return '{base_url}/xbn/2/cookie'.format(\n base_url=BASE_URL)\n", "def _validate_response(response):\n \"\"\" Verify that response is OK \"\"\"\n if response.status_code == 200:\n return\n raise ResponseError(response.status_code, response.text)\n" ]
class Session(object): """ Verisure app session Args: username (str): Username used to login to verisure app password (str): Password used to login to verisure app """ def __init__(self, username, password, cookieFileName='~/.verisure-cookie'): self._username ...
persandstrom/python-verisure
verisure/session.py
Session.set_heat_pump_mode
python
def set_heat_pump_mode(self, device_label, mode): response = None try: response = requests.put( urls.set_heatpump_state(self._giid, device_label), headers={ 'Accept': 'application/json', 'Content-Type': 'application/json...
Set heatpump mode Args: mode (str): 'HEAT', 'COOL', 'FAN' or 'AUTO'
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L529-L546
[ "def _validate_response(response):\n \"\"\" Verify that response is OK \"\"\"\n if response.status_code == 200:\n return\n raise ResponseError(response.status_code, response.text)\n", "def set_heatpump_state(guid, device_label):\n return (installation(guid)\n + 'device/{device_label}...
class Session(object): """ Verisure app session Args: username (str): Username used to login to verisure app password (str): Password used to login to verisure app """ def __init__(self, username, password, cookieFileName='~/.verisure-cookie'): self._username ...
persandstrom/python-verisure
verisure/session.py
Session.set_heat_pump_feature
python
def set_heat_pump_feature(self, device_label, feature): response = None try: response = requests.put( urls.set_heatpump_feature(self._giid, device_label, feature), headers={ 'Accept': 'application/json', 'Content-Type': ...
Set heatpump mode Args: feature: 'QUIET', 'ECONAVI', or 'POWERFUL'
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/session.py#L605-L621
[ "def _validate_response(response):\n \"\"\" Verify that response is OK \"\"\"\n if response.status_code == 200:\n return\n raise ResponseError(response.status_code, response.text)\n", "def set_heatpump_feature(guid, device_label, featurestate):\n return (installation(guid)\n + 'devic...
class Session(object): """ Verisure app session Args: username (str): Username used to login to verisure app password (str): Password used to login to verisure app """ def __init__(self, username, password, cookieFileName='~/.verisure-cookie'): self._username ...
persandstrom/python-verisure
verisure/__main__.py
print_result
python
def print_result(overview, *names): if names: for name in names: toprint = overview for part in name.split('/'): toprint = toprint[part] print(json.dumps(toprint, indent=4, separators=(',', ': '))) else: print(json.dumps(overview, indent=4, sep...
Print the result of a verisure request
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/__main__.py#L22-L31
null
""" Command line interface for Verisure MyPages """ from __future__ import print_function import argparse import json import verisure COMMAND_OVERVIEW = 'overview' COMMAND_SET = 'set' COMMAND_CLIMATE = 'climate' COMMAND_EVENTLOG = 'eventlog' COMMAND_INSTALLATIONS = 'installations' COMMAND_CAPTURE = 'capture' COMMAND_...
persandstrom/python-verisure
verisure/__main__.py
main
python
def main(): parser = argparse.ArgumentParser( description='Read or change status of verisure devices') parser.add_argument( 'username', help='MyPages username') parser.add_argument( 'password', help='MyPages password') parser.add_argument( '-i', '--install...
Start verisure command line
train
https://github.com/persandstrom/python-verisure/blob/babd25e7f8fb2b24f12e4109dfa8a04041e8dcb8/verisure/__main__.py#L35-L261
[ "def print_result(overview, *names):\n \"\"\" Print the result of a verisure request \"\"\"\n if names:\n for name in names:\n toprint = overview\n for part in name.split('/'):\n toprint = toprint[part]\n print(json.dumps(toprint, indent=4, separators=(',...
""" Command line interface for Verisure MyPages """ from __future__ import print_function import argparse import json import verisure COMMAND_OVERVIEW = 'overview' COMMAND_SET = 'set' COMMAND_CLIMATE = 'climate' COMMAND_EVENTLOG = 'eventlog' COMMAND_INSTALLATIONS = 'installations' COMMAND_CAPTURE = 'capture' COMMAND_...
common-workflow-language/workflow-service
wes_client/util.py
get_version
python
def get_version(extension, workflow_file): '''Determines the version of a .py, .wdl, or .cwl file.''' if extension == 'py' and two_seven_compatible(workflow_file): return '2.7' elif extension == 'cwl': return yaml.load(open(workflow_file))['cwlVersion'] else: # Must be a wdl file. ...
Determines the version of a .py, .wdl, or .cwl file.
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_client/util.py#L27-L38
[ "def two_seven_compatible(filePath):\n \"\"\"Determines if a python file is 2.7 compatible by seeing if it compiles in a subprocess\"\"\"\n try:\n check_call(['python2', '-m', 'py_compile', filePath], stderr=DEVNULL)\n except CalledProcessError:\n raise RuntimeError('Python files must be 2.7 ...
import os import json import schema_salad.ref_resolver from subprocess32 import check_call, DEVNULL, CalledProcessError import yaml import glob import requests import logging from wes_service.util import visit from future.standard_library import hooks with hooks(): from urllib.request import urlopen, pathname2ur...
common-workflow-language/workflow-service
wes_client/util.py
wf_info
python
def wf_info(workflow_path): supported_formats = ['py', 'wdl', 'cwl'] file_type = workflow_path.lower().split('.')[-1] # Grab the file extension workflow_path = workflow_path if ':' in workflow_path else 'file://' + workflow_path if file_type in supported_formats: if workflow_path.startswith('...
Returns the version of the file and the file extension. Assumes that the file path is to the file directly ie, ends with a valid file extension.Supports checking local files as well as files at http:// and https:// locations. Files at these remote locations are recreated locally to enable our approach to v...
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_client/util.py#L41-L69
[ "def get_version(extension, workflow_file):\n '''Determines the version of a .py, .wdl, or .cwl file.'''\n if extension == 'py' and two_seven_compatible(workflow_file):\n return '2.7'\n elif extension == 'cwl':\n return yaml.load(open(workflow_file))['cwlVersion']\n else: # Must be a wdl ...
import os import json import schema_salad.ref_resolver from subprocess32 import check_call, DEVNULL, CalledProcessError import yaml import glob import requests import logging from wes_service.util import visit from future.standard_library import hooks with hooks(): from urllib.request import urlopen, pathname2ur...
common-workflow-language/workflow-service
wes_client/util.py
modify_jsonyaml_paths
python
def modify_jsonyaml_paths(jsonyaml_file): loader = schema_salad.ref_resolver.Loader({ "location": {"@type": "@id"}, "path": {"@type": "@id"} }) input_dict, _ = loader.resolve_ref(jsonyaml_file, checklinks=False) basedir = os.path.dirname(jsonyaml_file) def fixpaths(d): """Ma...
Changes relative paths in a json/yaml file to be relative to where the json/yaml file is located. :param jsonyaml_file: Path to a json/yaml file.
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_client/util.py#L72-L98
[ "def visit(d, op):\n \"\"\"Recursively call op(d) for all list subelements and dictionary 'values' that d may have.\"\"\"\n op(d)\n if isinstance(d, list):\n for i in d:\n visit(i, op)\n elif isinstance(d, dict):\n for i in itervalues(d):\n visit(i, op)\n" ]
import os import json import schema_salad.ref_resolver from subprocess32 import check_call, DEVNULL, CalledProcessError import yaml import glob import requests import logging from wes_service.util import visit from future.standard_library import hooks with hooks(): from urllib.request import urlopen, pathname2ur...
common-workflow-language/workflow-service
wes_client/util.py
build_wes_request
python
def build_wes_request(workflow_file, json_path, attachments=None): workflow_file = "file://" + workflow_file if ":" not in workflow_file else workflow_file wfbase = None if json_path.startswith("file://"): wfbase = os.path.dirname(json_path[7:]) json_path = json_path[7:] with open(js...
:param str workflow_file: Path to cwl/wdl file. Can be http/https/file. :param json_path: Path to accompanying json file. :param attachments: Any other files needing to be uploaded to the server. :return: A list of tuples formatted to be sent in a post to the wes-server (Swagger API).
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_client/util.py#L101-L148
[ "def wf_info(workflow_path):\n \"\"\"\n Returns the version of the file and the file extension.\n\n Assumes that the file path is to the file directly ie, ends with a valid file extension.Supports checking local\n files as well as files at http:// and https:// locations. Files at these remote locations ...
import os import json import schema_salad.ref_resolver from subprocess32 import check_call, DEVNULL, CalledProcessError import yaml import glob import requests import logging from wes_service.util import visit from future.standard_library import hooks with hooks(): from urllib.request import urlopen, pathname2ur...
common-workflow-language/workflow-service
wes_client/util.py
WESClient.get_service_info
python
def get_service_info(self): postresult = requests.get("%s://%s/ga4gh/wes/v1/service-info" % (self.proto, self.host), headers=self.auth) return wes_reponse(postresult)
Get information about Workflow Execution Service. May include information related (but not limited to) the workflow descriptor formats, versions supported, the WES API versions supported, and information about general the service availability. :param str auth: String to send in ...
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_client/util.py#L180-L195
[ "def wes_reponse(postresult):\n if postresult.status_code != 200:\n error = str(json.loads(postresult.text))\n logging.error(error)\n raise Exception(error)\n\n return json.loads(postresult.text)\n" ]
class WESClient(object): def __init__(self, service): self.auth = service['auth'] self.proto = service['proto'] self.host = service['host'] def list_runs(self): """ List the workflows, this endpoint will list the workflows in order of oldest to newest. There is ...
common-workflow-language/workflow-service
wes_client/util.py
WESClient.run
python
def run(self, wf, jsonyaml, attachments): attachments = list(expand_globs(attachments)) parts = build_wes_request(wf, jsonyaml, attachments) postresult = requests.post("%s://%s/ga4gh/wes/v1/runs" % (self.proto, self.host), files=parts, ...
Composes and sends a post request that signals the wes server to run a workflow. :param str workflow_file: A local/http/https path to a cwl/wdl/python workflow file. :param str jsonyaml: A local path to a json or yaml file. :param list attachments: A list of local paths to files that will be up...
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_client/util.py#L213-L231
[ "def expand_globs(attachments):\n expanded_list = []\n for filepath in attachments:\n if 'file://' in filepath:\n for f in glob.glob(filepath[7:]):\n expanded_list += ['file://' + os.path.abspath(f)]\n elif ':' not in filepath:\n for f in glob.glob(filepath):...
class WESClient(object): def __init__(self, service): self.auth = service['auth'] self.proto = service['proto'] self.host = service['host'] def get_service_info(self): """ Get information about Workflow Execution Service. May include information related (but not ...
common-workflow-language/workflow-service
wes_client/util.py
WESClient.cancel
python
def cancel(self, run_id): postresult = requests.post("%s://%s/ga4gh/wes/v1/runs/%s/cancel" % (self.proto, self.host, run_id), headers=self.auth) return wes_reponse(postresult)
Cancel a running workflow. :param run_id: String (typically a uuid) identifying the run. :param str auth: String to send in the auth header. :param proto: Schema where the server resides (http, https) :param host: Port where the post request will be sent and the wes server listens at (d...
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_client/util.py#L233-L245
[ "def wes_reponse(postresult):\n if postresult.status_code != 200:\n error = str(json.loads(postresult.text))\n logging.error(error)\n raise Exception(error)\n\n return json.loads(postresult.text)\n" ]
class WESClient(object): def __init__(self, service): self.auth = service['auth'] self.proto = service['proto'] self.host = service['host'] def get_service_info(self): """ Get information about Workflow Execution Service. May include information related (but not ...
common-workflow-language/workflow-service
wes_client/util.py
WESClient.get_run_log
python
def get_run_log(self, run_id): postresult = requests.get("%s://%s/ga4gh/wes/v1/runs/%s" % (self.proto, self.host, run_id), headers=self.auth) return wes_reponse(postresult)
Get detailed info about a running workflow. :param run_id: String (typically a uuid) identifying the run. :param str auth: String to send in the auth header. :param proto: Schema where the server resides (http, https) :param host: Port where the post request will be sent and the wes ser...
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_client/util.py#L247-L259
[ "def wes_reponse(postresult):\n if postresult.status_code != 200:\n error = str(json.loads(postresult.text))\n logging.error(error)\n raise Exception(error)\n\n return json.loads(postresult.text)\n" ]
class WESClient(object): def __init__(self, service): self.auth = service['auth'] self.proto = service['proto'] self.host = service['host'] def get_service_info(self): """ Get information about Workflow Execution Service. May include information related (but not ...
common-workflow-language/workflow-service
wes_service/cwl_runner.py
Workflow.run
python
def run(self, request, tempdir, opts): with open(os.path.join(self.workdir, "request.json"), "w") as f: json.dump(request, f) with open(os.path.join(self.workdir, "cwl.input.json"), "w") as inputtemp: json.dump(request["workflow_params"], inputtemp) workflow_url = reque...
Constructs a command to run a cwl/json from requests and opts, runs it, and deposits the outputs in outdir. Runner: opts.getopt("runner", default="cwl-runner") CWL (url): request["workflow_url"] == a url to a cwl file or request["workflow_attachment"] == input c...
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/cwl_runner.py#L19-L79
[ "def getstatus(self):\n state, exit_code = self.getstate()\n\n return {\n \"run_id\": self.run_id,\n \"state\": state\n }\n", "def getopt(self, p, default=None):\n \"\"\"Returns the first option value stored that matches p or default.\"\"\"\n for k, v in self.pairs:\n if k == p...
class Workflow(object): def __init__(self, run_id): super(Workflow, self).__init__() self.run_id = run_id self.workdir = os.path.join(os.getcwd(), "workflows", self.run_id) self.outdir = os.path.join(self.workdir, 'outdir') if not os.path.exists(self.outdir): os.m...
common-workflow-language/workflow-service
wes_service/cwl_runner.py
Workflow.getstate
python
def getstate(self): state = "RUNNING" exit_code = -1 exitcode_file = os.path.join(self.workdir, "exit_code") pid_file = os.path.join(self.workdir, "pid") if os.path.exists(exitcode_file): with open(exitcode_file) as f: exit_code = int(f.read()) ...
Returns RUNNING, -1 COMPLETE, 0 or EXECUTOR_ERROR, 255
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/cwl_runner.py#L81-L116
null
class Workflow(object): def __init__(self, run_id): super(Workflow, self).__init__() self.run_id = run_id self.workdir = os.path.join(os.getcwd(), "workflows", self.run_id) self.outdir = os.path.join(self.workdir, 'outdir') if not os.path.exists(self.outdir): os.m...
common-workflow-language/workflow-service
wes_service/toil_wes.py
ToilWorkflow.write_workflow
python
def write_workflow(self, request, opts, cwd, wftype='cwl'): workflow_url = request.get("workflow_url") # link the cwl and json into the cwd if workflow_url.startswith('file://'): os.link(workflow_url[7:], os.path.join(cwd, "wes_workflow." + wftype)) workflow_url = os.pa...
Writes a cwl, wdl, or python file as appropriate from the request dictionary.
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/toil_wes.py#L68-L90
[ "def sort_toil_options(self, extra):\n # determine jobstore and set a new default if the user did not set one\n cloud = False\n for e in extra:\n if e.startswith('--jobStore='):\n self.jobstore = e[11:]\n if self.jobstore.startswith(('aws', 'google', 'azure')):\n ...
class ToilWorkflow(object): def __init__(self, run_id): """ Represents a toil workflow. :param str run_id: A uuid string. Used to name the folder that contains all of the files containing this particular workflow instance's information. """ super(ToilWorkflow, s...
common-workflow-language/workflow-service
wes_service/toil_wes.py
ToilWorkflow.call_cmd
python
def call_cmd(self, cmd, cwd): with open(self.cmdfile, 'w') as f: f.write(str(cmd)) stdout = open(self.outfile, 'w') stderr = open(self.errfile, 'w') logging.info('Calling: ' + ' '.join(cmd)) process = subprocess.Popen(cmd, stdout=std...
Calls a command with Popen. Writes stdout, stderr, and the command to separate files. :param cmd: A string or array of strings. :param tempdir: :return: The pid of the command.
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/toil_wes.py#L98-L120
null
class ToilWorkflow(object): def __init__(self, run_id): """ Represents a toil workflow. :param str run_id: A uuid string. Used to name the folder that contains all of the files containing this particular workflow instance's information. """ super(ToilWorkflow, s...
common-workflow-language/workflow-service
wes_service/toil_wes.py
ToilWorkflow.run
python
def run(self, request, tempdir, opts): wftype = request['workflow_type'].lower().strip() version = request['workflow_type_version'] if version != 'v1.0' and wftype == 'cwl': raise RuntimeError('workflow_type "cwl" requires ' '"workflow_type_version" to...
Constructs a command to run a cwl/json from requests and opts, runs it, and deposits the outputs in outdir. Runner: opts.getopt("runner", default="cwl-runner") CWL (url): request["workflow_url"] == a url to a cwl file or request["workflow_attachment"] == input c...
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/toil_wes.py#L173-L222
[ "def write_workflow(self, request, opts, cwd, wftype='cwl'):\n \"\"\"Writes a cwl, wdl, or python file as appropriate from the request dictionary.\"\"\"\n\n workflow_url = request.get(\"workflow_url\")\n\n # link the cwl and json into the cwd\n if workflow_url.startswith('file://'):\n os.link(wor...
class ToilWorkflow(object): def __init__(self, run_id): """ Represents a toil workflow. :param str run_id: A uuid string. Used to name the folder that contains all of the files containing this particular workflow instance's information. """ super(ToilWorkflow, s...
common-workflow-language/workflow-service
wes_service/toil_wes.py
ToilWorkflow.getstate
python
def getstate(self): # the jobstore never existed if not os.path.exists(self.jobstorefile): logging.info('Workflow ' + self.run_id + ': QUEUED') return "QUEUED", -1 # completed earlier if os.path.exists(self.statcompletefile): logging.info('Workflow ' ...
Returns QUEUED, -1 INITIALIZING, -1 RUNNING, -1 COMPLETE, 0 or EXECUTOR_ERROR, 255
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/toil_wes.py#L224-L271
null
class ToilWorkflow(object): def __init__(self, run_id): """ Represents a toil workflow. :param str run_id: A uuid string. Used to name the folder that contains all of the files containing this particular workflow instance's information. """ super(ToilWorkflow, s...
common-workflow-language/workflow-service
wes_service/util.py
visit
python
def visit(d, op): op(d) if isinstance(d, list): for i in d: visit(i, op) elif isinstance(d, dict): for i in itervalues(d): visit(i, op)
Recursively call op(d) for all list subelements and dictionary 'values' that d may have.
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/util.py#L11-L19
[ "def visit(d, op):\n \"\"\"Recursively call op(d) for all list subelements and dictionary 'values' that d may have.\"\"\"\n op(d)\n if isinstance(d, list):\n for i in d:\n visit(i, op)\n elif isinstance(d, dict):\n for i in itervalues(d):\n visit(i, op)\n", "def fix...
import tempfile import json import os import logging from six import itervalues, iterlists import connexion from werkzeug.utils import secure_filename class WESBackend(object): """Stores and retrieves options. Intended to be inherited.""" def __init__(self, opts): """Parse and store options as a li...
common-workflow-language/workflow-service
wes_service/util.py
WESBackend.getopt
python
def getopt(self, p, default=None): for k, v in self.pairs: if k == p: return v return default
Returns the first option value stored that matches p or default.
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/util.py#L31-L36
null
class WESBackend(object): """Stores and retrieves options. Intended to be inherited.""" def __init__(self, opts): """Parse and store options as a list of tuples.""" self.pairs = [] for o in opts if opts else []: k, v = o.split("=", 1) self.pairs.append((k, v)) ...
common-workflow-language/workflow-service
wes_service/util.py
WESBackend.getoptlist
python
def getoptlist(self, p): optlist = [] for k, v in self.pairs: if k == p: optlist.append(v) return optlist
Returns all option values stored that match p as a list.
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/util.py#L38-L44
null
class WESBackend(object): """Stores and retrieves options. Intended to be inherited.""" def __init__(self, opts): """Parse and store options as a list of tuples.""" self.pairs = [] for o in opts if opts else []: k, v = o.split("=", 1) self.pairs.append((k, v)) ...
common-workflow-language/workflow-service
wes_service/arvados_wes.py
catch_exceptions
python
def catch_exceptions(orig_func): @functools.wraps(orig_func) def catch_exceptions_wrapper(self, *args, **kwargs): try: return orig_func(self, *args, **kwargs) except arvados.errors.ApiError as e: logging.exception("Failure") return {"msg": e._get_reason(), "s...
Catch uncaught exceptions and turn them into http errors
train
https://github.com/common-workflow-language/workflow-service/blob/e879604b65c55546e4f87be1c9df9903a3e0b896/wes_service/arvados_wes.py#L46-L65
null
import arvados import arvados.util import arvados.collection import arvados.errors import os import connexion import json import subprocess import tempfile import functools import threading import logging import shutil from wes_service.util import visit, WESBackend class MissingAuthorization(Exception): pass d...
box/genty
genty/genty_repeat.py
genty_repeat
python
def genty_repeat(count): if count < 0: raise ValueError( "Really? Can't have {0} iterations. Please pick a value >= 0." .format(count) ) def wrap(test_method): test_method.genty_repeat_count = count return test_method return wrap
To use in conjunction with a TestClass wrapped with @genty. Runs the wrapped test 'count' times: @genty_repeat(count) def test_some_function(self) ... Can also wrap a test already decorated with @genty_dataset @genty_repeat(3) @genty_dataset(True, False) def...
train
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty_repeat.py#L6-L36
null
# coding: utf-8 from __future__ import unicode_literals
box/genty
genty/genty.py
genty
python
def genty(target_cls): tests = _expand_tests(target_cls) tests_with_datasets = _expand_datasets(tests) tests_with_datasets_and_repeats = _expand_repeats(tests_with_datasets) _add_new_test_methods(target_cls, tests_with_datasets_and_repeats) return target_cls
This decorator takes the information provided by @genty_dataset, @genty_dataprovider, and @genty_repeat and generates the corresponding test methods. :param target_cls: Test class whose test methods have been decorated. :type target_cls: `class`
train
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L21-L38
[ "def _expand_tests(target_cls):\n \"\"\"\n Generator of all the test unbound functions in the given class.\n\n :param target_cls:\n Target test class.\n :type target_cls:\n `class`\n :return:\n Generator of all the test_methods in the given class yielding\n tuples of metho...
# coding: utf-8 from __future__ import absolute_import, unicode_literals import functools from itertools import chain import math import re import sys import types import six from .genty_args import GentyArgs from .private import encode_non_ascii_string REPLACE_FOR_PERIOD_CHAR = '\xb7' def _expand_tests(target...
box/genty
genty/genty.py
_expand_datasets
python
def _expand_datasets(test_functions): for name, func in test_functions: dataset_tuples = chain( [(None, getattr(func, 'genty_datasets', {}))], getattr(func, 'genty_dataproviders', []), ) no_datasets = True for dataprovider, datasets in dataset_tuples: ...
Generator producing test_methods, with an optional dataset. :param test_functions: Iterator over tuples of test name and test unbound function. :type test_functions: `iterator` of `tuple` of (`unicode`, `function`) :return: Generator yielding a tuple of - method_name : ...
train
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L62-L101
null
# coding: utf-8 from __future__ import absolute_import, unicode_literals import functools from itertools import chain import math import re import sys import types import six from .genty_args import GentyArgs from .private import encode_non_ascii_string REPLACE_FOR_PERIOD_CHAR = '\xb7' def genty(target_cls): ...
box/genty
genty/genty.py
_expand_repeats
python
def _expand_repeats(test_functions): for name, func, dataset_name, dataset, dataprovider in test_functions: repeat_count = getattr(func, 'genty_repeat_count', 0) if repeat_count: for i in range(1, repeat_count + 1): repeat_suffix = _build_repeat_suffix(i, repeat_count) ...
Generator producing test_methods, with any repeat count unrolled. :param test_functions: Sequence of tuples of - method_name : Name of the test method - unbound function : Unbound function that will be the test method. - dataset name : String representation of the given dat...
train
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L104-L139
[ "def _build_repeat_suffix(iteration, count):\n \"\"\"\n Return the suffix string to identify iteration X out of Y.\n\n For example, with a count of 100, this will build strings like\n \"iteration_053\" or \"iteration_008\".\n\n :param iteration:\n Current iteration.\n :type iteration:\n ...
# coding: utf-8 from __future__ import absolute_import, unicode_literals import functools from itertools import chain import math import re import sys import types import six from .genty_args import GentyArgs from .private import encode_non_ascii_string REPLACE_FOR_PERIOD_CHAR = '\xb7' def genty(target_cls): ...
box/genty
genty/genty.py
_is_referenced_in_argv
python
def _is_referenced_in_argv(method_name): expr = '.*[:.]{0}$'.format(method_name) regex = re.compile(expr) return any(regex.match(arg) for arg in sys.argv)
Various test runners allow one to run a specific test like so: python -m unittest -v <test_module>.<test_name> Return True is the given method name is so referenced. :param method_name: Base name of the method to add. :type method_name: `unicode` :return: Is the given m...
train
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L193-L211
null
# coding: utf-8 from __future__ import absolute_import, unicode_literals import functools from itertools import chain import math import re import sys import types import six from .genty_args import GentyArgs from .private import encode_non_ascii_string REPLACE_FOR_PERIOD_CHAR = '\xb7' def genty(target_cls): ...
box/genty
genty/genty.py
_build_repeat_suffix
python
def _build_repeat_suffix(iteration, count): format_width = int(math.ceil(math.log(count + 1, 10))) new_suffix = 'iteration_{0:0{width}d}'.format( iteration, width=format_width ) return new_suffix
Return the suffix string to identify iteration X out of Y. For example, with a count of 100, this will build strings like "iteration_053" or "iteration_008". :param iteration: Current iteration. :type iteration: `int` :param count: Total number of iterations. :type coun...
train
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/genty.py#L214-L239
null
# coding: utf-8 from __future__ import absolute_import, unicode_literals import functools from itertools import chain import math import re import sys import types import six from .genty_args import GentyArgs from .private import encode_non_ascii_string REPLACE_FOR_PERIOD_CHAR = '\xb7' def genty(target_cls): ...