repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
donovan-duplessis/pwnurl
pwnurl/models/base.py
BaseModel.delete
def delete(self, commit=True): """ Delete model from database """ db.session.delete(self) return commit and db.session.commit()
python
def delete(self, commit=True): """ Delete model from database """ db.session.delete(self) return commit and db.session.commit()
[ "def", "delete", "(", "self", ",", "commit", "=", "True", ")", ":", "db", ".", "session", ".", "delete", "(", "self", ")", "return", "commit", "and", "db", ".", "session", ".", "commit", "(", ")" ]
Delete model from database
[ "Delete", "model", "from", "database" ]
train
https://github.com/donovan-duplessis/pwnurl/blob/a13e27694f738228d186ea437b4d15ef5a925a87/pwnurl/models/base.py#L68-L72
jpablo128/simplystatic
simplystatic/s2site.py
verify_dir_structure
def verify_dir_structure(full_path): '''Check if given directory to see if it is usable by s2. Checks that all required directories exist under the given directory, and also checks that they are writable. ''' if full_path == None: return False r = True for d2c in PREDEFINED_DIR_NA...
python
def verify_dir_structure(full_path): '''Check if given directory to see if it is usable by s2. Checks that all required directories exist under the given directory, and also checks that they are writable. ''' if full_path == None: return False r = True for d2c in PREDEFINED_DIR_NA...
[ "def", "verify_dir_structure", "(", "full_path", ")", ":", "if", "full_path", "==", "None", ":", "return", "False", "r", "=", "True", "for", "d2c", "in", "PREDEFINED_DIR_NAMES", ":", "#if d2c == \"s2\":", "# d2c = \".s2\"", "cp2c", "=", "os", ".", "path", "...
Check if given directory to see if it is usable by s2. Checks that all required directories exist under the given directory, and also checks that they are writable.
[ "Check", "if", "given", "directory", "to", "see", "if", "it", "is", "usable", "by", "s2", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L32-L53
jpablo128/simplystatic
simplystatic/s2site.py
dir_param_valid
def dir_param_valid(d): '''True if d is a string and it's an existing directory.''' r = True if not isinstance(d, str) : r = False raise TypeError if not os.path.isdir(d): r = False raise ValueError return r
python
def dir_param_valid(d): '''True if d is a string and it's an existing directory.''' r = True if not isinstance(d, str) : r = False raise TypeError if not os.path.isdir(d): r = False raise ValueError return r
[ "def", "dir_param_valid", "(", "d", ")", ":", "r", "=", "True", "if", "not", "isinstance", "(", "d", ",", "str", ")", ":", "r", "=", "False", "raise", "TypeError", "if", "not", "os", ".", "path", ".", "isdir", "(", "d", ")", ":", "r", "=", "Fal...
True if d is a string and it's an existing directory.
[ "True", "if", "d", "is", "a", "string", "and", "it", "s", "an", "existing", "directory", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L55-L64
jpablo128/simplystatic
simplystatic/s2site.py
dir_empty
def dir_empty(d): '''Return True if given directory is empty, false otherwise.''' flist = glob.glob(os.path.join(d,'*')) return (len(flist) == 0)
python
def dir_empty(d): '''Return True if given directory is empty, false otherwise.''' flist = glob.glob(os.path.join(d,'*')) return (len(flist) == 0)
[ "def", "dir_empty", "(", "d", ")", ":", "flist", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "d", ",", "'*'", ")", ")", "return", "(", "len", "(", "flist", ")", "==", "0", ")" ]
Return True if given directory is empty, false otherwise.
[ "Return", "True", "if", "given", "directory", "is", "empty", "false", "otherwise", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L66-L69
jpablo128/simplystatic
simplystatic/s2site.py
is_base_dir
def is_base_dir(d): '''True if the dir is valid and it contains a dir called s2''' if not dir_param_valid(d): # pragma: no cover raise else: mfn = os.path.join(d,'s2') #marker name. it must be a directory. return os.path.isdir(mfn)
python
def is_base_dir(d): '''True if the dir is valid and it contains a dir called s2''' if not dir_param_valid(d): # pragma: no cover raise else: mfn = os.path.join(d,'s2') #marker name. it must be a directory. return os.path.isdir(mfn)
[ "def", "is_base_dir", "(", "d", ")", ":", "if", "not", "dir_param_valid", "(", "d", ")", ":", "# pragma: no cover", "raise", "else", ":", "mfn", "=", "os", ".", "path", ".", "join", "(", "d", ",", "'s2'", ")", "#marker name. it must be a directory.", "retu...
True if the dir is valid and it contains a dir called s2
[ "True", "if", "the", "dir", "is", "valid", "and", "it", "contains", "a", "dir", "called", "s2" ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L71-L77
jpablo128/simplystatic
simplystatic/s2site.py
discover_base_dir
def discover_base_dir(start_dir): '''Return start_dir or the parent dir that has the s2 marker. Starting from the specified directory, and going up the parent chain, check each directory to see if it's a base_dir (contains the "marker" directory *s2*) and return it. Otherwise, return the start_dir....
python
def discover_base_dir(start_dir): '''Return start_dir or the parent dir that has the s2 marker. Starting from the specified directory, and going up the parent chain, check each directory to see if it's a base_dir (contains the "marker" directory *s2*) and return it. Otherwise, return the start_dir....
[ "def", "discover_base_dir", "(", "start_dir", ")", ":", "if", "is_base_dir", "(", "start_dir", ")", ":", "return", "start_dir", "pcl", "=", "start_dir", ".", "split", "(", "'/'", ")", "#path component list", "found_base_dir", "=", "None", "for", "i", "in", "...
Return start_dir or the parent dir that has the s2 marker. Starting from the specified directory, and going up the parent chain, check each directory to see if it's a base_dir (contains the "marker" directory *s2*) and return it. Otherwise, return the start_dir.
[ "Return", "start_dir", "or", "the", "parent", "dir", "that", "has", "the", "s2", "marker", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L79-L99
jpablo128/simplystatic
simplystatic/s2site.py
package_data_location
def package_data_location(): '''Get the locations of themes distributed with this package. Just finds if there are templates, and returns a dictionary with the corresponding values. ''' pkg_dir = os.path.split(__file__)[0] pkg_data_dir = os.path.join(pkg_dir,'data') return pkg_data_dir
python
def package_data_location(): '''Get the locations of themes distributed with this package. Just finds if there are templates, and returns a dictionary with the corresponding values. ''' pkg_dir = os.path.split(__file__)[0] pkg_data_dir = os.path.join(pkg_dir,'data') return pkg_data_dir
[ "def", "package_data_location", "(", ")", ":", "pkg_dir", "=", "os", ".", "path", ".", "split", "(", "__file__", ")", "[", "0", "]", "pkg_data_dir", "=", "os", ".", "path", ".", "join", "(", "pkg_dir", ",", "'data'", ")", "return", "pkg_data_dir" ]
Get the locations of themes distributed with this package. Just finds if there are templates, and returns a dictionary with the corresponding values.
[ "Get", "the", "locations", "of", "themes", "distributed", "with", "this", "package", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L107-L116
jpablo128/simplystatic
simplystatic/s2site.py
Site._set_directories
def _set_directories(self): '''Initialize variables based on evidence about the directories.''' if self._dirs['initial'] == None: self._dirs['base'] = discover_base_dir(self._dirs['run']) else: self._dirs['base'] = discover_base_dir(self._dirs['initial']) # no...
python
def _set_directories(self): '''Initialize variables based on evidence about the directories.''' if self._dirs['initial'] == None: self._dirs['base'] = discover_base_dir(self._dirs['run']) else: self._dirs['base'] = discover_base_dir(self._dirs['initial']) # no...
[ "def", "_set_directories", "(", "self", ")", ":", "if", "self", ".", "_dirs", "[", "'initial'", "]", "==", "None", ":", "self", ".", "_dirs", "[", "'base'", "]", "=", "discover_base_dir", "(", "self", ".", "_dirs", "[", "'run'", "]", ")", "else", ":"...
Initialize variables based on evidence about the directories.
[ "Initialize", "variables", "based", "on", "evidence", "about", "the", "directories", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L207-L220
jpablo128/simplystatic
simplystatic/s2site.py
Site._update_dirs_on_base
def _update_dirs_on_base(self): '''Fill up the names of dirs based on the contents of 'base'.''' if self._dirs['base'] != None: for d in self._predefined_dir_names: dstr = d #if d == "s2": # dstr = '.'+d self._dirs[d] = os.pa...
python
def _update_dirs_on_base(self): '''Fill up the names of dirs based on the contents of 'base'.''' if self._dirs['base'] != None: for d in self._predefined_dir_names: dstr = d #if d == "s2": # dstr = '.'+d self._dirs[d] = os.pa...
[ "def", "_update_dirs_on_base", "(", "self", ")", ":", "if", "self", ".", "_dirs", "[", "'base'", "]", "!=", "None", ":", "for", "d", "in", "self", ".", "_predefined_dir_names", ":", "dstr", "=", "d", "#if d == \"s2\":", "# dstr = '.'+d", "self", ".", "_...
Fill up the names of dirs based on the contents of 'base'.
[ "Fill", "up", "the", "names", "of", "dirs", "based", "on", "the", "contents", "of", "base", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L222-L229
jpablo128/simplystatic
simplystatic/s2site.py
Site.init_structure
def init_structure(self): '''Initialize a directory to serve as a Simply Static site. Initialization is done on the base_dir (base_dir is set upon __init__, so it has a value when this method is called), and it is only performed if base_dir is empty and it is writeable. This op...
python
def init_structure(self): '''Initialize a directory to serve as a Simply Static site. Initialization is done on the base_dir (base_dir is set upon __init__, so it has a value when this method is called), and it is only performed if base_dir is empty and it is writeable. This op...
[ "def", "init_structure", "(", "self", ")", ":", "if", "self", ".", "_dirs", "[", "'base'", "]", "!=", "None", ":", "# pragma: no cover ", "#there's a base here or up the chain", "raise", "ValueError", "#cannot initialize", "else", ":", "if", "self", ".", "_dirs", ...
Initialize a directory to serve as a Simply Static site. Initialization is done on the base_dir (base_dir is set upon __init__, so it has a value when this method is called), and it is only performed if base_dir is empty and it is writeable. This operation creates the directories, copi...
[ "Initialize", "a", "directory", "to", "serve", "as", "a", "Simply", "Static", "site", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L236-L275
jpablo128/simplystatic
simplystatic/s2site.py
Site.get_page_names
def get_page_names(self): '''Return a list of page names (directories) under source_dir.''' fis = [p for p in glob.glob(os.path.join(self._dirs['source'], \ "*")) if os.path.isdir(p)] fis = [os.path.split(p)[1] for p in fis ] return fis
python
def get_page_names(self): '''Return a list of page names (directories) under source_dir.''' fis = [p for p in glob.glob(os.path.join(self._dirs['source'], \ "*")) if os.path.isdir(p)] fis = [os.path.split(p)[1] for p in fis ] return fis
[ "def", "get_page_names", "(", "self", ")", ":", "fis", "=", "[", "p", "for", "p", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_dirs", "[", "'source'", "]", ",", "\"*\"", ")", ")", "if", "os", ".", "path", ...
Return a list of page names (directories) under source_dir.
[ "Return", "a", "list", "of", "page", "names", "(", "directories", ")", "under", "source_dir", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L277-L282
jpablo128/simplystatic
simplystatic/s2site.py
Site.generate
def generate(self): '''Generate the whole static site. Iterates through all existing s2 pages, rendering and writing them (and copying all common files along). It also generates the toc, a sitemap, and the atom feed etc. (in the future it should handle tags and categories) ...
python
def generate(self): '''Generate the whole static site. Iterates through all existing s2 pages, rendering and writing them (and copying all common files along). It also generates the toc, a sitemap, and the atom feed etc. (in the future it should handle tags and categories) ...
[ "def", "generate", "(", "self", ")", ":", "if", "self", ".", "_dirs", "[", "'base'", "]", "==", "None", "or", "not", "self", ".", "_tree_ready", ":", "#there's NO base here or up the chain", "raise", "ValueError", "#cannot generate!", "# wipe www dir & recreate", ...
Generate the whole static site. Iterates through all existing s2 pages, rendering and writing them (and copying all common files along). It also generates the toc, a sitemap, and the atom feed etc. (in the future it should handle tags and categories)
[ "Generate", "the", "whole", "static", "site", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L293-L382
jpablo128/simplystatic
simplystatic/s2site.py
Site.random_page
def random_page(self, title=None, content=None, creation_date=None, tags=None): '''Generate random page, write it and return the corresponding \ object.''' if title == None: title = util.random_title() if content == None: content = util.random_md_page...
python
def random_page(self, title=None, content=None, creation_date=None, tags=None): '''Generate random page, write it and return the corresponding \ object.''' if title == None: title = util.random_title() if content == None: content = util.random_md_page...
[ "def", "random_page", "(", "self", ",", "title", "=", "None", ",", "content", "=", "None", ",", "creation_date", "=", "None", ",", "tags", "=", "None", ")", ":", "if", "title", "==", "None", ":", "title", "=", "util", ".", "random_title", "(", ")", ...
Generate random page, write it and return the corresponding \ object.
[ "Generate", "random", "page", "write", "it", "and", "return", "the", "corresponding", "\\", "object", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L474-L495
jpablo128/simplystatic
simplystatic/s2site.py
Site.page_exists_on_disk
def page_exists_on_disk(self, slug): '''Return true if post directory and post file both exist.''' r = False page_dir = os.path.join(self.dirs['source'], slug) page_file_name = os.path.join(page_dir, slug + '.md') if os.path.isdir(page_dir): if os.path.isfile(page_fi...
python
def page_exists_on_disk(self, slug): '''Return true if post directory and post file both exist.''' r = False page_dir = os.path.join(self.dirs['source'], slug) page_file_name = os.path.join(page_dir, slug + '.md') if os.path.isdir(page_dir): if os.path.isfile(page_fi...
[ "def", "page_exists_on_disk", "(", "self", ",", "slug", ")", ":", "r", "=", "False", "page_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "dirs", "[", "'source'", "]", ",", "slug", ")", "page_file_name", "=", "os", ".", "path", ".", "...
Return true if post directory and post file both exist.
[ "Return", "true", "if", "post", "directory", "and", "post", "file", "both", "exist", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L497-L506
jpablo128/simplystatic
simplystatic/s2site.py
Site.rename_page
def rename_page(self, old_slug, new_title): '''Load the page corresponding to the slug, and rename it.''' #load page p = s2page.Page(self, old_slug, isslug=True) p.rename(new_title)
python
def rename_page(self, old_slug, new_title): '''Load the page corresponding to the slug, and rename it.''' #load page p = s2page.Page(self, old_slug, isslug=True) p.rename(new_title)
[ "def", "rename_page", "(", "self", ",", "old_slug", ",", "new_title", ")", ":", "#load page", "p", "=", "s2page", ".", "Page", "(", "self", ",", "old_slug", ",", "isslug", "=", "True", ")", "p", ".", "rename", "(", "new_title", ")" ]
Load the page corresponding to the slug, and rename it.
[ "Load", "the", "page", "corresponding", "to", "the", "slug", "and", "rename", "it", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L508-L512
jpablo128/simplystatic
simplystatic/s2site.py
Site._wipe_www_page
def _wipe_www_page(self, slug): '''Remove all data in www about the page identified by slug.''' wd = os.path.join(self._dirs['www'], slug) if os.path.isdir(wd): # pragma: no cover shutil.rmtree(wd)
python
def _wipe_www_page(self, slug): '''Remove all data in www about the page identified by slug.''' wd = os.path.join(self._dirs['www'], slug) if os.path.isdir(wd): # pragma: no cover shutil.rmtree(wd)
[ "def", "_wipe_www_page", "(", "self", ",", "slug", ")", ":", "wd", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_dirs", "[", "'www'", "]", ",", "slug", ")", "if", "os", ".", "path", ".", "isdir", "(", "wd", ")", ":", "# pragma: no cove...
Remove all data in www about the page identified by slug.
[ "Remove", "all", "data", "in", "www", "about", "the", "page", "identified", "by", "slug", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L524-L528
jpablo128/simplystatic
simplystatic/s2site.py
Site._pages_to_generate
def _pages_to_generate(self): '''Return list of slugs that correspond to pages to generate.''' # right now it gets all the files. In theory, It should only # get what's changed... but the program is not doing that yet. all_pages = self.get_page_names() # keep only those whose st...
python
def _pages_to_generate(self): '''Return list of slugs that correspond to pages to generate.''' # right now it gets all the files. In theory, It should only # get what's changed... but the program is not doing that yet. all_pages = self.get_page_names() # keep only those whose st...
[ "def", "_pages_to_generate", "(", "self", ")", ":", "# right now it gets all the files. In theory, It should only", "# get what's changed... but the program is not doing that yet.", "all_pages", "=", "self", ".", "get_page_names", "(", ")", "# keep only those whose status is published"...
Return list of slugs that correspond to pages to generate.
[ "Return", "list", "of", "slugs", "that", "correspond", "to", "pages", "to", "generate", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L530-L546
jpablo128/simplystatic
simplystatic/s2site.py
Site._create_default_config
def _create_default_config(self): '''Create and write to disk a default site config file.''' # maybe I should read the default config from somewhere in the package? cfg = { 'site_title': '', 'site_subtitle': '', 'default_author': '', 'site_url': ''...
python
def _create_default_config(self): '''Create and write to disk a default site config file.''' # maybe I should read the default config from somewhere in the package? cfg = { 'site_title': '', 'site_subtitle': '', 'default_author': '', 'site_url': ''...
[ "def", "_create_default_config", "(", "self", ")", ":", "# maybe I should read the default config from somewhere in the package?", "cfg", "=", "{", "'site_title'", ":", "''", ",", "'site_subtitle'", ":", "''", ",", "'default_author'", ":", "''", ",", "'site_url'", ":", ...
Create and write to disk a default site config file.
[ "Create", "and", "write", "to", "disk", "a", "default", "site", "config", "file", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L548-L565
jpablo128/simplystatic
simplystatic/s2site.py
Site._read_site_config
def _read_site_config(self): '''Read and return the site config, as a dictionary.''' file_name = os.path.join(self._dirs['s2'],'config.yml') if os.path.isfile(file_name): f = open(file_name,'r') cfg = yaml.load(f.read()) f.close() else: cfg...
python
def _read_site_config(self): '''Read and return the site config, as a dictionary.''' file_name = os.path.join(self._dirs['s2'],'config.yml') if os.path.isfile(file_name): f = open(file_name,'r') cfg = yaml.load(f.read()) f.close() else: cfg...
[ "def", "_read_site_config", "(", "self", ")", ":", "file_name", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_dirs", "[", "'s2'", "]", ",", "'config.yml'", ")", "if", "os", ".", "path", ".", "isfile", "(", "file_name", ")", ":", "f", "="...
Read and return the site config, as a dictionary.
[ "Read", "and", "return", "the", "site", "config", "as", "a", "dictionary", "." ]
train
https://github.com/jpablo128/simplystatic/blob/91ac579c8f34fa240bef9b87adb0116c6b40b24d/simplystatic/s2site.py#L567-L576
salimm/msgpack-pystream
msgpackstream/defs.py
TimestampParser.parse_int
def parse_int(self, buff, start, end): ''' parse an integer from the buffer given the interval of bytes :param buff: :param start: :param end: ''' # num = self.parse_uint(buff, start, end) # l = (end - start) # return self.twos_comp(num, l * 8)...
python
def parse_int(self, buff, start, end): ''' parse an integer from the buffer given the interval of bytes :param buff: :param start: :param end: ''' # num = self.parse_uint(buff, start, end) # l = (end - start) # return self.twos_comp(num, l * 8)...
[ "def", "parse_int", "(", "self", ",", "buff", ",", "start", ",", "end", ")", ":", "# num = self.parse_uint(buff, start, end)", "# l = (end - start)", "# return self.twos_comp(num, l * 8)", "return", "struct", ".", "unpack_from", "(", "self", ".", "...
parse an integer from the buffer given the interval of bytes :param buff: :param start: :param end:
[ "parse", "an", "integer", "from", "the", "buffer", "given", "the", "interval", "of", "bytes", ":", "param", "buff", ":", ":", "param", "start", ":", ":", "param", "end", ":" ]
train
https://github.com/salimm/msgpack-pystream/blob/676158a5a8dd8ff56dca080d597943f67fc4325e/msgpackstream/defs.py#L311-L321
OiNutter/lean
lean/__init__.py
Lean.register
def register(template_class,*extensions): ''' Register a template for a given extension or range of extensions ''' for ext in extensions: ext = normalize(ext) if not Lean.template_mappings.has_key(ext): Lean.template_mappings[ext] = [] Lean.template_mappings[ext].insert(0,template_class) Lean.templ...
python
def register(template_class,*extensions): ''' Register a template for a given extension or range of extensions ''' for ext in extensions: ext = normalize(ext) if not Lean.template_mappings.has_key(ext): Lean.template_mappings[ext] = [] Lean.template_mappings[ext].insert(0,template_class) Lean.templ...
[ "def", "register", "(", "template_class", ",", "*", "extensions", ")", ":", "for", "ext", "in", "extensions", ":", "ext", "=", "normalize", "(", "ext", ")", "if", "not", "Lean", ".", "template_mappings", ".", "has_key", "(", "ext", ")", ":", "Lean", "....
Register a template for a given extension or range of extensions
[ "Register", "a", "template", "for", "a", "given", "extension", "or", "range", "of", "extensions" ]
train
https://github.com/OiNutter/lean/blob/5d251f923acd44265ed401de14a9ead6752c543f/lean/__init__.py#L10-L18
OiNutter/lean
lean/__init__.py
Lean.prefer
def prefer(template_class,*extensions): ''' Makes a template class preferred for the given file extensions. If you don't provide any extensions, it will be preferred for all its already registered extensions: # Prefer Markdown for its registered file extensions: Lean.prefer(Ma...
python
def prefer(template_class,*extensions): ''' Makes a template class preferred for the given file extensions. If you don't provide any extensions, it will be preferred for all its already registered extensions: # Prefer Markdown for its registered file extensions: Lean.prefer(Ma...
[ "def", "prefer", "(", "template_class", ",", "*", "extensions", ")", ":", "if", "len", "(", "extensions", ")", ":", "for", "(", "ext", ",", "klasses", ")", "in", "Lean", ".", "template_mappings", ".", "items", "(", ")", ":", "if", "klasses", ".", "co...
Makes a template class preferred for the given file extensions. If you don't provide any extensions, it will be preferred for all its already registered extensions: # Prefer Markdown for its registered file extensions: Lean.prefer(MarkdownTemplate) # Prefer Markdo...
[ "Makes", "a", "template", "class", "preferred", "for", "the", "given", "file", "extensions", ".", "If", "you", "don", "t", "provide", "any", "extensions", "it", "will", "be", "preferred", "for", "all", "its", "already", "registered", "extensions", ":", "#", ...
train
https://github.com/OiNutter/lean/blob/5d251f923acd44265ed401de14a9ead6752c543f/lean/__init__.py#L21-L41
OiNutter/lean
lean/__init__.py
Lean.is_registered
def is_registered(ext): ''' Returns true when a template exists on an exact match of the provided file extension ''' return Lean.template_mappings.has_key(ext.lower()) and len(Lean.template_mappings[ext])
python
def is_registered(ext): ''' Returns true when a template exists on an exact match of the provided file extension ''' return Lean.template_mappings.has_key(ext.lower()) and len(Lean.template_mappings[ext])
[ "def", "is_registered", "(", "ext", ")", ":", "return", "Lean", ".", "template_mappings", ".", "has_key", "(", "ext", ".", "lower", "(", ")", ")", "and", "len", "(", "Lean", ".", "template_mappings", "[", "ext", "]", ")" ]
Returns true when a template exists on an exact match of the provided file extension
[ "Returns", "true", "when", "a", "template", "exists", "on", "an", "exact", "match", "of", "the", "provided", "file", "extension" ]
train
https://github.com/OiNutter/lean/blob/5d251f923acd44265ed401de14a9ead6752c543f/lean/__init__.py#L44-L46
OiNutter/lean
lean/__init__.py
Lean.load
def load(file,line=None,options={},block=None): ''' Create a new template for the given file using the file's extension to determine the the template mapping. ''' template_class = Lean.get_template(file) if template_class: return template_class(file,line,options,block) else: rai...
python
def load(file,line=None,options={},block=None): ''' Create a new template for the given file using the file's extension to determine the the template mapping. ''' template_class = Lean.get_template(file) if template_class: return template_class(file,line,options,block) else: rai...
[ "def", "load", "(", "file", ",", "line", "=", "None", ",", "options", "=", "{", "}", ",", "block", "=", "None", ")", ":", "template_class", "=", "Lean", ".", "get_template", "(", "file", ")", "if", "template_class", ":", "return", "template_class", "("...
Create a new template for the given file using the file's extension to determine the the template mapping.
[ "Create", "a", "new", "template", "for", "the", "given", "file", "using", "the", "file", "s", "extension", "to", "determine", "the", "the", "template", "mapping", "." ]
train
https://github.com/OiNutter/lean/blob/5d251f923acd44265ed401de14a9ead6752c543f/lean/__init__.py#L49-L58
OiNutter/lean
lean/__init__.py
Lean.get_template
def get_template(file): ''' Lookup a template class for the given filename or file extension. Return nil when no implementation is found. ''' pattern = str(file).lower() while len(pattern) and not Lean.is_registered(pattern): pattern = os.path.basename(pattern) pattern = re.sub(r'^[...
python
def get_template(file): ''' Lookup a template class for the given filename or file extension. Return nil when no implementation is found. ''' pattern = str(file).lower() while len(pattern) and not Lean.is_registered(pattern): pattern = os.path.basename(pattern) pattern = re.sub(r'^[...
[ "def", "get_template", "(", "file", ")", ":", "pattern", "=", "str", "(", "file", ")", ".", "lower", "(", ")", "while", "len", "(", "pattern", ")", "and", "not", "Lean", ".", "is_registered", "(", "pattern", ")", ":", "pattern", "=", "os", ".", "pa...
Lookup a template class for the given filename or file extension. Return nil when no implementation is found.
[ "Lookup", "a", "template", "class", "for", "the", "given", "filename", "or", "file", "extension", ".", "Return", "nil", "when", "no", "implementation", "is", "found", "." ]
train
https://github.com/OiNutter/lean/blob/5d251f923acd44265ed401de14a9ead6752c543f/lean/__init__.py#L61-L103
steenzout/python-sphinx
steenzout/sphinx/cli.py
generate
def generate(organization, package, destination): """Generates the Sphinx configuration and Makefile. Args: organization (str): the organization name. package (str): the package to be documented. destination (str): the destination directory. """ gen = ResourceGenerator(organizat...
python
def generate(organization, package, destination): """Generates the Sphinx configuration and Makefile. Args: organization (str): the organization name. package (str): the package to be documented. destination (str): the destination directory. """ gen = ResourceGenerator(organizat...
[ "def", "generate", "(", "organization", ",", "package", ",", "destination", ")", ":", "gen", "=", "ResourceGenerator", "(", "organization", ",", "package", ")", "tmp", "=", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "'w+t'", ",", "delete", "=",...
Generates the Sphinx configuration and Makefile. Args: organization (str): the organization name. package (str): the package to be documented. destination (str): the destination directory.
[ "Generates", "the", "Sphinx", "configuration", "and", "Makefile", "." ]
train
https://github.com/steenzout/python-sphinx/blob/b9767195fba74540c385fdf5f94cc4a24bc5e46d/steenzout/sphinx/cli.py#L33-L57
elifesciences/elife-article
elifearticle/article.py
Article.get_self_uri
def get_self_uri(self, content_type): "return the first self uri with the content_type" try: return [self_uri for self_uri in self.self_uri_list if self_uri.content_type == content_type][0] except IndexError: return None
python
def get_self_uri(self, content_type): "return the first self uri with the content_type" try: return [self_uri for self_uri in self.self_uri_list if self_uri.content_type == content_type][0] except IndexError: return None
[ "def", "get_self_uri", "(", "self", ",", "content_type", ")", ":", "try", ":", "return", "[", "self_uri", "for", "self_uri", "in", "self", ".", "self_uri_list", "if", "self_uri", ".", "content_type", "==", "content_type", "]", "[", "0", "]", "except", "Ind...
return the first self uri with the content_type
[ "return", "the", "first", "self", "uri", "with", "the", "content_type" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/article.py#L145-L151
elifesciences/elife-article
elifearticle/article.py
Article.pretty
def pretty(self): "sort values and format output for viewing and comparing in test scenarios" pretty_obj = OrderedDict() for key, value in sorted(iteritems(self.__dict__)): if value is None: pretty_obj[key] = None elif is_str_or_unicode(value): ...
python
def pretty(self): "sort values and format output for viewing and comparing in test scenarios" pretty_obj = OrderedDict() for key, value in sorted(iteritems(self.__dict__)): if value is None: pretty_obj[key] = None elif is_str_or_unicode(value): ...
[ "def", "pretty", "(", "self", ")", ":", "pretty_obj", "=", "OrderedDict", "(", ")", "for", "key", ",", "value", "in", "sorted", "(", "iteritems", "(", "self", ".", "__dict__", ")", ")", ":", "if", "value", "is", "None", ":", "pretty_obj", "[", "key",...
sort values and format output for viewing and comparing in test scenarios
[ "sort", "values", "and", "format", "output", "for", "viewing", "and", "comparing", "in", "test", "scenarios" ]
train
https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/article.py#L153-L167
biocore/mustached-octo-ironman
moi/__init__.py
_support_directory
def _support_directory(): """Get the path of the support_files directory""" from os.path import join, dirname, abspath return join(dirname(abspath(__file__)), 'support_files')
python
def _support_directory(): """Get the path of the support_files directory""" from os.path import join, dirname, abspath return join(dirname(abspath(__file__)), 'support_files')
[ "def", "_support_directory", "(", ")", ":", "from", "os", ".", "path", "import", "join", ",", "dirname", ",", "abspath", "return", "join", "(", "dirname", "(", "abspath", "(", "__file__", ")", ")", ",", "'support_files'", ")" ]
Get the path of the support_files directory
[ "Get", "the", "path", "of", "the", "support_files", "directory" ]
train
https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/__init__.py#L21-L24
EnigmaBridge/client.py
ebclient/eb_create_uo.py
CreateUO.create_uo
def create_uo(self, configuration=None, tpl=None, keys=None, obj_type=None): """ Create a new UserObject from the given template. :param configuration: EB configuration to use :param tpl: CreateUserObject template, contain misc settings :param keys: dictionary of keys, create_u...
python
def create_uo(self, configuration=None, tpl=None, keys=None, obj_type=None): """ Create a new UserObject from the given template. :param configuration: EB configuration to use :param tpl: CreateUserObject template, contain misc settings :param keys: dictionary of keys, create_u...
[ "def", "create_uo", "(", "self", ",", "configuration", "=", "None", ",", "tpl", "=", "None", ",", "keys", "=", "None", ",", "obj_type", "=", "None", ")", ":", "if", "configuration", "is", "not", "None", ":", "self", ".", "configuration", "=", "configur...
Create a new UserObject from the given template. :param configuration: EB configuration to use :param tpl: CreateUserObject template, contain misc settings :param keys: dictionary of keys, create_uo.KeyTypes. Communication keys, application key (if applicable). :param obj_type: optiona...
[ "Create", "a", "new", "UserObject", "from", "the", "given", "template", "." ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L36-L84
EnigmaBridge/client.py
ebclient/eb_create_uo.py
CreateUO.get_default_template
def get_default_template(): """ Returns default getTemplate request specification. :return: """ return { "format": 1, "protocol": 1, "environment": Environment.DEV, # shows whether the UO should be for production (live), ...
python
def get_default_template(): """ Returns default getTemplate request specification. :return: """ return { "format": 1, "protocol": 1, "environment": Environment.DEV, # shows whether the UO should be for production (live), ...
[ "def", "get_default_template", "(", ")", ":", "return", "{", "\"format\"", ":", "1", ",", "\"protocol\"", ":", "1", ",", "\"environment\"", ":", "Environment", ".", "DEV", ",", "# shows whether the UO should be for production (live),", "# test (pre-production testing), or...
Returns default getTemplate request specification. :return:
[ "Returns", "default", "getTemplate", "request", "specification", ".", ":", "return", ":" ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L107-L139
EnigmaBridge/client.py
ebclient/eb_create_uo.py
CreateUO.get_template_request_spec
def get_template_request_spec(spec): """ Returns get template request specification, using default values if not present in spec. If dictionary is provided, it is considered as JSON. If Configuration is provided, we look at createTpl object :param spec: :return: "...
python
def get_template_request_spec(spec): """ Returns get template request specification, using default values if not present in spec. If dictionary is provided, it is considered as JSON. If Configuration is provided, we look at createTpl object :param spec: :return: "...
[ "def", "get_template_request_spec", "(", "spec", ")", ":", "dst", "=", "CreateUO", ".", "get_default_template", "(", ")", "src", "=", "None", "if", "isinstance", "(", "spec", ",", "Configuration", ")", ":", "src", "=", "spec", ".", "create_tpl", "elif", "i...
Returns get template request specification, using default values if not present in spec. If dictionary is provided, it is considered as JSON. If Configuration is provided, we look at createTpl object :param spec: :return:
[ "Returns", "get", "template", "request", "specification", "using", "default", "values", "if", "not", "present", "in", "spec", ".", "If", "dictionary", "is", "provided", "it", "is", "considered", "as", "JSON", ".", "If", "Configuration", "is", "provided", "we",...
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L142-L162
EnigmaBridge/client.py
ebclient/eb_create_uo.py
CreateUO.set_type
def set_type(spec, obj_type): """ Updates type integer in the cerate UO specification. Type has to already have generations flags set correctly. Generation field is set accordingly. :param spec: :param obj_type: :return: """ if spec is None: ...
python
def set_type(spec, obj_type): """ Updates type integer in the cerate UO specification. Type has to already have generations flags set correctly. Generation field is set accordingly. :param spec: :param obj_type: :return: """ if spec is None: ...
[ "def", "set_type", "(", "spec", ",", "obj_type", ")", ":", "if", "spec", "is", "None", ":", "raise", "ValueError", "(", "'Spec cannot be None'", ")", "if", "TemplateFields", ".", "generation", "not", "in", "spec", ":", "spec", "[", "TemplateFields", ".", "...
Updates type integer in the cerate UO specification. Type has to already have generations flags set correctly. Generation field is set accordingly. :param spec: :param obj_type: :return:
[ "Updates", "type", "integer", "in", "the", "cerate", "UO", "specification", ".", "Type", "has", "to", "already", "have", "generations", "flags", "set", "correctly", ".", "Generation", "field", "is", "set", "accordingly", "." ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L165-L185
EnigmaBridge/client.py
ebclient/eb_create_uo.py
CreateUO.get_uo_type
def get_uo_type(obj_type, comm_keys_provided=True, app_keys_provided=True): """ Constructs UO type from the operation and keys provided, clears bits set ib obj_type before unless None is specified to the given parameters. :param obj_type: :param comm_keys_provided: :para...
python
def get_uo_type(obj_type, comm_keys_provided=True, app_keys_provided=True): """ Constructs UO type from the operation and keys provided, clears bits set ib obj_type before unless None is specified to the given parameters. :param obj_type: :param comm_keys_provided: :para...
[ "def", "get_uo_type", "(", "obj_type", ",", "comm_keys_provided", "=", "True", ",", "app_keys_provided", "=", "True", ")", ":", "if", "comm_keys_provided", "is", "not", "None", "and", "comm_keys_provided", "==", "False", ":", "obj_type", "&=", "~", "(", "int",...
Constructs UO type from the operation and keys provided, clears bits set ib obj_type before unless None is specified to the given parameters. :param obj_type: :param comm_keys_provided: :param app_keys_provided: :return:
[ "Constructs", "UO", "type", "from", "the", "operation", "and", "keys", "provided", "clears", "bits", "set", "ib", "obj_type", "before", "unless", "None", "is", "specified", "to", "the", "given", "parameters", "." ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L188-L208
EnigmaBridge/client.py
ebclient/eb_create_uo.py
CreateUO.get_template_request
def get_template_request(configuration, spec): """ Builds API request block. :param configuration: :param spec: :return: """ req = RequestHolder() req.api_method = 'GetUserObjectTemplate' req.nonce = EBUtils.generate_nonce() req.api_object ...
python
def get_template_request(configuration, spec): """ Builds API request block. :param configuration: :param spec: :return: """ req = RequestHolder() req.api_method = 'GetUserObjectTemplate' req.nonce = EBUtils.generate_nonce() req.api_object ...
[ "def", "get_template_request", "(", "configuration", ",", "spec", ")", ":", "req", "=", "RequestHolder", "(", ")", "req", ".", "api_method", "=", "'GetUserObjectTemplate'", "req", ".", "nonce", "=", "EBUtils", ".", "generate_nonce", "(", ")", "req", ".", "ap...
Builds API request block. :param configuration: :param spec: :return:
[ "Builds", "API", "request", "block", ".", ":", "param", "configuration", ":", ":", "param", "spec", ":", ":", "return", ":" ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L220-L234
EnigmaBridge/client.py
ebclient/eb_create_uo.py
CreateUO.template_request
def template_request(configuration, spec): """ Calls the get template request :param configuration: :param spec: :return: """ # Template request, nonce will be regenerated. req = CreateUO.get_template_request(configuration, spec) # Do the request...
python
def template_request(configuration, spec): """ Calls the get template request :param configuration: :param spec: :return: """ # Template request, nonce will be regenerated. req = CreateUO.get_template_request(configuration, spec) # Do the request...
[ "def", "template_request", "(", "configuration", ",", "spec", ")", ":", "# Template request, nonce will be regenerated.", "req", "=", "CreateUO", ".", "get_template_request", "(", "configuration", ",", "spec", ")", "# Do the request with retry.", "caller", "=", "RequestCa...
Calls the get template request :param configuration: :param spec: :return:
[ "Calls", "the", "get", "template", "request" ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L237-L251
EnigmaBridge/client.py
ebclient/eb_create_uo.py
CreateUO.build_imported_object
def build_imported_object(configuration, tpl_import_req, import_resp): """ Builds uo from the imported object to the EB. Imported object = result of CreateUserObject call in EB. Returns usable uo - you may call ProcessData with it. """ if import_resp is None \ ...
python
def build_imported_object(configuration, tpl_import_req, import_resp): """ Builds uo from the imported object to the EB. Imported object = result of CreateUserObject call in EB. Returns usable uo - you may call ProcessData with it. """ if import_resp is None \ ...
[ "def", "build_imported_object", "(", "configuration", ",", "tpl_import_req", ",", "import_resp", ")", ":", "if", "import_resp", "is", "None", "or", "import_resp", ".", "response", "is", "None", "or", "'result'", "not", "in", "import_resp", ".", "response", "or",...
Builds uo from the imported object to the EB. Imported object = result of CreateUserObject call in EB. Returns usable uo - you may call ProcessData with it.
[ "Builds", "uo", "from", "the", "imported", "object", "to", "the", "EB", ".", "Imported", "object", "=", "result", "of", "CreateUserObject", "call", "in", "EB", ".", "Returns", "usable", "uo", "-", "you", "may", "call", "ProcessData", "with", "it", "." ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L274-L309
EnigmaBridge/client.py
ebclient/eb_create_uo.py
TemplateProcessor.set_flags
def set_flags(self): """ Set flags representing generation way accordingly - commkeys are client generated, app key is server generated. :return: """ offset = self.template['flagoffset']//8 # comm keys provided? self.tpl_buff = bytes_transform(self.tpl_buff, offs...
python
def set_flags(self): """ Set flags representing generation way accordingly - commkeys are client generated, app key is server generated. :return: """ offset = self.template['flagoffset']//8 # comm keys provided? self.tpl_buff = bytes_transform(self.tpl_buff, offs...
[ "def", "set_flags", "(", "self", ")", ":", "offset", "=", "self", ".", "template", "[", "'flagoffset'", "]", "//", "8", "# comm keys provided?", "self", ".", "tpl_buff", "=", "bytes_transform", "(", "self", ".", "tpl_buff", ",", "offset", "+", "1", ",", ...
Set flags representing generation way accordingly - commkeys are client generated, app key is server generated. :return:
[ "Set", "flags", "representing", "generation", "way", "accordingly", "-", "commkeys", "are", "client", "generated", "app", "key", "is", "server", "generated", ".", ":", "return", ":" ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L446-L454
EnigmaBridge/client.py
ebclient/eb_create_uo.py
TemplateProcessor.set_flag_bit
def set_flag_bit(self, x): """ Function internally used in set_flags. No multi-line lambdas in python :/ :param x: :return: """ x = bytes_to_byte(x) if KeyTypes.COMM_ENC in self.keys: x &= ~0x8 if KeyTypes.APP_KEY in self.keys: x &=...
python
def set_flag_bit(self, x): """ Function internally used in set_flags. No multi-line lambdas in python :/ :param x: :return: """ x = bytes_to_byte(x) if KeyTypes.COMM_ENC in self.keys: x &= ~0x8 if KeyTypes.APP_KEY in self.keys: x &=...
[ "def", "set_flag_bit", "(", "self", ",", "x", ")", ":", "x", "=", "bytes_to_byte", "(", "x", ")", "if", "KeyTypes", ".", "COMM_ENC", "in", "self", ".", "keys", ":", "x", "&=", "~", "0x8", "if", "KeyTypes", ".", "APP_KEY", "in", "self", ".", "keys",...
Function internally used in set_flags. No multi-line lambdas in python :/ :param x: :return:
[ "Function", "internally", "used", "in", "set_flags", ".", "No", "multi", "-", "line", "lambdas", "in", "python", ":", "/", ":", "param", "x", ":", ":", "return", ":" ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L456-L467
EnigmaBridge/client.py
ebclient/eb_create_uo.py
TemplateProcessor.encrypt_template
def encrypt_template(self, enc_key, mac_key, enc_offset): """ Encrypts current tpl_buf according to the protocol - symmetric encryption :param enc_key: :param mac_key: :param enc_offset: :return: """ # AES-256-CBC/PKCS7Padding to_encrypt = self.tp...
python
def encrypt_template(self, enc_key, mac_key, enc_offset): """ Encrypts current tpl_buf according to the protocol - symmetric encryption :param enc_key: :param mac_key: :param enc_offset: :return: """ # AES-256-CBC/PKCS7Padding to_encrypt = self.tp...
[ "def", "encrypt_template", "(", "self", ",", "enc_key", ",", "mac_key", ",", "enc_offset", ")", ":", "# AES-256-CBC/PKCS7Padding", "to_encrypt", "=", "self", ".", "tpl_buff", "[", "enc_offset", ":", "]", "encrypted", "=", "aes_enc", "(", "enc_key", ",", "PKCS7...
Encrypts current tpl_buf according to the protocol - symmetric encryption :param enc_key: :param mac_key: :param enc_offset: :return:
[ "Encrypts", "current", "tpl_buf", "according", "to", "the", "protocol", "-", "symmetric", "encryption", ":", "param", "enc_key", ":", ":", "param", "mac_key", ":", ":", "param", "enc_offset", ":", ":", "return", ":" ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L469-L486
EnigmaBridge/client.py
ebclient/eb_create_uo.py
TemplateProcessor.get_best_import_key
def get_best_import_key(self, import_keys): """ Picks best RSA key for import from the import keys arrays. :param import_keys: :return: """ rsa2048 = None rsa1024 = None for c_key in import_keys: if c_key is None \ or 'type...
python
def get_best_import_key(self, import_keys): """ Picks best RSA key for import from the import keys arrays. :param import_keys: :return: """ rsa2048 = None rsa1024 = None for c_key in import_keys: if c_key is None \ or 'type...
[ "def", "get_best_import_key", "(", "self", ",", "import_keys", ")", ":", "rsa2048", "=", "None", "rsa1024", "=", "None", "for", "c_key", "in", "import_keys", ":", "if", "c_key", "is", "None", "or", "'type'", "not", "in", "c_key", "or", "c_key", "[", "'ty...
Picks best RSA key for import from the import keys arrays. :param import_keys: :return:
[ "Picks", "best", "RSA", "key", "for", "import", "from", "the", "import", "keys", "arrays", ".", ":", "param", "import_keys", ":", ":", "return", ":" ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L488-L509
EnigmaBridge/client.py
ebclient/eb_create_uo.py
TemplateProcessor.encrypt_with_import_key
def encrypt_with_import_key(self, plain): """ Encrypts plain buffer with the import key :param plain: :return: """ n, e = TemplateProcessor.read_serialized_rsa_pub_key(self.import_key['key']) n_bit_size = long_bit_size(n) bs = 0 if n_bit_size > 10...
python
def encrypt_with_import_key(self, plain): """ Encrypts plain buffer with the import key :param plain: :return: """ n, e = TemplateProcessor.read_serialized_rsa_pub_key(self.import_key['key']) n_bit_size = long_bit_size(n) bs = 0 if n_bit_size > 10...
[ "def", "encrypt_with_import_key", "(", "self", ",", "plain", ")", ":", "n", ",", "e", "=", "TemplateProcessor", ".", "read_serialized_rsa_pub_key", "(", "self", ".", "import_key", "[", "'key'", "]", ")", "n_bit_size", "=", "long_bit_size", "(", "n", ")", "bs...
Encrypts plain buffer with the import key :param plain: :return:
[ "Encrypts", "plain", "buffer", "with", "the", "import", "key", ":", "param", "plain", ":", ":", "return", ":" ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L511-L529
EnigmaBridge/client.py
ebclient/eb_create_uo.py
TemplateProcessor.read_serialized_rsa_pub_key
def read_serialized_rsa_pub_key(serialized): """ Reads serialized RSA pub key TAG|len-2B|value. 81 = exponent, 82 = modulus :param serialized: :return: n, e """ n = None e = None rsa = from_hex(serialized) pos = 0 ln = len(rsa) ...
python
def read_serialized_rsa_pub_key(serialized): """ Reads serialized RSA pub key TAG|len-2B|value. 81 = exponent, 82 = modulus :param serialized: :return: n, e """ n = None e = None rsa = from_hex(serialized) pos = 0 ln = len(rsa) ...
[ "def", "read_serialized_rsa_pub_key", "(", "serialized", ")", ":", "n", "=", "None", "e", "=", "None", "rsa", "=", "from_hex", "(", "serialized", ")", "pos", "=", "0", "ln", "=", "len", "(", "rsa", ")", "while", "pos", "<", "ln", ":", "tag", "=", "...
Reads serialized RSA pub key TAG|len-2B|value. 81 = exponent, 82 = modulus :param serialized: :return: n, e
[ "Reads", "serialized", "RSA", "pub", "key", "TAG|len", "-", "2B|value", ".", "81", "=", "exponent", "82", "=", "modulus" ]
train
https://github.com/EnigmaBridge/client.py/blob/0fafe3902da394da88e9f960751d695ca65bbabd/ebclient/eb_create_uo.py#L532-L563
hobson/pug-dj
pug/dj/crawlnmine/crawlnmine/settings/common.py
env
def env(var_name, default=False): """ Get the environment variable or assume a default, but let the user know about the error.""" try: value = os.environ[var_name] if str(value).strip().lower() in ['false', 'no', 'off' '0', 'none', 'null']: return None return value except...
python
def env(var_name, default=False): """ Get the environment variable or assume a default, but let the user know about the error.""" try: value = os.environ[var_name] if str(value).strip().lower() in ['false', 'no', 'off' '0', 'none', 'null']: return None return value except...
[ "def", "env", "(", "var_name", ",", "default", "=", "False", ")", ":", "try", ":", "value", "=", "os", ".", "environ", "[", "var_name", "]", "if", "str", "(", "value", ")", ".", "strip", "(", ")", ".", "lower", "(", ")", "in", "[", "'false'", "...
Get the environment variable or assume a default, but let the user know about the error.
[ "Get", "the", "environment", "variable", "or", "assume", "a", "default", "but", "let", "the", "user", "know", "about", "the", "error", "." ]
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/crawlnmine/crawlnmine/settings/common.py#L20-L31
saltzm/yadi
yadi/datalog2sql/ast2sql/safety_checker.py
ConjunctiveQuerySafetyChecker.check_negated_goals
def check_negated_goals(self,safe_variables,query): ''' Create a list of variables which occur in negated goals. ''' variables_in_negated_goals = \ [y for x in query.relations for y in list(x.variables) if x.is_negated()] # And check them: for variable in variables_in_negate...
python
def check_negated_goals(self,safe_variables,query): ''' Create a list of variables which occur in negated goals. ''' variables_in_negated_goals = \ [y for x in query.relations for y in list(x.variables) if x.is_negated()] # And check them: for variable in variables_in_negate...
[ "def", "check_negated_goals", "(", "self", ",", "safe_variables", ",", "query", ")", ":", "variables_in_negated_goals", "=", "[", "y", "for", "x", "in", "query", ".", "relations", "for", "y", "in", "list", "(", "x", ".", "variables", ")", "if", "x", ".",...
Create a list of variables which occur in negated goals.
[ "Create", "a", "list", "of", "variables", "which", "occur", "in", "negated", "goals", "." ]
train
https://github.com/saltzm/yadi/blob/755790167c350e650c1e8b15c6f9209a97be9e42/yadi/datalog2sql/ast2sql/safety_checker.py#L41-L54
saltzm/yadi
yadi/datalog2sql/ast2sql/safety_checker.py
ConjunctiveQuerySafetyChecker.check_non_equality_explicit_constraints
def check_non_equality_explicit_constraints(self,safe_variables,query): ''' Checking variables which occur in explicit constraints with non equality operators ''' # Create a list of variables which occur in explicit constraints with non # equality operators variables_in_constrain...
python
def check_non_equality_explicit_constraints(self,safe_variables,query): ''' Checking variables which occur in explicit constraints with non equality operators ''' # Create a list of variables which occur in explicit constraints with non # equality operators variables_in_constrain...
[ "def", "check_non_equality_explicit_constraints", "(", "self", ",", "safe_variables", ",", "query", ")", ":", "# Create a list of variables which occur in explicit constraints with non", "# equality operators", "variables_in_constraints_with_non_equality_operators", "=", "[", "y", "f...
Checking variables which occur in explicit constraints with non equality operators
[ "Checking", "variables", "which", "occur", "in", "explicit", "constraints", "with", "non", "equality", "operators" ]
train
https://github.com/saltzm/yadi/blob/755790167c350e650c1e8b15c6f9209a97be9e42/yadi/datalog2sql/ast2sql/safety_checker.py#L56-L73
tax/snor
snor/utils.py
create_database
def create_database(destroy_existing=False): """ Create db and tables if it doesn't exist """ if not os.path.exists(DB_NAME): logger.info('Create database: {0}'.format(DB_NAME)) open(DB_NAME, 'a').close() Show.create_table() Episode.create_table() Setting.create_ta...
python
def create_database(destroy_existing=False): """ Create db and tables if it doesn't exist """ if not os.path.exists(DB_NAME): logger.info('Create database: {0}'.format(DB_NAME)) open(DB_NAME, 'a').close() Show.create_table() Episode.create_table() Setting.create_ta...
[ "def", "create_database", "(", "destroy_existing", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "DB_NAME", ")", ":", "logger", ".", "info", "(", "'Create database: {0}'", ".", "format", "(", "DB_NAME", ")", ")", "open", "("...
Create db and tables if it doesn't exist
[ "Create", "db", "and", "tables", "if", "it", "doesn", "t", "exist" ]
train
https://github.com/tax/snor/blob/0d639bd6913066db743a64b4a14a384024e4ab7d/snor/utils.py#L216-L223
kryptn/Pantry
demo.py
magic_api
def magic_api(word): """ This is our magic API that we're simulating. It'll return a random number and a cache timer. """ result = sum(ord(x)-65 + randint(1,50) for x in word) delta = timedelta(seconds=result) cached_until = datetime.now() + delta return result, cached_until
python
def magic_api(word): """ This is our magic API that we're simulating. It'll return a random number and a cache timer. """ result = sum(ord(x)-65 + randint(1,50) for x in word) delta = timedelta(seconds=result) cached_until = datetime.now() + delta return result, cached_until
[ "def", "magic_api", "(", "word", ")", ":", "result", "=", "sum", "(", "ord", "(", "x", ")", "-", "65", "+", "randint", "(", "1", ",", "50", ")", "for", "x", "in", "word", ")", "delta", "=", "timedelta", "(", "seconds", "=", "result", ")", "cach...
This is our magic API that we're simulating. It'll return a random number and a cache timer.
[ "This", "is", "our", "magic", "API", "that", "we", "re", "simulating", ".", "It", "ll", "return", "a", "random", "number", "and", "a", "cache", "timer", "." ]
train
https://github.com/kryptn/Pantry/blob/2e1c30f8b04127c4fd0e42451a3047d1300ac45f/demo.py#L6-L15
hobson/pug-invest
pug/invest/sandbox/sim.py
portfolio_value
def portfolio_value(portfolio, date, price='close'): """Total value of a portfolio (dict mapping symbols to numbers of shares) $CASH used as symbol for USD """ value = 0.0 for (sym, sym_shares) in portfolio.iteritems(): sym_price = None if sym_shares: sym_price = get_pri...
python
def portfolio_value(portfolio, date, price='close'): """Total value of a portfolio (dict mapping symbols to numbers of shares) $CASH used as symbol for USD """ value = 0.0 for (sym, sym_shares) in portfolio.iteritems(): sym_price = None if sym_shares: sym_price = get_pri...
[ "def", "portfolio_value", "(", "portfolio", ",", "date", ",", "price", "=", "'close'", ")", ":", "value", "=", "0.0", "for", "(", "sym", ",", "sym_shares", ")", "in", "portfolio", ".", "iteritems", "(", ")", ":", "sym_price", "=", "None", "if", "sym_sh...
Total value of a portfolio (dict mapping symbols to numbers of shares) $CASH used as symbol for USD
[ "Total", "value", "of", "a", "portfolio", "(", "dict", "mapping", "symbols", "to", "numbers", "of", "shares", ")" ]
train
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L77-L98
hobson/pug-invest
pug/invest/sandbox/sim.py
chart
def chart( symbols=("AAPL", "GLD", "GOOG", "$SPX", "XOM", "msft"), start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), # data stops at 2013/1/1 normalize=True, ): """Display a graph of the price history for the list of ticker symbols provided Arguments: symbols...
python
def chart( symbols=("AAPL", "GLD", "GOOG", "$SPX", "XOM", "msft"), start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), # data stops at 2013/1/1 normalize=True, ): """Display a graph of the price history for the list of ticker symbols provided Arguments: symbols...
[ "def", "chart", "(", "symbols", "=", "(", "\"AAPL\"", ",", "\"GLD\"", ",", "\"GOOG\"", ",", "\"$SPX\"", ",", "\"XOM\"", ",", "\"msft\"", ")", ",", "start", "=", "datetime", ".", "datetime", "(", "2008", ",", "1", ",", "1", ")", ",", "end", "=", "da...
Display a graph of the price history for the list of ticker symbols provided Arguments: symbols (list of str): Ticker symbols like "GOOG", "AAPL", etc start (datetime): The date at the start of the period being analyzed. end (datetime): The date at the end of the period being analyzed. nor...
[ "Display", "a", "graph", "of", "the", "price", "history", "for", "the", "list", "of", "ticker", "symbols", "provided" ]
train
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L103-L140
hobson/pug-invest
pug/invest/sandbox/sim.py
chart_series
def chart_series(series, market_sym='$SPX', price='actual_close', normalize=True): """Display a graph of the price history for the list of ticker symbols provided Arguments: series (dataframe, list of str, or list of tuples): datafram (Timestamp or Datetime for index) other columns ar...
python
def chart_series(series, market_sym='$SPX', price='actual_close', normalize=True): """Display a graph of the price history for the list of ticker symbols provided Arguments: series (dataframe, list of str, or list of tuples): datafram (Timestamp or Datetime for index) other columns ar...
[ "def", "chart_series", "(", "series", ",", "market_sym", "=", "'$SPX'", ",", "price", "=", "'actual_close'", ",", "normalize", "=", "True", ")", ":", "series", "=", "util", ".", "make_dataframe", "(", "series", ")", "start", "=", "util", ".", "normalize_da...
Display a graph of the price history for the list of ticker symbols provided Arguments: series (dataframe, list of str, or list of tuples): datafram (Timestamp or Datetime for index) other columns are float y-axis values to be plotted list of str: 1st 3 comma or slash-separated in...
[ "Display", "a", "graph", "of", "the", "price", "history", "for", "the", "list", "of", "ticker", "symbols", "provided" ]
train
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L143-L184
hobson/pug-invest
pug/invest/sandbox/sim.py
price_dataframe
def price_dataframe(symbols='sp5002012', start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='actual_close', cleaner=clean_dataframe, ): """Retrieve the prices of a list of equities as a DataFrame (columns = symbols) Arguments: symbols (list of str):...
python
def price_dataframe(symbols='sp5002012', start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='actual_close', cleaner=clean_dataframe, ): """Retrieve the prices of a list of equities as a DataFrame (columns = symbols) Arguments: symbols (list of str):...
[ "def", "price_dataframe", "(", "symbols", "=", "'sp5002012'", ",", "start", "=", "datetime", ".", "datetime", "(", "2008", ",", "1", ",", "1", ")", ",", "end", "=", "datetime", ".", "datetime", "(", "2009", ",", "12", ",", "31", ")", ",", "price_type...
Retrieve the prices of a list of equities as a DataFrame (columns = symbols) Arguments: symbols (list of str): Ticker symbols like "GOOG", "AAPL", etc e.g. ["AAPL", " slv ", GLD", "GOOG", "$SPX", "XOM", "msft"] start (datetime): The date at the start of the period being analyzed. end (dat...
[ "Retrieve", "the", "prices", "of", "a", "list", "of", "equities", "as", "a", "DataFrame", "(", "columns", "=", "symbols", ")" ]
train
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L188-L213
hobson/pug-invest
pug/invest/sandbox/sim.py
portfolio_prices
def portfolio_prices( symbols=("AAPL", "GLD", "GOOG", "$SPX", "XOM", "msft"), start=datetime.datetime(2005, 1, 1), end=datetime.datetime(2011, 12, 31), # data stops at 2013/1/1 normalize=True, allocation=None, price_type='actual_close', ): """Calculate the Sharpe Ratio and other perfor...
python
def portfolio_prices( symbols=("AAPL", "GLD", "GOOG", "$SPX", "XOM", "msft"), start=datetime.datetime(2005, 1, 1), end=datetime.datetime(2011, 12, 31), # data stops at 2013/1/1 normalize=True, allocation=None, price_type='actual_close', ): """Calculate the Sharpe Ratio and other perfor...
[ "def", "portfolio_prices", "(", "symbols", "=", "(", "\"AAPL\"", ",", "\"GLD\"", ",", "\"GOOG\"", ",", "\"$SPX\"", ",", "\"XOM\"", ",", "\"msft\"", ")", ",", "start", "=", "datetime", ".", "datetime", "(", "2005", ",", "1", ",", "1", ")", ",", "end", ...
Calculate the Sharpe Ratio and other performance metrics for a portfolio Arguments: symbols (list of str): Ticker symbols like "GOOG", "AAPL", etc start (datetime): The date at the start of the period being analyzed. end (datetime): The date at the end of the period being analyzed. normaliz...
[ "Calculate", "the", "Sharpe", "Ratio", "and", "other", "performance", "metrics", "for", "a", "portfolio" ]
train
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L216-L253
hobson/pug-invest
pug/invest/sandbox/sim.py
symbol_bollinger
def symbol_bollinger(symbol='GOOG', start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='close', cleaner=clean_dataframe, window=20, sigma=1.): """Calculate the Bolinger indicator value >>> symbol_bollinger("goog", '2008-1-1', '2008-2-1')[-1] # doctest: +ELLIPSIS, +NOR...
python
def symbol_bollinger(symbol='GOOG', start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='close', cleaner=clean_dataframe, window=20, sigma=1.): """Calculate the Bolinger indicator value >>> symbol_bollinger("goog", '2008-1-1', '2008-2-1')[-1] # doctest: +ELLIPSIS, +NOR...
[ "def", "symbol_bollinger", "(", "symbol", "=", "'GOOG'", ",", "start", "=", "datetime", ".", "datetime", "(", "2008", ",", "1", ",", "1", ")", ",", "end", "=", "datetime", ".", "datetime", "(", "2009", ",", "12", ",", "31", ")", ",", "price_type", ...
Calculate the Bolinger indicator value >>> symbol_bollinger("goog", '2008-1-1', '2008-2-1')[-1] # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE -1.8782...
[ "Calculate", "the", "Bolinger", "indicator", "value" ]
train
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L263-L273
hobson/pug-invest
pug/invest/sandbox/sim.py
symbols_bollinger
def symbols_bollinger(symbols='sp5002012', start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='adjusted_close', cleaner=clean_dataframe, window=20, sigma=1.): """Calculate the Bolinger for a list or set of symbols Example: >>> symbols_bollinger(["AAPL", "GOOG", "IB...
python
def symbols_bollinger(symbols='sp5002012', start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='adjusted_close', cleaner=clean_dataframe, window=20, sigma=1.): """Calculate the Bolinger for a list or set of symbols Example: >>> symbols_bollinger(["AAPL", "GOOG", "IB...
[ "def", "symbols_bollinger", "(", "symbols", "=", "'sp5002012'", ",", "start", "=", "datetime", ".", "datetime", "(", "2008", ",", "1", ",", "1", ")", ",", "end", "=", "datetime", ".", "datetime", "(", "2009", ",", "12", ",", "31", ")", ",", "price_ty...
Calculate the Bolinger for a list or set of symbols Example: >>> symbols_bollinger(["AAPL", "GOOG", "IBM", "MSFT"], '10-12-01', '10-12-30')[-5:] # doctest: +NORMALIZE_WHITESPACE GOOG AAPL IBM MSFT 2010-12-23 16:00:00 1.298178 1.185009 1.177220 1.237684 ...
[ "Calculate", "the", "Bolinger", "for", "a", "list", "or", "set", "of", "symbols" ]
train
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L276-L292
hobson/pug-invest
pug/invest/sandbox/sim.py
metrics
def metrics(prices, fudge=False, sharpe_days=252., baseline='$SPX'): """Calculate the volatiliy, average daily return, Sharpe ratio, and cumulative return Arguments: prices (file or basestring or iterable): path to file or file pointer or sequence of prices/values of a portfolio or equity fudge (bo...
python
def metrics(prices, fudge=False, sharpe_days=252., baseline='$SPX'): """Calculate the volatiliy, average daily return, Sharpe ratio, and cumulative return Arguments: prices (file or basestring or iterable): path to file or file pointer or sequence of prices/values of a portfolio or equity fudge (bo...
[ "def", "metrics", "(", "prices", ",", "fudge", "=", "False", ",", "sharpe_days", "=", "252.", ",", "baseline", "=", "'$SPX'", ")", ":", "if", "isinstance", "(", "prices", ",", "basestring", ")", "and", "os", ".", "path", ".", "isfile", "(", "prices", ...
Calculate the volatiliy, average daily return, Sharpe ratio, and cumulative return Arguments: prices (file or basestring or iterable): path to file or file pointer or sequence of prices/values of a portfolio or equity fudge (bool): Whether to use Tucker Balche's erroneous division by N or the more accu...
[ "Calculate", "the", "volatiliy", "average", "daily", "return", "Sharpe", "ratio", "and", "cumulative", "return" ]
train
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L319-L372
hobson/pug-invest
pug/invest/sandbox/sim.py
buy_on_drop
def buy_on_drop(symbol_set="sp5002012", dataobj=dataobj, start=datetime.datetime(2008, 1, 3), end=datetime.datetime(2009, 12, 28), market_sym='$SPX', threshold=6, sell_delay=5, ): '''Compute and display an "event profile" for mul...
python
def buy_on_drop(symbol_set="sp5002012", dataobj=dataobj, start=datetime.datetime(2008, 1, 3), end=datetime.datetime(2009, 12, 28), market_sym='$SPX', threshold=6, sell_delay=5, ): '''Compute and display an "event profile" for mul...
[ "def", "buy_on_drop", "(", "symbol_set", "=", "\"sp5002012\"", ",", "dataobj", "=", "dataobj", ",", "start", "=", "datetime", ".", "datetime", "(", "2008", ",", "1", ",", "3", ")", ",", "end", "=", "datetime", ".", "datetime", "(", "2009", ",", "12", ...
Compute and display an "event profile" for multiple sets of symbols
[ "Compute", "and", "display", "an", "event", "profile", "for", "multiple", "sets", "of", "symbols" ]
train
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L437-L475
hobson/pug-invest
pug/invest/sandbox/sim.py
trade
def trade(args): """Simulate a sequence of trades indicated in `infile` and write the portfolio value time series to `outfile`""" print args print vars(args)['funds'] print args.funds portfolio = { '$CASH': args.funds } print portfolio csvreader = csv.reader(args.infile, dialect='excel', quo...
python
def trade(args): """Simulate a sequence of trades indicated in `infile` and write the portfolio value time series to `outfile`""" print args print vars(args)['funds'] print args.funds portfolio = { '$CASH': args.funds } print portfolio csvreader = csv.reader(args.infile, dialect='excel', quo...
[ "def", "trade", "(", "args", ")", ":", "print", "args", "print", "vars", "(", "args", ")", "[", "'funds'", "]", "print", "args", ".", "funds", "portfolio", "=", "{", "'$CASH'", ":", "args", ".", "funds", "}", "print", "portfolio", "csvreader", "=", "...
Simulate a sequence of trades indicated in `infile` and write the portfolio value time series to `outfile`
[ "Simulate", "a", "sequence", "of", "trades", "indicated", "in", "infile", "and", "write", "the", "portfolio", "value", "time", "series", "to", "outfile" ]
train
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L487-L542
hobson/pug-invest
pug/invest/sandbox/sim.py
generate_orders
def generate_orders(events, sell_delay=5, sep=','): """Generate CSV orders based on events indicated in a DataFrame Arguments: events (pandas.DataFrame): Table of NaNs or 1's, one column for each symbol. 1 indicates a BUY event. -1 a SELL event. nan or 0 is a nonevent. sell_delay (float): N...
python
def generate_orders(events, sell_delay=5, sep=','): """Generate CSV orders based on events indicated in a DataFrame Arguments: events (pandas.DataFrame): Table of NaNs or 1's, one column for each symbol. 1 indicates a BUY event. -1 a SELL event. nan or 0 is a nonevent. sell_delay (float): N...
[ "def", "generate_orders", "(", "events", ",", "sell_delay", "=", "5", ",", "sep", "=", "','", ")", ":", "sell_delay", "=", "float", "(", "unicode", "(", "sell_delay", ")", ")", "or", "1", "for", "i", ",", "(", "t", ",", "row", ")", "in", "enumerate...
Generate CSV orders based on events indicated in a DataFrame Arguments: events (pandas.DataFrame): Table of NaNs or 1's, one column for each symbol. 1 indicates a BUY event. -1 a SELL event. nan or 0 is a nonevent. sell_delay (float): Number of days to wait before selling back the shares bought...
[ "Generate", "CSV", "orders", "based", "on", "events", "indicated", "in", "a", "DataFrame" ]
train
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L576-L608
hobson/pug-invest
pug/invest/sandbox/sim.py
orders_from_events
def orders_from_events(events, sell_delay=5, num_shares=100): """Create a DataFrame of orders (signed share quantities) based on event triggers (T/F or 0/1 matrix) Arguments: events (DataFrame): mask table to indicate occurrence of buy event (1 = buy, NaN/0/False = do nothing) sell_delay (int): num...
python
def orders_from_events(events, sell_delay=5, num_shares=100): """Create a DataFrame of orders (signed share quantities) based on event triggers (T/F or 0/1 matrix) Arguments: events (DataFrame): mask table to indicate occurrence of buy event (1 = buy, NaN/0/False = do nothing) sell_delay (int): num...
[ "def", "orders_from_events", "(", "events", ",", "sell_delay", "=", "5", ",", "num_shares", "=", "100", ")", ":", "buy", "=", "events", ".", "copy", "(", ")", "*", "num_shares", "sell", "=", "-", "1", "*", "pd", ".", "DataFrame", "(", "buy", ".", "...
Create a DataFrame of orders (signed share quantities) based on event triggers (T/F or 0/1 matrix) Arguments: events (DataFrame): mask table to indicate occurrence of buy event (1 = buy, NaN/0/False = do nothing) sell_delay (int): number of days after the buy order to initiate a sell order of those sha...
[ "Create", "a", "DataFrame", "of", "orders", "(", "signed", "share", "quantities", ")", "based", "on", "event", "triggers", "(", "T", "/", "F", "or", "0", "/", "1", "matrix", ")" ]
train
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L611-L631
hobson/pug-invest
pug/invest/sandbox/sim.py
portfolio_from_orders
def portfolio_from_orders(orders, funds=1e5, price_type='close'): """Create a DataFrame of portfolio holdings (#'s' of shares for the symbols and dates) Appends the "$CASH" symbol to the porfolio and initializes it to `funds` indicated. Appends the symbol "total_value" to store the total value of cash + st...
python
def portfolio_from_orders(orders, funds=1e5, price_type='close'): """Create a DataFrame of portfolio holdings (#'s' of shares for the symbols and dates) Appends the "$CASH" symbol to the porfolio and initializes it to `funds` indicated. Appends the symbol "total_value" to store the total value of cash + st...
[ "def", "portfolio_from_orders", "(", "orders", ",", "funds", "=", "1e5", ",", "price_type", "=", "'close'", ")", ":", "portfolio", "=", "orders", ".", "copy", "(", ")", "prices", "=", "price_dataframe", "(", "orders", ".", "columns", ",", "start", "=", "...
Create a DataFrame of portfolio holdings (#'s' of shares for the symbols and dates) Appends the "$CASH" symbol to the porfolio and initializes it to `funds` indicated. Appends the symbol "total_value" to store the total value of cash + stocks at each timestamp. The symbol holdings are found by multipling ...
[ "Create", "a", "DataFrame", "of", "portfolio", "holdings", "(", "#", "s", "of", "shares", "for", "the", "symbols", "and", "dates", ")" ]
train
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L634-L652
hobson/pug-invest
pug/invest/sandbox/sim.py
clipping_params
def clipping_params(ts, capacity=100): """Start and end index that clips the price/value of a time series the most Assumes that the integrated maximum includes the peak (instantaneous maximum). Arguments: ts (TimeSeries): Time series to attempt to clip to as low a max value as possible capacit...
python
def clipping_params(ts, capacity=100): """Start and end index that clips the price/value of a time series the most Assumes that the integrated maximum includes the peak (instantaneous maximum). Arguments: ts (TimeSeries): Time series to attempt to clip to as low a max value as possible capacit...
[ "def", "clipping_params", "(", "ts", ",", "capacity", "=", "100", ")", ":", "ts_sorted", "=", "ts", ".", "order", "(", "ascending", "=", "False", ")", "i", ",", "t0", ",", "t1", ",", "integral", "=", "1", ",", "None", ",", "None", ",", "0", "whil...
Start and end index that clips the price/value of a time series the most Assumes that the integrated maximum includes the peak (instantaneous maximum). Arguments: ts (TimeSeries): Time series to attempt to clip to as low a max value as possible capacity (float): Total "funds" or "energy" available...
[ "Start", "and", "end", "index", "that", "clips", "the", "price", "/", "value", "of", "a", "time", "series", "the", "most" ]
train
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L678-L701
hobson/pug-invest
pug/invest/sandbox/sim.py
find_events
def find_events(symbols, d_data, market_sym='$SPX', trigger=drop_below, trigger_kwargs={}): '''Return dataframe of 1's (event happened) and NaNs (no event), 1 column for each symbol''' df_close = d_data['actual_close'] ts_market = df_close[market_sym] print "Finding `{0}` events with kwargs={1} for {2...
python
def find_events(symbols, d_data, market_sym='$SPX', trigger=drop_below, trigger_kwargs={}): '''Return dataframe of 1's (event happened) and NaNs (no event), 1 column for each symbol''' df_close = d_data['actual_close'] ts_market = df_close[market_sym] print "Finding `{0}` events with kwargs={1} for {2...
[ "def", "find_events", "(", "symbols", ",", "d_data", ",", "market_sym", "=", "'$SPX'", ",", "trigger", "=", "drop_below", ",", "trigger_kwargs", "=", "{", "}", ")", ":", "df_close", "=", "d_data", "[", "'actual_close'", "]", "ts_market", "=", "df_close", "...
Return dataframe of 1's (event happened) and NaNs (no event), 1 column for each symbol
[ "Return", "dataframe", "of", "1", "s", "(", "event", "happened", ")", "and", "NaNs", "(", "no", "event", ")", "1", "column", "for", "each", "symbol" ]
train
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L715-L747
BlueHack-Core/blueforge
blueforge/util/trans.py
download_file
def download_file(save_path, file_url): """ Download file from http url link """ r = requests.get(file_url) # create HTTP response object with open(save_path, 'wb') as f: f.write(r.content) return save_path
python
def download_file(save_path, file_url): """ Download file from http url link """ r = requests.get(file_url) # create HTTP response object with open(save_path, 'wb') as f: f.write(r.content) return save_path
[ "def", "download_file", "(", "save_path", ",", "file_url", ")", ":", "r", "=", "requests", ".", "get", "(", "file_url", ")", "# create HTTP response object", "with", "open", "(", "save_path", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "r",...
Download file from http url link
[ "Download", "file", "from", "http", "url", "link" ]
train
https://github.com/BlueHack-Core/blueforge/blob/ac40a888ee9c388638a8f312c51f7500b8891b6c/blueforge/util/trans.py#L6-L14
BlueHack-Core/blueforge
blueforge/util/trans.py
make_url
def make_url(domain, location): """ This function helps to make full url path.""" url = urlparse(location) if url.scheme == '' and url.netloc == '': return domain + url.path elif url.scheme == '': return 'http://' + url.netloc + url.path else: return url.geturl()
python
def make_url(domain, location): """ This function helps to make full url path.""" url = urlparse(location) if url.scheme == '' and url.netloc == '': return domain + url.path elif url.scheme == '': return 'http://' + url.netloc + url.path else: return url.geturl()
[ "def", "make_url", "(", "domain", ",", "location", ")", ":", "url", "=", "urlparse", "(", "location", ")", "if", "url", ".", "scheme", "==", "''", "and", "url", ".", "netloc", "==", "''", ":", "return", "domain", "+", "url", ".", "path", "elif", "u...
This function helps to make full url path.
[ "This", "function", "helps", "to", "make", "full", "url", "path", "." ]
train
https://github.com/BlueHack-Core/blueforge/blob/ac40a888ee9c388638a8f312c51f7500b8891b6c/blueforge/util/trans.py#L17-L27
webadmin87/midnight
midnight_banners/templatetags/midnight_banners.py
one_banner
def one_banner(slug): """ Служит для отображения одного случайного баннера из указанного баннерного места Пример использования:: {% one_banner 'place_slug' %} :param slug: символьный код баннерного места :return: """ place = BannerPlace.objects.published().get(slug=slug) banne...
python
def one_banner(slug): """ Служит для отображения одного случайного баннера из указанного баннерного места Пример использования:: {% one_banner 'place_slug' %} :param slug: символьный код баннерного места :return: """ place = BannerPlace.objects.published().get(slug=slug) banne...
[ "def", "one_banner", "(", "slug", ")", ":", "place", "=", "BannerPlace", ".", "objects", ".", "published", "(", ")", ".", "get", "(", "slug", "=", "slug", ")", "banner", "=", "place", ".", "banner_set", ".", "published", "(", ")", ".", "order_by", "(...
Служит для отображения одного случайного баннера из указанного баннерного места Пример использования:: {% one_banner 'place_slug' %} :param slug: символьный код баннерного места :return:
[ "Служит", "для", "отображения", "одного", "случайного", "баннера", "из", "указанного", "баннерного", "места" ]
train
https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_banners/templatetags/midnight_banners.py#L9-L23
webadmin87/midnight
midnight_banners/templatetags/midnight_banners.py
list_banners
def list_banners(slug, **kwargs): """ Отображает все баннеры из указанного баннерного места Пример использования:: {% list_banners 'place_slug' class='banners-class' %} :param slug: символьный код баннерного места :param kwargs: html атрибуты оборачивающего тега :return: """ p...
python
def list_banners(slug, **kwargs): """ Отображает все баннеры из указанного баннерного места Пример использования:: {% list_banners 'place_slug' class='banners-class' %} :param slug: символьный код баннерного места :param kwargs: html атрибуты оборачивающего тега :return: """ p...
[ "def", "list_banners", "(", "slug", ",", "*", "*", "kwargs", ")", ":", "place", "=", "BannerPlace", ".", "objects", ".", "published", "(", ")", ".", "get", "(", "slug", "=", "slug", ")", "banners", "=", "place", ".", "banner_set", ".", "published", "...
Отображает все баннеры из указанного баннерного места Пример использования:: {% list_banners 'place_slug' class='banners-class' %} :param slug: символьный код баннерного места :param kwargs: html атрибуты оборачивающего тега :return:
[ "Отображает", "все", "баннеры", "из", "указанного", "баннерного", "места" ]
train
https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_banners/templatetags/midnight_banners.py#L26-L44
Kopachris/seshet
seshet/utils.py
Storage.getlist
def getlist(self, key): """Returns a Storage value as a list. If the value is a list it will be returned as-is. If object is None, an empty list will be returned. Otherwise, `[value]` will be returned. Example output for a query string of `?x=abc&y=abc&y=def`:: >>>...
python
def getlist(self, key): """Returns a Storage value as a list. If the value is a list it will be returned as-is. If object is None, an empty list will be returned. Otherwise, `[value]` will be returned. Example output for a query string of `?x=abc&y=abc&y=def`:: >>>...
[ "def", "getlist", "(", "self", ",", "key", ")", ":", "value", "=", "self", ".", "get", "(", "key", ",", "[", "]", ")", "if", "value", "is", "None", "or", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "valu...
Returns a Storage value as a list. If the value is a list it will be returned as-is. If object is None, an empty list will be returned. Otherwise, `[value]` will be returned. Example output for a query string of `?x=abc&y=abc&y=def`:: >>> request = Storage() >>...
[ "Returns", "a", "Storage", "value", "as", "a", "list", "." ]
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/utils.py#L94-L120
Kopachris/seshet
seshet/utils.py
Storage.getfirst
def getfirst(self, key, default=None): """Returns the first value of a list or the value itself when given a `request.vars` style key. If the value is a list, its first item will be returned; otherwise, the value will be returned as-is. Example output for a query string of `?x=...
python
def getfirst(self, key, default=None): """Returns the first value of a list or the value itself when given a `request.vars` style key. If the value is a list, its first item will be returned; otherwise, the value will be returned as-is. Example output for a query string of `?x=...
[ "def", "getfirst", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "values", "=", "self", ".", "getlist", "(", "key", ")", "return", "values", "[", "0", "]", "if", "values", "else", "default" ]
Returns the first value of a list or the value itself when given a `request.vars` style key. If the value is a list, its first item will be returned; otherwise, the value will be returned as-is. Example output for a query string of `?x=abc&y=abc&y=def`:: >>> request = Stor...
[ "Returns", "the", "first", "value", "of", "a", "list", "or", "the", "value", "itself", "when", "given", "a", "request", ".", "vars", "style", "key", "." ]
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/utils.py#L122-L144
Kopachris/seshet
seshet/utils.py
Storage.getlast
def getlast(self, key, default=None): """Returns the last value of a list or value itself when given a `request.vars` style key. If the value is a list, the last item will be returned; otherwise, the value will be returned as-is. Simulated output with a query string of `?x=abc&...
python
def getlast(self, key, default=None): """Returns the last value of a list or value itself when given a `request.vars` style key. If the value is a list, the last item will be returned; otherwise, the value will be returned as-is. Simulated output with a query string of `?x=abc&...
[ "def", "getlast", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "values", "=", "self", ".", "getlist", "(", "key", ")", "return", "values", "[", "-", "1", "]", "if", "values", "else", "default" ]
Returns the last value of a list or value itself when given a `request.vars` style key. If the value is a list, the last item will be returned; otherwise, the value will be returned as-is. Simulated output with a query string of `?x=abc&y=abc&y=def`:: >>> request = Storage...
[ "Returns", "the", "last", "value", "of", "a", "list", "or", "value", "itself", "when", "given", "a", "request", ".", "vars", "style", "key", "." ]
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/utils.py#L146-L168
Kopachris/seshet
seshet/utils.py
KVStore.popitem
def popitem(self): """Unlike `dict.popitem()`, this is actually random""" all_items = self.items() removed_item = random.choice(all_items) self[removed_item[0]] = None return removed_item
python
def popitem(self): """Unlike `dict.popitem()`, this is actually random""" all_items = self.items() removed_item = random.choice(all_items) self[removed_item[0]] = None return removed_item
[ "def", "popitem", "(", "self", ")", ":", "all_items", "=", "self", ".", "items", "(", ")", "removed_item", "=", "random", ".", "choice", "(", "all_items", ")", "self", "[", "removed_item", "[", "0", "]", "]", "=", "None", "return", "removed_item" ]
Unlike `dict.popitem()`, this is actually random
[ "Unlike", "dict", ".", "popitem", "()", "this", "is", "actually", "random" ]
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/utils.py#L381-L386
luismasuelli/django-trackmodels-ritual
grimoire/django/tracked/reports.py
TrackingReport._serialize_value
def _serialize_value(self, value): """ Serialize values like date and time. Respect other values: :return: """ if isinstance(value, datetime.datetime): return value.strftime(self.datetime_format) elif isinstance(value, datetime.date): return value...
python
def _serialize_value(self, value): """ Serialize values like date and time. Respect other values: :return: """ if isinstance(value, datetime.datetime): return value.strftime(self.datetime_format) elif isinstance(value, datetime.date): return value...
[ "def", "_serialize_value", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "value", ".", "strftime", "(", "self", ".", "datetime_format", ")", "elif", "isinstance", "(", "value", ...
Serialize values like date and time. Respect other values: :return:
[ "Serialize", "values", "like", "date", "and", "time", ".", "Respect", "other", "values", ":", ":", "return", ":" ]
train
https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/reports.py#L48-L60
luismasuelli/django-trackmodels-ritual
grimoire/django/tracked/reports.py
TrackingReport.get_report_column_builders
def get_report_column_builders(self, request, model): """ Returns builders for column names and column values for the elements, being each element like this: 1. A header fetcher: will retrieve the title for the column. 2. A value fetcher: will retrieve the value for the col...
python
def get_report_column_builders(self, request, model): """ Returns builders for column names and column values for the elements, being each element like this: 1. A header fetcher: will retrieve the title for the column. 2. A value fetcher: will retrieve the value for the col...
[ "def", "get_report_column_builders", "(", "self", ",", "request", ",", "model", ")", ":", "meta", "=", "model", ".", "_meta", "field_names", "=", "set", "(", "field", ".", "name", "for", "field", "in", "meta", ".", "fields", ")", "list_report", "=", "sel...
Returns builders for column names and column values for the elements, being each element like this: 1. A header fetcher: will retrieve the title for the column. 2. A value fetcher: will retrieve the value for the column. :param model: model to analyze and fetch. :param requ...
[ "Returns", "builders", "for", "column", "names", "and", "column", "values", "for", "the", "elements", "being", "each", "element", "like", "this", ":", "1", ".", "A", "header", "fetcher", ":", "will", "retrieve", "the", "title", "for", "the", "column", ".",...
train
https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/reports.py#L98-L178
luismasuelli/django-trackmodels-ritual
grimoire/django/tracked/reports.py
TrackingReport.get_report_data_rows
def get_report_data_rows(self, request, queryset): """ Using the builders for the queryset model, iterates over the queryset to generate a result with headers and rows. This queryset must be the exact same received in the .process method, which tells us that this function should be c...
python
def get_report_data_rows(self, request, queryset): """ Using the builders for the queryset model, iterates over the queryset to generate a result with headers and rows. This queryset must be the exact same received in the .process method, which tells us that this function should be c...
[ "def", "get_report_data_rows", "(", "self", ",", "request", ",", "queryset", ")", ":", "model", "=", "queryset", ".", "model", "meta", "=", "model", ".", "_meta", "field_names", "=", "set", "(", "field", ".", "name", "for", "field", "in", "meta", ".", ...
Using the builders for the queryset model, iterates over the queryset to generate a result with headers and rows. This queryset must be the exact same received in the .process method, which tells us that this function should be called inside .process implementation. :param queryset: Provided...
[ "Using", "the", "builders", "for", "the", "queryset", "model", "iterates", "over", "the", "queryset", "to", "generate", "a", "result", "with", "headers", "and", "rows", ".", "This", "queryset", "must", "be", "the", "exact", "same", "received", "in", "the", ...
train
https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/reports.py#L180-L201
luismasuelli/django-trackmodels-ritual
grimoire/django/tracked/reports.py
TrackingReport.get_attachment_content
def get_attachment_content(self, request, queryset): """ Returns the generated file content. :param request: The request being processed. :param queryset: The model class being processed. :return: The report content (usually expressed in raw bytes but could be unicode as well). ...
python
def get_attachment_content(self, request, queryset): """ Returns the generated file content. :param request: The request being processed. :param queryset: The model class being processed. :return: The report content (usually expressed in raw bytes but could be unicode as well). ...
[ "def", "get_attachment_content", "(", "self", ",", "request", ",", "queryset", ")", ":", "return", "self", ".", "dump_report_content", "(", "request", ",", "self", ".", "get_report_data_rows", "(", "request", ",", "queryset", ")", ")" ]
Returns the generated file content. :param request: The request being processed. :param queryset: The model class being processed. :return: The report content (usually expressed in raw bytes but could be unicode as well).
[ "Returns", "the", "generated", "file", "content", ".", ":", "param", "request", ":", "The", "request", "being", "processed", ".", ":", "param", "queryset", ":", "The", "model", "class", "being", "processed", ".", ":", "return", ":", "The", "report", "conte...
train
https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/reports.py#L225-L233
luismasuelli/django-trackmodels-ritual
grimoire/django/tracked/reports.py
TrackingReport.process
def process(self, request, queryset, period): """ Will process the request and return an appropriate Response object. :param request: The request being processed. :param model: The model class being processed. :param period: The model being processed. :return: The respons...
python
def process(self, request, queryset, period): """ Will process the request and return an appropriate Response object. :param request: The request being processed. :param model: The model class being processed. :param period: The model being processed. :return: The respons...
[ "def", "process", "(", "self", ",", "request", ",", "queryset", ",", "period", ")", ":", "response", "=", "HttpResponse", "(", "content", "=", "self", ".", "get_attachment_content", "(", "request", ",", "queryset", ")", "or", "''", ",", "content_type", "="...
Will process the request and return an appropriate Response object. :param request: The request being processed. :param model: The model class being processed. :param period: The model being processed. :return: The response with the report.
[ "Will", "process", "the", "request", "and", "return", "an", "appropriate", "Response", "object", ".", ":", "param", "request", ":", "The", "request", "being", "processed", ".", ":", "param", "model", ":", "The", "model", "class", "being", "processed", ".", ...
train
https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/reports.py#L235-L248
luismasuelli/django-trackmodels-ritual
grimoire/django/tracked/reports.py
CSVReport.dump_report_content
def dump_report_content(self, request, result): """ Dumps the content to a string, suitable to being written on a file. :param result: The result being processed. :return: string """ output = StringIO() writer = csv.writer(output, **self.csv_kwargs) write...
python
def dump_report_content(self, request, result): """ Dumps the content to a string, suitable to being written on a file. :param result: The result being processed. :return: string """ output = StringIO() writer = csv.writer(output, **self.csv_kwargs) write...
[ "def", "dump_report_content", "(", "self", ",", "request", ",", "result", ")", ":", "output", "=", "StringIO", "(", ")", "writer", "=", "csv", ".", "writer", "(", "output", ",", "*", "*", "self", ".", "csv_kwargs", ")", "writer", ".", "writerows", "(",...
Dumps the content to a string, suitable to being written on a file. :param result: The result being processed. :return: string
[ "Dumps", "the", "content", "to", "a", "string", "suitable", "to", "being", "written", "on", "a", "file", ".", ":", "param", "result", ":", "The", "result", "being", "processed", ".", ":", "return", ":", "string" ]
train
https://github.com/luismasuelli/django-trackmodels-ritual/blob/ee0a6e07a5851ed477c9c1e3b9f8aafd9da35657/grimoire/django/tracked/reports.py#L300-L310
francois-vincent/clingon
clingon/clingon.py
clize
def clize(*args, **kwargs): """ Decorator has 2 usages: @clize def decorated(params): ... optional parameters aliases are autogenerated, conflicts are silently ignored. @clize(aliases) def decorated(params) ... where aliases is a dictionary, key=python parameter of decorat...
python
def clize(*args, **kwargs): """ Decorator has 2 usages: @clize def decorated(params): ... optional parameters aliases are autogenerated, conflicts are silently ignored. @clize(aliases) def decorated(params) ... where aliases is a dictionary, key=python parameter of decorat...
[ "def", "clize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "dict", "(", "(", "k", ".", "lower", "(", ")", ",", "v", ")", "for", "k", ",", "v", "in", "iteritems", "(", "kwargs", ")", ")", "class", "mycli", "(", "Clizer...
Decorator has 2 usages: @clize def decorated(params): ... optional parameters aliases are autogenerated, conflicts are silently ignored. @clize(aliases) def decorated(params) ... where aliases is a dictionary, key=python parameter of decorated function, value=tuple of aliases ...
[ "Decorator", "has", "2", "usages", ":", "@clize", "def", "decorated", "(", "params", ")", ":", "...", "optional", "parameters", "aliases", "are", "autogenerated", "conflicts", "are", "silently", "ignored", "." ]
train
https://github.com/francois-vincent/clingon/blob/afc9db073dbc72b2562ce3e444152986a555dcbf/clingon/clingon.py#L444-L472
francois-vincent/clingon
clingon/clingon.py
make_script
def make_script(python_script, target_path='', target_name='', user=False, make_link=False, force=False, remove=False, no_check_shebang=False, no_check_path=False): """v{VERSION} This script makes a command line script out of a python script. For example, 'clingon script.py' will copy or sym...
python
def make_script(python_script, target_path='', target_name='', user=False, make_link=False, force=False, remove=False, no_check_shebang=False, no_check_path=False): """v{VERSION} This script makes a command line script out of a python script. For example, 'clingon script.py' will copy or sym...
[ "def", "make_script", "(", "python_script", ",", "target_path", "=", "''", ",", "target_name", "=", "''", ",", "user", "=", "False", ",", "make_link", "=", "False", ",", "force", "=", "False", ",", "remove", "=", "False", ",", "no_check_shebang", "=", "F...
v{VERSION} This script makes a command line script out of a python script. For example, 'clingon script.py' will copy or symlink script.py (without the .py extension) to: - <python-exe-path>/script (default), - <target-path>/script if --target-path is specfied, - ~/bin/script if --user is specif...
[ "v", "{", "VERSION", "}", "This", "script", "makes", "a", "command", "line", "script", "out", "of", "a", "python", "script", ".", "For", "example", "clingon", "script", ".", "py", "will", "copy", "or", "symlink", "script", ".", "py", "(", "without", "t...
train
https://github.com/francois-vincent/clingon/blob/afc9db073dbc72b2562ce3e444152986a555dcbf/clingon/clingon.py#L485-L567
francois-vincent/clingon
clingon/clingon.py
Clizer.eval_option_value
def eval_option_value(self, option): """ Evaluates an option :param option: a string :return: an object of type str, bool, int, float or list """ try: value = eval(option, {}, {}) except (SyntaxError, NameError, TypeError): return option if...
python
def eval_option_value(self, option): """ Evaluates an option :param option: a string :return: an object of type str, bool, int, float or list """ try: value = eval(option, {}, {}) except (SyntaxError, NameError, TypeError): return option if...
[ "def", "eval_option_value", "(", "self", ",", "option", ")", ":", "try", ":", "value", "=", "eval", "(", "option", ",", "{", "}", ",", "{", "}", ")", "except", "(", "SyntaxError", ",", "NameError", ",", "TypeError", ")", ":", "return", "option", "if"...
Evaluates an option :param option: a string :return: an object of type str, bool, int, float or list
[ "Evaluates", "an", "option", ":", "param", "option", ":", "a", "string", ":", "return", ":", "an", "object", "of", "type", "str", "bool", "int", "float", "or", "list" ]
train
https://github.com/francois-vincent/clingon/blob/afc9db073dbc72b2562ce3e444152986a555dcbf/clingon/clingon.py#L147-L163
francois-vincent/clingon
clingon/clingon.py
Clizer.get_options_from_file
def get_options_from_file(self, options): """ Search and read a configuration file to override options. Available formats are python, yaml and json (file extension rules). By default, there is no configuration file and this method exits immediately. To define a configuration file...
python
def get_options_from_file(self, options): """ Search and read a configuration file to override options. Available formats are python, yaml and json (file extension rules). By default, there is no configuration file and this method exits immediately. To define a configuration file...
[ "def", "get_options_from_file", "(", "self", ",", "options", ")", ":", "options_file", "=", "self", ".", "python_options", ".", "get", "(", "'options_file'", ")", "or", "self", ".", "_variables", ".", "get", "(", "'OPTIONS_FILE'", ")", "if", "not", "options_...
Search and read a configuration file to override options. Available formats are python, yaml and json (file extension rules). By default, there is no configuration file and this method exits immediately. To define a configuration file, use: - variable OPTIONS_FILE, - optional spe...
[ "Search", "and", "read", "a", "configuration", "file", "to", "override", "options", ".", "Available", "formats", "are", "python", "yaml", "and", "json", "(", "file", "extension", "rules", ")", ".", "By", "default", "there", "is", "no", "configuration", "file...
train
https://github.com/francois-vincent/clingon/blob/afc9db073dbc72b2562ce3e444152986a555dcbf/clingon/clingon.py#L173-L215
francois-vincent/clingon
clingon/clingon.py
Clizer._eval_variables
def _eval_variables(self): """evaluates callable _variables """ for k, v in listitems(self._variables): self._variables[k] = v() if hasattr(v, '__call__') else v
python
def _eval_variables(self): """evaluates callable _variables """ for k, v in listitems(self._variables): self._variables[k] = v() if hasattr(v, '__call__') else v
[ "def", "_eval_variables", "(", "self", ")", ":", "for", "k", ",", "v", "in", "listitems", "(", "self", ".", "_variables", ")", ":", "self", ".", "_variables", "[", "k", "]", "=", "v", "(", ")", "if", "hasattr", "(", "v", ",", "'__call__'", ")", "...
evaluates callable _variables
[ "evaluates", "callable", "_variables" ]
train
https://github.com/francois-vincent/clingon/blob/afc9db073dbc72b2562ce3e444152986a555dcbf/clingon/clingon.py#L217-L221
francois-vincent/clingon
clingon/clingon.py
Clizer.start
def start(self, param_string=None): """ Parses command line parameters A string can be passed to simulate a cli for test purpose """ external_opt = {} self.get_options_from_environ(external_opt) self.get_options_from_file(external_opt) # construct optional arg...
python
def start(self, param_string=None): """ Parses command line parameters A string can be passed to simulate a cli for test purpose """ external_opt = {} self.get_options_from_environ(external_opt) self.get_options_from_file(external_opt) # construct optional arg...
[ "def", "start", "(", "self", ",", "param_string", "=", "None", ")", ":", "external_opt", "=", "{", "}", "self", ".", "get_options_from_environ", "(", "external_opt", ")", "self", ".", "get_options_from_file", "(", "external_opt", ")", "# construct optional args, r...
Parses command line parameters A string can be passed to simulate a cli for test purpose
[ "Parses", "command", "line", "parameters", "A", "string", "can", "be", "passed", "to", "simulate", "a", "cli", "for", "test", "purpose" ]
train
https://github.com/francois-vincent/clingon/blob/afc9db073dbc72b2562ce3e444152986a555dcbf/clingon/clingon.py#L232-L336
francois-vincent/clingon
clingon/clingon.py
Clizer._print_help
def _print_help(self): """ Help is automatically generated from the __doc__ of the subclass if present and from the names of the args of run(). Therefore args names selection is more important than ever here ! """ options = self._print_usage('\n ', file=sys.stdout) ...
python
def _print_help(self): """ Help is automatically generated from the __doc__ of the subclass if present and from the names of the args of run(). Therefore args names selection is more important than ever here ! """ options = self._print_usage('\n ', file=sys.stdout) ...
[ "def", "_print_help", "(", "self", ")", ":", "options", "=", "self", ".", "_print_usage", "(", "'\\n '", ",", "file", "=", "sys", ".", "stdout", ")", "if", "self", ".", "docstring", ":", "print", "(", ")", "try", ":", "doc_string", "=", "self", ".",...
Help is automatically generated from the __doc__ of the subclass if present and from the names of the args of run(). Therefore args names selection is more important than ever here !
[ "Help", "is", "automatically", "generated", "from", "the", "__doc__", "of", "the", "subclass", "if", "present", "and", "from", "the", "names", "of", "the", "args", "of", "run", "()", ".", "Therefore", "args", "names", "selection", "is", "more", "important", ...
train
https://github.com/francois-vincent/clingon/blob/afc9db073dbc72b2562ce3e444152986a555dcbf/clingon/clingon.py#L410-L441
formwork-io/lazarus
lazarus/_util.py
defer
def defer(callable): '''Defers execution of the callable to a thread. For example: >>> def foo(): ... print('bar') >>> join = defer(foo) >>> join() ''' t = threading.Thread(target=callable) t.start() return t.join
python
def defer(callable): '''Defers execution of the callable to a thread. For example: >>> def foo(): ... print('bar') >>> join = defer(foo) >>> join() ''' t = threading.Thread(target=callable) t.start() return t.join
[ "def", "defer", "(", "callable", ")", ":", "t", "=", "threading", ".", "Thread", "(", "target", "=", "callable", ")", "t", ".", "start", "(", ")", "return", "t", ".", "join" ]
Defers execution of the callable to a thread. For example: >>> def foo(): ... print('bar') >>> join = defer(foo) >>> join()
[ "Defers", "execution", "of", "the", "callable", "to", "a", "thread", "." ]
train
https://github.com/formwork-io/lazarus/blob/b2b6120fe06d69c23b4f41d55b6d71860a9fdeaa/lazarus/_util.py#L11-L23
formwork-io/lazarus
lazarus/_util.py
close_fds
def close_fds(): '''Close extraneous file descriptors. On Linux, close everything but stdin, stdout, and stderr. On Mac, close stdin, stdout, and stderr and everything owned by our user id. ''' def close(fd): with ignored(OSError): os.close(fd) if sys.platform == 'linux': ...
python
def close_fds(): '''Close extraneous file descriptors. On Linux, close everything but stdin, stdout, and stderr. On Mac, close stdin, stdout, and stderr and everything owned by our user id. ''' def close(fd): with ignored(OSError): os.close(fd) if sys.platform == 'linux': ...
[ "def", "close_fds", "(", ")", ":", "def", "close", "(", "fd", ")", ":", "with", "ignored", "(", "OSError", ")", ":", "os", ".", "close", "(", "fd", ")", "if", "sys", ".", "platform", "==", "'linux'", ":", "fd_dir", "=", "'/proc/self/fd'", "fds", "=...
Close extraneous file descriptors. On Linux, close everything but stdin, stdout, and stderr. On Mac, close stdin, stdout, and stderr and everything owned by our user id.
[ "Close", "extraneous", "file", "descriptors", "." ]
train
https://github.com/formwork-io/lazarus/blob/b2b6120fe06d69c23b4f41d55b6d71860a9fdeaa/lazarus/_util.py#L48-L75
formwork-io/lazarus
lazarus/_util.py
do_over
def do_over(): '''Calls :py:func:`os.exec` with executable and args derived from sys.''' path = sys.executable args = [path] + sys.argv # And the rest, after a sudden wet thud, was silence. os.execv(path, args)
python
def do_over(): '''Calls :py:func:`os.exec` with executable and args derived from sys.''' path = sys.executable args = [path] + sys.argv # And the rest, after a sudden wet thud, was silence. os.execv(path, args)
[ "def", "do_over", "(", ")", ":", "path", "=", "sys", ".", "executable", "args", "=", "[", "path", "]", "+", "sys", ".", "argv", "# And the rest, after a sudden wet thud, was silence.", "os", ".", "execv", "(", "path", ",", "args", ")" ]
Calls :py:func:`os.exec` with executable and args derived from sys.
[ "Calls", ":", "py", ":", "func", ":", "os", ".", "exec", "with", "executable", "and", "args", "derived", "from", "sys", "." ]
train
https://github.com/formwork-io/lazarus/blob/b2b6120fe06d69c23b4f41d55b6d71860a9fdeaa/lazarus/_util.py#L78-L84
HazardDede/dictmentor
dictmentor/base.py
DictMentor.bind
def bind(self, extension: Extension) -> 'DictMentor': """ Add any predefined or custom extension. Args: extension: Extension to add to the processor. Returns: The DictMentor itself for chaining. """ if not Extension.is_valid_extension(extension):...
python
def bind(self, extension: Extension) -> 'DictMentor': """ Add any predefined or custom extension. Args: extension: Extension to add to the processor. Returns: The DictMentor itself for chaining. """ if not Extension.is_valid_extension(extension):...
[ "def", "bind", "(", "self", ",", "extension", ":", "Extension", ")", "->", "'DictMentor'", ":", "if", "not", "Extension", ".", "is_valid_extension", "(", "extension", ")", ":", "raise", "ValueError", "(", "\"Cannot bind extension due to missing interface requirements\...
Add any predefined or custom extension. Args: extension: Extension to add to the processor. Returns: The DictMentor itself for chaining.
[ "Add", "any", "predefined", "or", "custom", "extension", "." ]
train
https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/base.py#L31-L45
HazardDede/dictmentor
dictmentor/base.py
DictMentor.augment
def augment(self, dct: NonAugmentedDict, document: Optional[YamlDocument] = None) -> AugmentedDict: """ Augments the given dictionary by using all the bound extensions. Args: dct: Dictionary to augment. document: The document the dictionary was loaded fro...
python
def augment(self, dct: NonAugmentedDict, document: Optional[YamlDocument] = None) -> AugmentedDict: """ Augments the given dictionary by using all the bound extensions. Args: dct: Dictionary to augment. document: The document the dictionary was loaded fro...
[ "def", "augment", "(", "self", ",", "dct", ":", "NonAugmentedDict", ",", "document", ":", "Optional", "[", "YamlDocument", "]", "=", "None", ")", "->", "AugmentedDict", ":", "Validator", ".", "instance_of", "(", "dict", ",", "raise_ex", "=", "True", ",", ...
Augments the given dictionary by using all the bound extensions. Args: dct: Dictionary to augment. document: The document the dictionary was loaded from. Returns: The augmented dictionary.
[ "Augments", "the", "given", "dictionary", "by", "using", "all", "the", "bound", "extensions", "." ]
train
https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/base.py#L47-L78
HazardDede/dictmentor
dictmentor/base.py
DictMentor._load_plain_yaml
def _load_plain_yaml(cls, _yaml: YamlDocument) -> Any: """ Will just load the yaml without executing any extensions. You will get the plain dictionary without augmentation. It is equivalent to just perform `yaml.safe_load`. Besides that you can specify a stream, a file or just a string t...
python
def _load_plain_yaml(cls, _yaml: YamlDocument) -> Any: """ Will just load the yaml without executing any extensions. You will get the plain dictionary without augmentation. It is equivalent to just perform `yaml.safe_load`. Besides that you can specify a stream, a file or just a string t...
[ "def", "_load_plain_yaml", "(", "cls", ",", "_yaml", ":", "YamlDocument", ")", "->", "Any", ":", "if", "Validator", ".", "is_stream", "(", "yaml_", "=", "_yaml", ")", ":", "return", "yaml", ".", "safe_load", "(", "_yaml", ")", "if", "Validator", ".", "...
Will just load the yaml without executing any extensions. You will get the plain dictionary without augmentation. It is equivalent to just perform `yaml.safe_load`. Besides that you can specify a stream, a file or just a string that contains yaml/json data. Examples: >>> jstr = '{"a...
[ "Will", "just", "load", "the", "yaml", "without", "executing", "any", "extensions", ".", "You", "will", "get", "the", "plain", "dictionary", "without", "augmentation", ".", "It", "is", "equivalent", "to", "just", "perform", "yaml", ".", "safe_load", ".", "Be...
train
https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/base.py#L81-L108
HazardDede/dictmentor
dictmentor/base.py
DictMentor.load_yaml
def load_yaml(self, _yaml: YamlDocument) -> AugmentedDict: """ Loads a partial yaml and augments it. A partial yaml in this context is a yaml that is syntactically correct, but is not yet complete in terms of content. The yaml will be completed by augmenting with some external resources ...
python
def load_yaml(self, _yaml: YamlDocument) -> AugmentedDict: """ Loads a partial yaml and augments it. A partial yaml in this context is a yaml that is syntactically correct, but is not yet complete in terms of content. The yaml will be completed by augmenting with some external resources ...
[ "def", "load_yaml", "(", "self", ",", "_yaml", ":", "YamlDocument", ")", "->", "AugmentedDict", ":", "return", "self", ".", "augment", "(", "self", ".", "_load_plain_yaml", "(", "_yaml", ")", ",", "document", "=", "_yaml", ")" ]
Loads a partial yaml and augments it. A partial yaml in this context is a yaml that is syntactically correct, but is not yet complete in terms of content. The yaml will be completed by augmenting with some external resources and/or executing so called extensions. Args: _yaml...
[ "Loads", "a", "partial", "yaml", "and", "augments", "it", ".", "A", "partial", "yaml", "in", "this", "context", "is", "a", "yaml", "that", "is", "syntactically", "correct", "but", "is", "not", "yet", "complete", "in", "terms", "of", "content", ".", "The"...
train
https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/base.py#L110-L124
fmenabe/python-clif
examples/backup/lib/types.py
Date
def Date(value): """Custom type for managing dates in the command-line.""" from datetime import datetime try: return datetime(*reversed([int(val) for val in value.split('/')])) except Exception as err: raise argparse.ArgumentTypeError("invalid date '%s'" % value)
python
def Date(value): """Custom type for managing dates in the command-line.""" from datetime import datetime try: return datetime(*reversed([int(val) for val in value.split('/')])) except Exception as err: raise argparse.ArgumentTypeError("invalid date '%s'" % value)
[ "def", "Date", "(", "value", ")", ":", "from", "datetime", "import", "datetime", "try", ":", "return", "datetime", "(", "*", "reversed", "(", "[", "int", "(", "val", ")", "for", "val", "in", "value", ".", "split", "(", "'/'", ")", "]", ")", ")", ...
Custom type for managing dates in the command-line.
[ "Custom", "type", "for", "managing", "dates", "in", "the", "command", "-", "line", "." ]
train
https://github.com/fmenabe/python-clif/blob/7d74b344337567f7951046406510a980afd7ee97/examples/backup/lib/types.py#L11-L17
the01/python-paps
examples/measure/echo_client.py
create
def create(clients_num, clients_host, clients_port, people_num, throttle): """ Prepare clients to execute :return: Modules to execute, cmd line function :rtype: list[WrapperClient], (str, object) -> str | None """ res = [] for number in range(clients_num): sc = EchoClient({ ...
python
def create(clients_num, clients_host, clients_port, people_num, throttle): """ Prepare clients to execute :return: Modules to execute, cmd line function :rtype: list[WrapperClient], (str, object) -> str | None """ res = [] for number in range(clients_num): sc = EchoClient({ ...
[ "def", "create", "(", "clients_num", ",", "clients_host", ",", "clients_port", ",", "people_num", ",", "throttle", ")", ":", "res", "=", "[", "]", "for", "number", "in", "range", "(", "clients_num", ")", ":", "sc", "=", "EchoClient", "(", "{", "'id'", ...
Prepare clients to execute :return: Modules to execute, cmd line function :rtype: list[WrapperClient], (str, object) -> str | None
[ "Prepare", "clients", "to", "execute" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/examples/measure/echo_client.py#L114-L139
the01/python-paps
examples/measure/echo_client.py
EchoClient._packet_loop
def _packet_loop(self): """ Packet processing loop :rtype: None """ while self._is_running: # Only wait if there are no more packets in the inbox if self.inbox.empty() \ and not self.new_packet.wait(self._packet_timeout): ...
python
def _packet_loop(self): """ Packet processing loop :rtype: None """ while self._is_running: # Only wait if there are no more packets in the inbox if self.inbox.empty() \ and not self.new_packet.wait(self._packet_timeout): ...
[ "def", "_packet_loop", "(", "self", ")", ":", "while", "self", ".", "_is_running", ":", "# Only wait if there are no more packets in the inbox", "if", "self", ".", "inbox", ".", "empty", "(", ")", "and", "not", "self", ".", "new_packet", ".", "wait", "(", "sel...
Packet processing loop :rtype: None
[ "Packet", "processing", "loop" ]
train
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/examples/measure/echo_client.py#L34-L53
maxweisspoker/simplebitcoinfuncs
simplebitcoinfuncs/miscfuncs.py
strlify
def strlify(a): ''' Used to turn hexlify() into hex string. Does nothing in Python 2, but is necessary for Python 3, so that all inputs and outputs are always the same encoding. Most of the time it doesn't matter, but some functions in Python 3 brick when they get bytes instead of a string, so...
python
def strlify(a): ''' Used to turn hexlify() into hex string. Does nothing in Python 2, but is necessary for Python 3, so that all inputs and outputs are always the same encoding. Most of the time it doesn't matter, but some functions in Python 3 brick when they get bytes instead of a string, so...
[ "def", "strlify", "(", "a", ")", ":", "if", "a", "==", "b'b'", "or", "a", "==", "'b'", ":", "return", "'b'", "return", "str", "(", "a", ")", ".", "rstrip", "(", "\"'\"", ")", ".", "replace", "(", "\"b'\"", ",", "\"\"", ",", "1", ")", ".", "re...
Used to turn hexlify() into hex string. Does nothing in Python 2, but is necessary for Python 3, so that all inputs and outputs are always the same encoding. Most of the time it doesn't matter, but some functions in Python 3 brick when they get bytes instead of a string, so it's safer to just strl...
[ "Used", "to", "turn", "hexlify", "()", "into", "hex", "string", "." ]
train
https://github.com/maxweisspoker/simplebitcoinfuncs/blob/ad332433dfcc067e86d2e77fa0c8f1a27daffb63/simplebitcoinfuncs/miscfuncs.py#L24-L67
maxweisspoker/simplebitcoinfuncs
simplebitcoinfuncs/miscfuncs.py
dechex
def dechex(num,zfill=0): ''' Simple integer to hex converter. The zfill is the number of bytes, even though the input is a hex string, which means that the actual zfill is 2x what you might initially think it would be. For example: >>> dechex(4,2) '0004' ''' if not isitint(num...
python
def dechex(num,zfill=0): ''' Simple integer to hex converter. The zfill is the number of bytes, even though the input is a hex string, which means that the actual zfill is 2x what you might initially think it would be. For example: >>> dechex(4,2) '0004' ''' if not isitint(num...
[ "def", "dechex", "(", "num", ",", "zfill", "=", "0", ")", ":", "if", "not", "isitint", "(", "num", ")", ":", "raise", "TypeError", "(", "\"Input must be integer/long.\"", ")", "o", "=", "hex", "(", "num", ")", ".", "lstrip", "(", "\"0x\"", ")", ".", ...
Simple integer to hex converter. The zfill is the number of bytes, even though the input is a hex string, which means that the actual zfill is 2x what you might initially think it would be. For example: >>> dechex(4,2) '0004'
[ "Simple", "integer", "to", "hex", "converter", "." ]
train
https://github.com/maxweisspoker/simplebitcoinfuncs/blob/ad332433dfcc067e86d2e77fa0c8f1a27daffb63/simplebitcoinfuncs/miscfuncs.py#L106-L136
maxweisspoker/simplebitcoinfuncs
simplebitcoinfuncs/miscfuncs.py
normalize_input
def normalize_input(input,preferunicodeoverstring=False,nfconly=False): ''' This looks dirty as crap, but the try/catch failure series goes in the correct order and it's a lot easier to use this most of the time, and it works for every situation I needed to use it in. That said, I'm kind of hoping n...
python
def normalize_input(input,preferunicodeoverstring=False,nfconly=False): ''' This looks dirty as crap, but the try/catch failure series goes in the correct order and it's a lot easier to use this most of the time, and it works for every situation I needed to use it in. That said, I'm kind of hoping n...
[ "def", "normalize_input", "(", "input", ",", "preferunicodeoverstring", "=", "False", ",", "nfconly", "=", "False", ")", ":", "if", "nfconly", ":", "try", ":", "return", "unhexlify", "(", "hexlify", "(", "unicodedata", ".", "normalize", "(", "'NFC'", ",", ...
This looks dirty as crap, but the try/catch failure series goes in the correct order and it's a lot easier to use this most of the time, and it works for every situation I needed to use it in. That said, I'm kind of hoping nobody ever sees this...
[ "This", "looks", "dirty", "as", "crap", "but", "the", "try", "/", "catch", "failure", "series", "goes", "in", "the", "correct", "order", "and", "it", "s", "a", "lot", "easier", "to", "use", "this", "most", "of", "the", "time", "and", "it", "works", "...
train
https://github.com/maxweisspoker/simplebitcoinfuncs/blob/ad332433dfcc067e86d2e77fa0c8f1a27daffb63/simplebitcoinfuncs/miscfuncs.py#L139-L166
selenol/selenol-python
selenol_python/params.py
selenol_params
def selenol_params(**kwargs): """Decorate request parameters to transform them into Selenol objects.""" def params_decorator(func): """Param decorator. :param f: Function to decorate, typically on_request. """ def service_function_wrapper(service, message): """Wrap f...
python
def selenol_params(**kwargs): """Decorate request parameters to transform them into Selenol objects.""" def params_decorator(func): """Param decorator. :param f: Function to decorate, typically on_request. """ def service_function_wrapper(service, message): """Wrap f...
[ "def", "selenol_params", "(", "*", "*", "kwargs", ")", ":", "def", "params_decorator", "(", "func", ")", ":", "\"\"\"Param decorator.\n\n :param f: Function to decorate, typically on_request.\n \"\"\"", "def", "service_function_wrapper", "(", "service", ",", "me...
Decorate request parameters to transform them into Selenol objects.
[ "Decorate", "request", "parameters", "to", "transform", "them", "into", "Selenol", "objects", "." ]
train
https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/params.py#L21-L37
selenol/selenol-python
selenol_python/params.py
_get_value
def _get_value(data_structure, key): """Return the value of a data_structure given a path. :param data_structure: Dictionary, list or subscriptable object. :param key: Array with the defined path ordered. """ if len(key) == 0: raise KeyError() value = data_structure[key[0]] if len(k...
python
def _get_value(data_structure, key): """Return the value of a data_structure given a path. :param data_structure: Dictionary, list or subscriptable object. :param key: Array with the defined path ordered. """ if len(key) == 0: raise KeyError() value = data_structure[key[0]] if len(k...
[ "def", "_get_value", "(", "data_structure", ",", "key", ")", ":", "if", "len", "(", "key", ")", "==", "0", ":", "raise", "KeyError", "(", ")", "value", "=", "data_structure", "[", "key", "[", "0", "]", "]", "if", "len", "(", "key", ")", ">", "1",...
Return the value of a data_structure given a path. :param data_structure: Dictionary, list or subscriptable object. :param key: Array with the defined path ordered.
[ "Return", "the", "value", "of", "a", "data_structure", "given", "a", "path", "." ]
train
https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/params.py#L40-L51
selenol/selenol-python
selenol_python/params.py
get_value_from_session
def get_value_from_session(key): """Get a session value from the path specifed. :param key: Array that defines the path of the value inside the message. """ def value_from_session_function(service, message): """Actual implementation of get_value_from_session function. :param service: S...
python
def get_value_from_session(key): """Get a session value from the path specifed. :param key: Array that defines the path of the value inside the message. """ def value_from_session_function(service, message): """Actual implementation of get_value_from_session function. :param service: S...
[ "def", "get_value_from_session", "(", "key", ")", ":", "def", "value_from_session_function", "(", "service", ",", "message", ")", ":", "\"\"\"Actual implementation of get_value_from_session function.\n\n :param service: SelenolService object.\n :param message: SelenolMessag...
Get a session value from the path specifed. :param key: Array that defines the path of the value inside the message.
[ "Get", "a", "session", "value", "from", "the", "path", "specifed", "." ]
train
https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/params.py#L54-L66